htmlize-release-1.59/0000775000175000017500000000000015037657164014414 5ustar dogslegdogsleghtmlize-release-1.59/Makefile0000664000175000017500000000342115037657164016054 0ustar dogslegdogsleg-include .config.mk PKG = htmlize ELS = $(PKG).el ELCS = $(ELS:.el=.elc) HTML = $(ELS:.el=.el.html) DEPS = EMACS ?= emacs EMACS_ARGS ?= LOAD_PATH ?= $(addprefix -L ../,$(DEPS)) LOAD_PATH += -L . all: lisp help: $(info make all - generate byte-code and autoloads) $(info make lisp - generate byte-code and autoloads) $(info make redo - re-generate byte-code and autoloads) $(info make htmlize - htmlize htmlize.el) $(info make clean - remove generated files) @printf "\n" redo: clean lisp lisp: $(ELCS) loaddefs check-declare loaddefs: $(PKG)-autoloads.el %.elc: %.el @printf "Compiling $<\n" @$(EMACS) -Q --batch $(EMACS_ARGS) $(LOAD_PATH) -f batch-byte-compile $< check-declare: @printf " Checking function declarations\n" @$(EMACS) -Q --batch $(EMACS_ARGS) $(LOAD_PATH) \ --eval "(check-declare-directory default-directory)" %.el.html: %.el @$(EMACS) -Q $(EMACS_ARGS) $(LOAD_PATH) \ -l htmlize --eval "(progn (htmlize-file \"$<\") (kill-emacs))" htmlize: $(HTML) CLEAN = $(ELCS) $(PKG)-autoloads.el clean: @printf " Cleaning...\n" @rm -rf $(CLEAN) $(PKG)-autoloads.el: $(ELS) @printf " Creating $@\n" @$(EMACS) -Q --batch -l autoload -l cl-lib --eval "\ (let ((file (expand-file-name \"$@\"))\ (autoload-timestamps nil) \ (backup-inhibited t)\ (version-control 'never)\ (coding-system-for-write 'utf-8-emacs-unix))\ (write-region (autoload-rubric file \"package\" nil) nil file nil 'silent)\ (cl-letf (((symbol-function 'progress-reporter-do-update) (lambda (&rest _)))\ ((symbol-function 'progress-reporter-done) (lambda (_))))\ (let ((generated-autoload-file file))\ (update-directory-autoloads default-directory))))" \ 2>&1 | sed "/^Package autoload is deprecated$$/d" htmlize-release-1.59/htmlize.el.html0000664000175000017500000044174015037657164017367 0ustar dogslegdogsleg htmlize.el
;;; htmlize.el --- Convert buffer text and decorations to HTML  -*- lexical-binding: t -*-

;; Copyright (C) 1997-2003,2005,2006,2009,2011,2012,2014,2017,2018,2020 Hrvoje Niksic

;; Author: Hrvoje Niksic <hniksic@gmail.com>
;; Homepage: https://github.com/emacsorphanage/htmlize
;; Keywords: hypermedia, extensions
;; Version: 1.58
;; Package-Requires: ((emacs "26.1"))

;; SPDX-License-Identifier: GPL-3.0-or-later

;; This file is free software: you can redistribute it and/or modify
;; it under the terms of the GNU General Public License as published
;; by the Free Software Foundation, either version 3 of the License,
;; or (at your option) any later version.
;;
;; This file is distributed in the hope that it will be useful,
;; but WITHOUT ANY WARRANTY; without even the implied warranty of
;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
;; GNU General Public License for more details.
;;
;; You should have received a copy of the GNU General Public License
;; along with this file.  If not, see <https://www.gnu.org/licenses/>.

;;; Commentary:

;; This package converts the buffer text and the associated
;; decorations to HTML.

;; To use it, just switch to the buffer you want HTML-ized and type
;; `M-x htmlize-buffer'.  You will be switched to a new buffer that
;; contains the resulting HTML code.  You can edit and inspect this
;; buffer, or you can just save it with C-x C-w.  `M-x htmlize-file'
;; will find a file, fontify it, and save the HTML version in
;; FILE.html, without any additional intervention.  `M-x
;; htmlize-many-files' allows you to htmlize any number of files in
;; the same manner.  `M-x htmlize-many-files-dired' does the same for
;; files marked in a dired buffer.

;; Htmlize supports three types of HTML output, selected by setting
;; `htmlize-output-type': `css', `inline-css', and `font'.  In `css'
;; mode, htmlize uses cascading style sheets to specify colors; it
;; generates classes that correspond to Emacs faces and uses <span
;; class=FACE>...</span> to color parts of text.  In this mode, the
;; produced HTML is valid under the 4.01 strict DTD, as confirmed by
;; the W3C validator.  `inline-css' is like `css', except the CSS is
;; put directly in the STYLE attribute of the SPAN element, making it
;; possible to paste the generated HTML into existing HTML documents.
;; In `font' mode, htmlize uses <font color="...">...</font> to
;; colorize HTML, which is not standard-compliant, but works better in
;; older browsers.  `css' mode is the default.

;; You can also use htmlize from your Emacs Lisp code.  When called
;; non-interactively, `htmlize-buffer' and `htmlize-region' will
;; return the resulting HTML buffer, but will not change current
;; buffer or move the point.  Htmlize will do its best to work on
;; non-windowing Emacs sessions but the result will be limited to
;; colors supported by the terminal.

;; The latest version is available at:
;;
;;        <https://github.com/emacsorphanage/htmlize>

;; Thanks go to the many people who have sent reports and contributed
;; comments, suggestions, and fixes.  They include Ron Gut, Bob
;; Weiner, Toni Drabik, Peter Breton, Ville Skytta, Thomas Vogels,
;; Juri Linkov, Maciek Pasternacki, and many others.

;; User quotes: "You sir, are a sick, sick, _sick_ person. :)"
;;                  -- Bill Perry, author of Emacs/W3


;;; Code: (require 'cl-lib) (defconst htmlize-version "1.58") (defgroup htmlize nil "Convert buffer text and faces to HTML." :group 'hypermedia) (defcustom htmlize-head-tags "" "Additional tags to insert within HEAD of the generated document." :type 'string :group 'htmlize) (defcustom htmlize-output-type 'css "Output type of generated HTML, one of `css', `inline-css', or `font'. When set to `css' (the default), htmlize will generate a style sheet with description of faces, and use it in the HTML document, specifying the faces in the actual text with <span class=\"FACE\">. When set to `inline-css', the style will be generated as above, but placed directly in the STYLE attribute of the span ELEMENT: <span style=\"STYLE\">. This makes it easier to paste the resulting HTML to other documents. When set to `font', the properties will be set using layout tags <font>, <b>, <i>, <u>, and <strike>. `css' output is normally preferred, but `font' is still useful for supporting old, pre-CSS browsers, and both `inline-css' and `font' for easier embedding of colorized text in foreign HTML documents (no style sheet to carry around)." :type '(choice (const css) (const inline-css) (const font)) :group 'htmlize) (defcustom htmlize-use-images t "Whether htmlize generates `img' for images attached to buffer contents." :type 'boolean :group 'htmlize) (defcustom htmlize-force-inline-images nil "Non-nil means generate all images inline using data URLs. Normally htmlize converts image descriptors with :file properties to relative URIs, and those with :data properties to data URIs. With this flag set, the images specified as a file name are loaded into memory and embedded in the HTML as data URIs." :type 'boolean :group 'htmlize) (defcustom htmlize-max-alt-text 100 "Maximum size of text to use as ALT text in images. Normally when htmlize encounters text covered by the `display' property that specifies an image, it generates an `alt' attribute containing the original text. If the text is larger than `htmlize-max-alt-text' characters, this will not be done." :type 'integer :group 'htmlize) (defcustom htmlize-transform-image 'htmlize-default-transform-image "Function called to modify the image descriptor. The function is called with the image descriptor found in the buffer and the text the image is supposed to replace. It should return a (possibly different) image descriptor property list or a replacement string to use instead of of the original buffer text. Returning nil is the same as returning the original text." :type 'boolean :group 'htmlize) (defcustom htmlize-generate-hyperlinks t "Non-nil means auto-generate the links from URLs and mail addresses in buffer. This is on by default; set it to nil if you don't want htmlize to autogenerate such links. Note that this option only turns off automatic search for contents that looks like URLs and converting them to links. It has no effect on whether htmlize respects the `htmlize-link' property." :type 'boolean :group 'htmlize) (defcustom htmlize-hyperlink-style " a { color: inherit; background-color: inherit; font: inherit; text-decoration: inherit; } a:hover { text-decoration: underline; } " "The CSS style used for hyperlinks when in CSS mode." :type 'string :group 'htmlize) (defcustom htmlize-replace-form-feeds t "Non-nil means replace form feeds in source code with HTML separators. Form feeds are the ^L characters at line beginnings that are sometimes used to separate sections of source code. If this variable is set to `t', form feed characters are replaced with the <hr> separator. If this is a string, it specifies the replacement to use. Note that <pre> is temporarily closed before the separator is inserted, so the default replacement is effectively \"</pre><hr /><pre>\". If you specify another replacement, don't forget to close and reopen the <pre> if you want the output to remain valid HTML. If you need more elaborate processing, set this to nil and use htmlize-after-hook." :type 'boolean :group 'htmlize) (defcustom htmlize-html-charset nil "The charset declared by the resulting HTML documents. When non-nil, causes htmlize to insert the following in the HEAD section of the generated HTML: <meta http-equiv=\"Content-Type\" content=\"text/html; charset=CHARSET\"> where CHARSET is the value you've set for htmlize-html-charset. Valid charsets are defined by MIME and include strings like \"iso-8859-1\", \"iso-8859-15\", \"utf-8\", etc. If you are using non-Latin-1 charsets, you might need to set this for your documents to render correctly. Also, the W3C validator requires submitted HTML documents to declare a charset. So if you care about validation, you can use this to prevent the validator from bitching. Needless to say, if you set this, you should actually make sure that the buffer is in the encoding you're claiming it is in. (This is normally achieved by using the correct file coding system for the buffer.) If you don't understand what that means, you should probably leave this option in its default setting." :type '(choice (const :tag "Unset" nil) string) :group 'htmlize) (defcustom htmlize-convert-nonascii-to-entities t "Whether non-ASCII characters should be converted to HTML entities. When this is non-nil, characters with codes in the 128-255 range will be considered Latin 1 and rewritten as \"&#CODE;\". Characters with codes above 255 will be converted to \"&#UCS;\", where UCS denotes the Unicode code point of the character. If the code point cannot be determined, the character will be copied unchanged, as would be the case if the option were nil. When the option is nil, the non-ASCII characters are copied to HTML without modification. In that case, the web server and/or the browser must be set to understand the encoding that was used when saving the buffer. (You might also want to specify it by setting `htmlize-html-charset'.) Note that in an HTML entity \"&#CODE;\", CODE is always a UCS code point, which has nothing to do with the charset the page is in. For example, \"&#169;\" *always* refers to the copyright symbol, regardless of charset specified by the META tag or the charset sent by the HTTP server. In other words, \"&#169;\" is exactly equivalent to \"&copy;\". For most people htmlize will work fine with this option left at the default setting; don't change it unless you know what you're doing." :type 'sexp :group 'htmlize) (defcustom htmlize-ignore-face-size 'absolute "Whether face size should be ignored when generating HTML. If this is nil, face sizes are used. If set to t, sizes are ignored If set to `absolute', only absolute size specifications are ignored. Please note that font sizes only work with CSS-based output types." :type '(choice (const :tag "Don't ignore" nil) (const :tag "Ignore all" t) (const :tag "Ignore absolute" absolute)) :group 'htmlize) (defcustom htmlize-css-name-prefix "" "The prefix used for CSS names. The CSS names that htmlize generates from face names are often too generic for CSS files; for example, `font-lock-type-face' is transformed to `type'. Use this variable to add a prefix to the generated names. The string \"htmlize-\" is an example of a reasonable prefix." :type 'string :group 'htmlize) (defcustom htmlize-use-rgb-txt t "Whether `rgb.txt' should be used to convert color names to RGB. This conversion means determining, for instance, that the color \"IndianRed\" corresponds to the (205, 92, 92) RGB triple. `rgb.txt' is the X color database that maps hundreds of color names to such RGB triples. When this variable is non-nil, `htmlize' uses `rgb.txt' to look up color names. If this variable is nil, htmlize queries Emacs for RGB components of colors using `color-instance-rgb-components' and `color-values'. This can yield incorrect results on non-true-color displays. If the `rgb.txt' file is not found (which will be the case if you're running Emacs on non-X11 systems), this option is ignored." :type 'boolean :group 'htmlize) (defvar htmlize-face-overrides nil "Overrides for face definitions. Normally face definitions are taken from Emacs settings for fonts in the current frame. For faces present in this plist, the definitions will be used instead. Keys in the plist are symbols naming the face and values are the overriding definitions. For example: (setq htmlize-face-overrides \\='(font-lock-warning-face \"black\" font-lock-function-name-face \"red\" font-lock-comment-face \"blue\" default (:foreground \"dark-green\" :background \"yellow\"))) This variable can be also be `let' bound when running `htmlize-buffer'.") (defcustom htmlize-untabify t "Non-nil means untabify buffer contents during htmlization." :type 'boolean :group 'htmlize) (defcustom htmlize-html-major-mode nil "The mode the newly created HTML buffer will be put in. Set this to nil if you prefer the default (fundamental) mode." :type '(radio (const :tag "No mode (fundamental)" nil) (function-item html-mode) (function :tag "User-defined major mode")) :group 'htmlize) (defcustom htmlize-pre-style nil "When non-nil, `<pre>' tags will be decorated with style information in `font' and `inline-css' modes. This allows a consistent background for captures of regions." :type 'boolean :group 'htmlize) (defvar htmlize-before-hook nil "Hook run before htmlizing a buffer. The hook functions are run in the source buffer (not the resulting HTML buffer).") (defvar htmlize-after-hook nil "Hook run after htmlizing a buffer. Unlike `htmlize-before-hook', these functions are run in the generated HTML buffer. You may use them to modify the outlook of the final HTML output.") (defvar htmlize-file-hook nil "Hook run by `htmlize-file' after htmlizing a file, but before saving it.") (defvar htmlize-buffer-places) (defconst htmlize-image-mime-type-alist '((svg . "svg+xml")) "Alist mapping Emacs image types to Mime media types. https://www.iana.org/assignments/media-types/media-types.xhtml#image")
;;; Some cross-Emacs compatibility. ;; We need a function that efficiently finds the next change of a ;; property regardless of whether the change occurred because of a ;; text property or an extent/overlay. (defun htmlize-next-change (pos prop &optional limit) (if prop (next-single-char-property-change pos prop nil limit) (next-char-property-change pos limit))) (defun htmlize-overlay-faces-at (pos) (delq nil (mapcar (lambda (o) (overlay-get o 'face)) (overlays-at pos)))) (defun htmlize-next-face-change (pos &optional limit) ;; (htmlize-next-change pos 'face limit) would skip over entire ;; overlays that specify the `face' property, even when they ;; contain smaller text properties that also specify `face'. ;; Emacs display engine merges those faces, and so must we. (or limit (setq limit (point-max))) (let ((next-prop (next-single-property-change pos 'face nil limit)) (overlay-faces (htmlize-overlay-faces-at pos))) (while (progn (setq pos (next-overlay-change pos)) (and (< pos next-prop) (equal overlay-faces (htmlize-overlay-faces-at pos))))) (setq pos (min pos next-prop)) ;; Additionally, we include the entire region that specifies the ;; `display' property. (when (get-char-property pos 'display) (setq pos (next-single-char-property-change pos 'display nil limit))) pos))
;;; Transformation of buffer text: HTML escapes, untabification, etc. (defvar htmlize-basic-character-table ;; Map characters in the 0-127 range to either one-character strings ;; or to numeric entities. (let ((table (make-vector 128 ?\0))) ;; Map characters in the 32-126 range to themselves, others to ;; &#CODE entities; (dotimes (i 128) (setf (aref table i) (if (and (>= i 32) (<= i 126)) (char-to-string i) (format "&#%d;" i)))) ;; Set exceptions manually. (setf ;; Don't escape newline, carriage return, and TAB. (aref table ?\n) "\n" (aref table ?\r) "\r" (aref table ?\t) "\t" ;; Escape &, <, and >. (aref table ?&) "&amp;" (aref table ?<) "&lt;" (aref table ?>) "&gt;" ;; Not escaping '"' buys us a measurable speedup. It's only ;; necessary to quote it for strings used in attribute values, ;; which htmlize doesn't typically do. ;; (aref table ?\") "&quot;" ) table)) ;; A cache of HTML representation of non-ASCII characters. Depending ;; on the setting of `htmlize-convert-nonascii-to-entities', this maps ;; non-ASCII characters to either "&#<code>;" or "<char>" (mapconcat's ;; mapper must always return strings). It's only filled as characters ;; are encountered, so that in a buffer with e.g. French text, it will ;; only ever contain French accented characters as keys. It's cleared ;; on each entry to htmlize-buffer-1 to allow modifications of ;; `htmlize-convert-nonascii-to-entities' to take effect. (defvar htmlize-extended-character-cache (make-hash-table :test 'eq)) (defun htmlize-protect-string (string) "HTML-protect string, escaping HTML metacharacters and I18N chars." ;; Only protecting strings that actually contain unsafe or non-ASCII ;; chars removes a lot of unnecessary funcalls and consing. (if (not (string-match "[^\r\n\t -%'-;=?-~]" string)) string (mapconcat (lambda (char) (cond ((< char 128) ;; ASCII: use htmlize-basic-character-table. (aref htmlize-basic-character-table char)) ((gethash char htmlize-extended-character-cache) ;; We've already seen this char; return the cached ;; string. ) ((not htmlize-convert-nonascii-to-entities) ;; If conversion to entities is not desired, always ;; copy the char literally. (setf (gethash char htmlize-extended-character-cache) (char-to-string char))) ((< char 256) ;; Latin 1: no need to call encode-char. (setf (gethash char htmlize-extended-character-cache) (format "&#%d;" char))) ((encode-char char 'ucs) ;; Must check if encode-char works for CHAR; ;; it fails for Arabic and possibly elsewhere. (setf (gethash char htmlize-extended-character-cache) (format "&#%d;" (encode-char char 'ucs)))) (t ;; encode-char doesn't work for this char. Copy it ;; unchanged and hope for the best. (setf (gethash char htmlize-extended-character-cache) (char-to-string char))))) string ""))) (defun htmlize-attr-escape (string) ;; Like htmlize-protect-string, but also escapes double-quoted ;; strings to make it usable in attribute values. (setq string (htmlize-protect-string string)) (if (not (string-match "\"" string)) string (mapconcat (lambda (char) (if (eql char ?\") "&quot;" (char-to-string char))) string ""))) (defsubst htmlize-concat (list) (if (and (consp list) (null (cdr list))) ;; Don't create a new string in the common case where the list only ;; consists of one element. (car list) (apply #'concat list))) (defun htmlize-format-link (linkprops text) (let ((uri (if (stringp linkprops) linkprops (plist-get linkprops :uri))) (escaped-text (htmlize-protect-string text))) (if uri (format "<a href=\"%s\">%s</a>" (htmlize-attr-escape uri) escaped-text) escaped-text))) (defun htmlize-escape-or-link (string) ;; Escape STRING and/or add hyperlinks. STRING comes from a ;; `display' property. (let ((pos 0) (end (length string)) outlist) (while (< pos end) (let* ((link (get-char-property pos 'htmlize-link string)) (next-link-change (next-single-property-change pos 'htmlize-link string end)) (chunk (substring string pos next-link-change))) (push (cond (link (htmlize-format-link link chunk)) ((get-char-property 0 'htmlize-literal chunk) chunk) (t (htmlize-protect-string chunk))) outlist) (setq pos next-link-change))) (htmlize-concat (nreverse outlist)))) (defun htmlize-display-prop-to-html (display text) (let (desc) (cond ((stringp display) ;; Emacs ignores recursive display properties. (htmlize-escape-or-link display)) ((not (eq (car-safe display) 'image)) (htmlize-protect-string text)) ((null (setq desc (funcall htmlize-transform-image (cdr display) text))) (htmlize-escape-or-link text)) ((stringp desc) (htmlize-escape-or-link desc)) (t (htmlize-generate-image desc text))))) (defun htmlize-string-to-html (string) ;; Convert the string to HTML, including images attached as ;; `display' property and links as `htmlize-link' property. In a ;; string without images or links, this is equivalent to ;; `htmlize-protect-string'. (let ((pos 0) (end (length string)) outlist) (while (< pos end) (let* ((display (get-char-property pos 'display string)) (next-display-change (next-single-property-change pos 'display string end)) (chunk (substring string pos next-display-change))) (push (if display (htmlize-display-prop-to-html display chunk) (htmlize-escape-or-link chunk)) outlist) (setq pos next-display-change))) (htmlize-concat (nreverse outlist)))) (defun htmlize-default-transform-image (imgprops _text) "Default transformation of image descriptor to something usable in HTML. If `htmlize-use-images' is nil, the function always returns nil, meaning use original text. Otherwise, it tries to find the image for images that specify a file name. If `htmlize-force-inline-images' is non-nil, it also converts the :file attribute to :data and returns the modified property list." (when htmlize-use-images (when (plist-get imgprops :file) (let ((location (plist-get (cdr (find-image (list imgprops))) :file))) (when location (setq imgprops (plist-put (cl-copy-list imgprops) :file location))))) (if htmlize-force-inline-images (let ((location (plist-get imgprops :file)) data) (when location (with-temp-buffer (condition-case nil (progn (insert-file-contents-literally location) (setq data (buffer-string))) (error nil)))) ;; if successful, return the new plist, otherwise return ;; nil, which will use the original text (and data (plist-put (plist-put imgprops :file nil) :data data))) imgprops))) (defun htmlize-alt-text (_imgprops origtext) (and (/= (length origtext) 0) (<= (length origtext) htmlize-max-alt-text) (not (string-match "[\0-\x1f]" origtext)) origtext)) (defun htmlize-generate-image (imgprops origtext) (let* ((alt-text (htmlize-alt-text imgprops origtext)) (alt-attr (if alt-text (format " alt=\"%s\"" (htmlize-attr-escape alt-text)) ""))) (cond ((plist-get imgprops :file) ;; Try to find the image in image-load-path (let* ((found-props (cdr (find-image (list imgprops)))) (file (or (plist-get found-props :file) (plist-get imgprops :file)))) (format "<img src=\"%s\"%s />" (htmlize-attr-escape (file-relative-name file)) alt-attr))) ((plist-get imgprops :data) (let ((image-type (plist-get imgprops :type))) (format "<img src=\"data:image/%s;base64,%s\"%s />" (or (alist-get image-type htmlize-image-mime-type-alist) image-type "") (base64-encode-string (plist-get imgprops :data)) alt-attr)))))) (defconst htmlize-ellipsis (propertize "..." 'htmlize-ellipsis t)) (defun htmlize-match-inv-spec (inv) (cl-member inv buffer-invisibility-spec :key (lambda (i) (if (symbolp i) i (car i))))) (defun htmlize-decode-invisibility-spec (invisible) ;; Return t, nil, or `ellipsis', depending on how invisible text should ;; be inserted. (if (not (listp buffer-invisibility-spec)) ;; If buffer-invisibility-spec is not a list, then all ;; characters with non-nil `invisible' property are visible. (not invisible) ;; Otherwise, the value of a non-nil `invisible' property can be: ;; 1. a symbol -- make the text invisible if it matches ;; buffer-invisibility-spec. ;; 2. a list of symbols -- make the text invisible if ;; any symbol in the list matches ;; buffer-invisibility-spec. ;; If the match of buffer-invisibility-spec has a non-nil ;; CDR, replace the invisible text with an ellipsis. (let ((match (if (symbolp invisible) (htmlize-match-inv-spec invisible) (cl-some #'htmlize-match-inv-spec invisible)))) (cond ((null match) t) ((cdr-safe (car match)) 'ellipsis) (t nil))))) (defun htmlize-add-before-after-strings (beg end text) ;; Find overlays specifying before-string and after-string in [beg, ;; pos). If any are found, splice them into TEXT and return the new ;; text. (let (additions) (dolist (overlay (overlays-in beg end)) (let ((before (overlay-get overlay 'before-string)) (after (overlay-get overlay 'after-string))) (when after (push (cons (- (overlay-end overlay) beg) after) additions)) (when before (push (cons (- (overlay-start overlay) beg) before) additions)))) (if additions (let ((textlist nil) (strpos 0)) (dolist (add (cl-stable-sort additions #'< :key #'car)) (let ((addpos (car add)) (addtext (cdr add))) (push (substring text strpos addpos) textlist) (push addtext textlist) (setq strpos addpos))) (push (substring text strpos) textlist) (apply #'concat (nreverse textlist))) text))) (defun htmlize-copy-prop (prop beg end string) ;; Copy the specified property from the specified region of the ;; buffer to the target string. We cannot rely on Emacs to copy the ;; property because we want to handle properties coming from both ;; text properties and overlays. (let ((pos beg)) (while (< pos end) (let ((value (get-char-property pos prop)) (next-change (htmlize-next-change pos prop end))) (when value (put-text-property (- pos beg) (- next-change beg) prop value string)) (setq pos next-change))))) (defun htmlize-get-text-with-display (beg end) ;; Like buffer-substring-no-properties, except it copies the ;; `display' property from the buffer, if found. (let ((text (buffer-substring-no-properties beg end))) (htmlize-copy-prop 'display beg end text) (htmlize-copy-prop 'htmlize-link beg end text) (setq text (htmlize-add-before-after-strings beg end text)) text)) (defun htmlize-buffer-substring-no-invisible (beg end) ;; Like buffer-substring-no-properties, but don't copy invisible ;; parts of the region. Where buffer-substring-no-properties ;; mandates an ellipsis to be shown, htmlize-ellipsis is inserted. (let ((pos beg) visible-list invisible show last-show next-change) ;; Iterate over the changes in the `invisible' property and filter ;; out the portions where it's non-nil, i.e. where the text is ;; invisible. (while (< pos end) (setq invisible (get-char-property pos 'invisible) next-change (htmlize-next-change pos 'invisible end) show (htmlize-decode-invisibility-spec invisible)) (cond ((eq show t) (push (htmlize-get-text-with-display pos next-change) visible-list)) ((and (eq show 'ellipsis) (not (eq last-show 'ellipsis)) ;; Conflate successive ellipses. (push htmlize-ellipsis visible-list)))) (setq pos next-change last-show show)) (htmlize-concat (nreverse visible-list)))) (defun htmlize-trim-ellipsis (text) ;; Remove htmlize-ellipses ("...") from the beginning of TEXT if it ;; starts with it. It checks for the special property of the ;; ellipsis so it doesn't work on ordinary text that begins with ;; "...". (if (get-text-property 0 'htmlize-ellipsis text) (substring text (length htmlize-ellipsis)) text)) (defconst htmlize-tab-spaces ;; A table of strings with spaces. (aref htmlize-tab-spaces 5) is ;; like (make-string 5 ?\s), except it doesn't cons. (let ((v (make-vector 32 nil))) (dotimes (i (length v)) (setf (aref v i) (make-string i ?\s))) v)) (defun htmlize-untabify-string (text start-column) "Untabify TEXT, assuming it starts at START-COLUMN." (let ((column start-column) (last-match 0) (chunk-start 0) chunks match-pos tab-size) (while (string-match "[\t\n]" text last-match) (setq match-pos (match-beginning 0)) (cond ((eq (aref text match-pos) ?\t) ;; Encountered a tab: create a chunk of text followed by ;; the expanded tab. (push (substring text chunk-start match-pos) chunks) ;; Increase COLUMN by the length of the text we've ;; skipped since last tab or newline. (Encountering ;; newline resets it.) (cl-incf column (- match-pos last-match)) ;; Calculate tab size based on tab-width and COLUMN. (setq tab-size (- tab-width (% column tab-width))) ;; Expand the tab, carefully recreating the `display' ;; property if one was on the TAB. (let ((display (get-text-property match-pos 'display text)) (expanded-tab (aref htmlize-tab-spaces tab-size))) (when display (setq expanded-tab (copy-sequence expanded-tab)) (put-text-property 0 tab-size 'display display expanded-tab)) (push expanded-tab chunks)) (cl-incf column tab-size) (setq chunk-start (1+ match-pos))) (t ;; Reset COLUMN at beginning of line. (setq column 0))) (setq last-match (1+ match-pos))) ;; If no chunks have been allocated, it means there have been no ;; tabs to expand. Return TEXT unmodified. (if (null chunks) text (when (< chunk-start (length text)) ;; Push the remaining chunk. (push (substring text chunk-start) chunks)) ;; Generate the output from the available chunks. (htmlize-concat (nreverse chunks))))) (defun htmlize-extract-text (beg end trailing-ellipsis) ;; Extract buffer text, sans the invisible parts. Then ;; untabify it and escape the HTML metacharacters. (let ((text (htmlize-buffer-substring-no-invisible beg end))) (when trailing-ellipsis (setq text (htmlize-trim-ellipsis text))) ;; If TEXT ends up empty, don't change trailing-ellipsis. (when (> (length text) 0) (setq trailing-ellipsis (get-text-property (1- (length text)) 'htmlize-ellipsis text))) (when htmlize-untabify (setq text (htmlize-untabify-string text (current-column)))) (setq text (htmlize-string-to-html text)) (cl-values text trailing-ellipsis))) (defun htmlize-despam-address (string) "Replace every occurrence of '@' in STRING with %40. This is used to protect mailto links without modifying their meaning." ;; Suggested by Ville Skytta. (while (string-match "@" string) (setq string (replace-match "%40" nil t string))) string) (defun htmlize-make-tmp-overlay (beg end props) (let ((overlay (make-overlay beg end))) (overlay-put overlay 'htmlize-tmp-overlay t) (while props (overlay-put overlay (pop props) (pop props))) overlay)) (defun htmlize-delete-tmp-overlays () (dolist (overlay (overlays-in (point-min) (point-max))) (when (overlay-get overlay 'htmlize-tmp-overlay) (delete-overlay overlay)))) (defun htmlize-make-link-overlay (beg end uri) (htmlize-make-tmp-overlay beg end `(htmlize-link (:uri ,uri)))) (defun htmlize-create-auto-links () "Add `htmlize-link' property to all mailto links in the buffer." (save-excursion (goto-char (point-min)) (while (re-search-forward "<\\(\\(mailto:\\)?\\([-=+_.a-zA-Z0-9]+@[-_.a-zA-Z0-9]+\\)\\)>" nil t) (let* ((address (match-string 3)) (beg (match-beginning 0)) (end (match-end 0)) (uri (concat "mailto:" (htmlize-despam-address address)))) (htmlize-make-link-overlay beg end uri))) (goto-char (point-min)) (while (re-search-forward "<\\(\\(URL:\\)?\\([a-zA-Z]+://[^;]+\\)\\)>" nil t) (htmlize-make-link-overlay (match-beginning 0) (match-end 0) (match-string 3)))))
;;; Tests for htmlize-create-auto-links: ;; <mailto:hniksic@xemacs.org> ;; <http://fly.srk.fer.hr> ;; <URL:http://www.xemacs.org> ;; <http://www.mail-archive.com/bbdb-info@xemacs.org/> ;; <hniksic@xemacs.org> ;; <xalan-dev-sc.10148567319.hacuhiucknfgmpfnjcpg-john=doe.com@xml.apache.org> (defun htmlize-shadow-form-feeds () (let ((s (propertize "\n<hr />" 'htmlize-literal t))) (let ((disp `(display ,s))) (while (re-search-forward "\n\^L" nil t) (let* ((beg (match-beginning 0)) (end (match-end 0)) (form-feed-pos (1+ beg)) ;; don't process ^L if invisible or covered by `display' (show (and (htmlize-decode-invisibility-spec (get-char-property form-feed-pos 'invisible)) (not (get-char-property form-feed-pos 'display))))) (when show (htmlize-make-tmp-overlay beg end disp))))))) (defun htmlize-defang-local-variables () ;; Juri Linkov reports that an HTML-ized "Local variables" can lead ;; visiting the HTML to fail with "Local variables list is not ;; properly terminated". He suggested changing the phrase to ;; syntactically equivalent HTML that Emacs doesn't recognize. (goto-char (point-min)) (while (search-forward "Local Variables:" nil t) (replace-match "Local Variables&#58;" nil t)))
;;; Color handling. (defvar htmlize-x-library-search-path `(,data-directory "/etc/X11/rgb.txt" "/usr/share/X11/rgb.txt" ;; the remainder of this list really belongs in a museum "/usr/X11R6/lib/X11/" "/usr/X11R5/lib/X11/" "/usr/lib/X11R6/X11/" "/usr/lib/X11R5/X11/" "/usr/local/X11R6/lib/X11/" "/usr/local/X11R5/lib/X11/" "/usr/local/lib/X11R6/X11/" "/usr/local/lib/X11R5/X11/" "/usr/X11/lib/X11/" "/usr/lib/X11/" "/usr/local/lib/X11/" "/usr/X386/lib/X11/" "/usr/x386/lib/X11/" "/usr/XFree86/lib/X11/" "/usr/unsupported/lib/X11/" "/usr/athena/lib/X11/" "/usr/local/x11r5/lib/X11/" "/usr/lpp/Xamples/lib/X11/" "/usr/openwin/lib/X11/" "/usr/openwin/share/lib/X11/")) (defun htmlize-get-color-rgb-hash (&optional rgb-file) "Return a hash table mapping X color names to RGB values. The keys in the hash table are X11 color names, and the values are the #rrggbb RGB specifications, extracted from `rgb.txt'. If RGB-FILE is nil, the function will try hard to find a suitable file in the system directories. If no rgb.txt file is found, return nil." (let ((rgb-file (or rgb-file (locate-file "rgb.txt" htmlize-x-library-search-path))) (hash nil)) (when rgb-file (with-temp-buffer (insert-file-contents rgb-file) (setq hash (make-hash-table :test 'equal)) (while (not (eobp)) (cond ((looking-at "^\\s-*\\([!#]\\|$\\)") ;; Skip comments and empty lines. ) ((looking-at "[ \t]*\\([0-9]+\\)[ \t]+\\([0-9]+\\)[ \t]+\\([0-9]+\\)[ \t]+\\(.*\\)") (setf (gethash (downcase (match-string 4)) hash) (format "#%02x%02x%02x" (string-to-number (match-string 1)) (string-to-number (match-string 2)) (string-to-number (match-string 3))))) (t (error "Unrecognized line in %s: %s" rgb-file (buffer-substring (point) (progn (end-of-line) (point)))))) (forward-line 1)))) hash)) ;; Compile the RGB map when loaded. On systems where rgb.txt is ;; missing, the value of the variable will be nil, and rgb.txt will ;; not be used. (defvar htmlize-color-rgb-hash (htmlize-get-color-rgb-hash))
;;; Face handling. (defun htmlize-face-color-internal (face fg) ;; Used only under GNU Emacs. Return the color of FACE, but don't ;; return "unspecified-fg" or "unspecified-bg". If the face is ;; `default' and the color is unspecified, look up the color in ;; frame parameters. (let* ((function (if fg #'face-foreground #'face-background)) (color (funcall function face nil t))) (when (and (eq face 'default) (null color)) (setq color (cdr (assq (if fg 'foreground-color 'background-color) (frame-parameters))))) (when (or (eq color 'unspecified) (equal color "unspecified-fg") (equal color "unspecified-bg")) (setq color nil)) (when (and (eq face 'default) (null color)) ;; Assuming black on white doesn't seem right, but I can't think ;; of anything better to do. (setq color (if fg "black" "white"))) color)) (defun htmlize-face-foreground (face) ;; Return the name of the foreground color of FACE. If FACE does ;; not specify a foreground color, return nil. (htmlize-face-color-internal face t)) (defun htmlize-face-background (face) ;; Return the name of the background color of FACE. If FACE does ;; not specify a background color, return nil. ;; GNU Emacs. (htmlize-face-color-internal face nil)) ;; Convert COLOR to the #RRGGBB string. If COLOR is already in that ;; format, it's left unchanged. (defun htmlize-color-to-rgb (color) (let ((rgb-string nil)) (cond ((null color) ;; Ignore nil COLOR because it means that the face is not ;; specifying any color. Hence (htmlize-color-to-rgb nil) ;; returns nil. ) ((string-match "\\`#" color) ;; The color is already in #rrggbb format. (setq rgb-string color)) ((and htmlize-use-rgb-txt htmlize-color-rgb-hash) ;; Use of rgb.txt is requested, and it's available on the ;; system. Use it. (setq rgb-string (gethash (downcase color) htmlize-color-rgb-hash))) (t ;; We're getting the RGB components from Emacs. (let ((rgb (mapcar (lambda (arg) (/ arg 256)) (color-values color)))) (when rgb (setq rgb-string (apply #'format "#%02x%02x%02x" rgb)))))) ;; If RGB-STRING is still nil, it means the color cannot be found, ;; for whatever reason. In that case just punt and return COLOR. ;; Most browsers support a decent set of color names anyway. (or rgb-string color))) ;; We store the face properties we care about into an ;; `htmlize-fstruct' type. That way we only have to analyze face ;; properties, which can be time consuming, once per each face. The ;; mapping between Emacs faces and htmlize-fstructs is established by ;; htmlize-make-face-map. The name "fstruct" refers to variables of ;; type `htmlize-fstruct', while the term "face" is reserved for Emacs ;; faces. (cl-defstruct htmlize-fstruct foreground ; foreground color, #rrggbb background ; background color, #rrggbb size ; size boldp ; whether face is bold italicp ; whether face is italic underlinep ; whether face is underlined overlinep ; whether face is overlined strikep ; whether face is struck through css-name ; CSS name of face ) (defun htmlize-face-set-from-keyword-attr (fstruct attr value) ;; For ATTR and VALUE, set the equivalent value in FSTRUCT. (cl-case attr (:foreground (setf (htmlize-fstruct-foreground fstruct) (htmlize-color-to-rgb value))) (:background (setf (htmlize-fstruct-background fstruct) (htmlize-color-to-rgb value))) (:height (setf (htmlize-fstruct-size fstruct) value)) (:weight (when (string-match (symbol-name value) "bold") (setf (htmlize-fstruct-boldp fstruct) t))) (:slant (setf (htmlize-fstruct-italicp fstruct) (or (eq value 'italic) (eq value 'oblique)))) (:bold (setf (htmlize-fstruct-boldp fstruct) value)) (:italic (setf (htmlize-fstruct-italicp fstruct) value)) (:underline (setf (htmlize-fstruct-underlinep fstruct) value)) (:overline (setf (htmlize-fstruct-overlinep fstruct) value)) (:strike-through (setf (htmlize-fstruct-strikep fstruct) value)))) (defun htmlize-face-size (face) ;; The size (height) of FACE, taking inheritance into account. ;; Only works in Emacs 21 and later. (let* ((face-list (list face)) (head face-list) (tail face-list)) (while head (let ((inherit (face-attribute (car head) :inherit))) (cond ((listp inherit) (setq tail (last inherit))) ((eq inherit 'unspecified)) (t (setcdr tail (list inherit)) (setq tail (cdr tail))))) (pop head)) (let ((size-list (cl-loop for f in face-list for h = (and (facep f) (face-attribute f :height)) collect (if (eq h 'unspecified) nil h)))) (cl-reduce 'htmlize-merge-size (cons nil size-list))))) (defun htmlize-face-css-name (face) ;; Generate the css-name property for the given face. Emacs places ;; no restrictions on the names of symbols that represent faces -- ;; any characters may be in the name, even control chars. We try ;; hard to beat the face name into shape, both esthetically and ;; according to CSS1 specs. (let ((name (downcase (symbol-name face)))) (when (string-match "\\`font-lock-" name) ;; font-lock-FOO-face -> FOO. (setq name (replace-match "" t t name))) (when (string-match "-face\\'" name) ;; Drop the redundant "-face" suffix. (setq name (replace-match "" t t name))) (while (string-match "[^-a-zA-Z0-9]" name) ;; Drop the non-alphanumerics. (setq name (replace-match "X" t t name))) (when (string-match "\\`[-0-9]" name) ;; CSS identifiers may not start with a digit. (setq name (concat "X" name))) ;; After these transformations, the face could come out empty. (when (equal name "") (setq name "face")) ;; Apply the prefix. (concat htmlize-css-name-prefix name))) (defun htmlize-face-to-fstruct-1 (face) "Convert Emacs face FACE to fstruct, internal." (let ((fstruct (make-htmlize-fstruct :foreground (htmlize-color-to-rgb (htmlize-face-foreground face)) :background (htmlize-color-to-rgb (htmlize-face-background face))))) ;; GNU Emacs (dolist (attr '(:weight :slant :underline :overline :strike-through)) (let ((value (face-attribute face attr nil t))) (when (and value (not (eq value 'unspecified))) (htmlize-face-set-from-keyword-attr fstruct attr value)))) (let ((size (htmlize-face-size face))) (unless (eql size 1.0) ; ignore non-spec (setf (htmlize-fstruct-size fstruct) size))) (setf (htmlize-fstruct-css-name fstruct) (htmlize-face-css-name face)) fstruct)) (defun htmlize-face-to-fstruct (face) (let* ((face-list (or (and (symbolp face) (cdr (assq face face-remapping-alist))) (list face))) (fstruct (htmlize-merge-faces (mapcar (lambda (face) (if (symbolp face) (or (htmlize-get-override-fstruct face) (htmlize-face-to-fstruct-1 face)) (htmlize-attrlist-to-fstruct face))) (nreverse face-list))))) (when (symbolp face) (setf (htmlize-fstruct-css-name fstruct) (htmlize-face-css-name face))) fstruct)) (defmacro htmlize-copy-attr-if-set (attr-list dest source) ;; Generate code with the following pattern: ;; (progn ;; (when (htmlize-fstruct-ATTR source) ;; (setf (htmlize-fstruct-ATTR dest) (htmlize-fstruct-ATTR source))) ;; ...) ;; for the given list of boolean attributes. (cons 'progn (cl-loop for attr in attr-list for attr-sym = (intern (format "htmlize-fstruct-%s" attr)) collect `(when (,attr-sym ,source) (setf (,attr-sym ,dest) (,attr-sym ,source)))))) (defun htmlize-merge-size (merged next) ;; Calculate the size of the merge of MERGED and NEXT. (cond ((null merged) next) ((integerp next) next) ((null next) merged) ((floatp merged) (* merged next)) ((integerp merged) (round (* merged next))))) (defun htmlize-merge-two-faces (merged next) (htmlize-copy-attr-if-set (foreground background boldp italicp underlinep overlinep strikep) merged next) (setf (htmlize-fstruct-size merged) (htmlize-merge-size (htmlize-fstruct-size merged) (htmlize-fstruct-size next))) merged) (defun htmlize-merge-faces (fstruct-list) (cond ((null fstruct-list) ;; Nothing to do, return a dummy face. (make-htmlize-fstruct)) ((null (cdr fstruct-list)) ;; Optimize for the common case of a single face, simply ;; return it. (car fstruct-list)) (t (cl-reduce #'htmlize-merge-two-faces (cons (make-htmlize-fstruct) fstruct-list))))) ;; GNU Emacs 20+ supports attribute lists in `face' properties. For ;; example, you can use `(:foreground "red" :weight bold)' as an ;; overlay's "face", or you can even use a list of such lists, etc. ;; We call those "attrlists". ;; ;; htmlize supports attrlist by converting them to fstructs, the same ;; as with regular faces. (defun htmlize-attrlist-to-fstruct (attrlist &optional name) ;; Like htmlize-face-to-fstruct, but accepts an ATTRLIST as input. (let ((fstruct (make-htmlize-fstruct))) (cond ((eq (car attrlist) 'foreground-color) ;; ATTRLIST is (foreground-color . COLOR) (setf (htmlize-fstruct-foreground fstruct) (htmlize-color-to-rgb (cdr attrlist)))) ((eq (car attrlist) 'background-color) ;; ATTRLIST is (background-color . COLOR) (setf (htmlize-fstruct-background fstruct) (htmlize-color-to-rgb (cdr attrlist)))) (t ;; ATTRLIST is a plist. (while attrlist (let ((attr (pop attrlist)) (value (pop attrlist))) (when (and value (not (eq value 'unspecified))) (htmlize-face-set-from-keyword-attr fstruct attr value)))))) (setf (htmlize-fstruct-css-name fstruct) (or name "custom")) fstruct)) (defun htmlize-decode-face-prop (prop) "Turn face property PROP into a list of face-like objects." ;; PROP can be a symbol naming a face, a string naming such a ;; symbol, a cons (foreground-color . COLOR) or (background-color ;; COLOR), a property list (:attr1 val1 :attr2 val2 ...), or a list ;; of any of those. ;; ;; (htmlize-decode-face-prop 'face) -> (face) ;; (htmlize-decode-face-prop '(face1 face2)) -> (face1 face2) ;; (htmlize-decode-face-prop '(:attr "val")) -> ((:attr "val")) ;; (htmlize-decode-face-prop '((:attr "val") face (foreground-color "red"))) ;; -> ((:attr "val") face (foreground-color "red")) ;; ;; Unrecognized atoms or non-face symbols/strings are silently ;; stripped away. (cond ((null prop) nil) ((symbolp prop) (and (facep prop) (list prop))) ((stringp prop) (and (facep (intern-soft prop)) (list prop))) ((atom prop) nil) ((and (symbolp (car prop)) (eq ?: (aref (symbol-name (car prop)) 0))) (list prop)) ((or (eq (car prop) 'foreground-color) (eq (car prop) 'background-color)) (list prop)) (t (apply #'nconc (mapcar #'htmlize-decode-face-prop prop))))) (defun htmlize-get-override-fstruct (face) (let* ((raw-def (plist-get htmlize-face-overrides face)) (def (cond ((stringp raw-def) (list :foreground raw-def)) ((listp raw-def) raw-def) (t (error (format (concat "face override must be an " "attribute list or string, got %s") raw-def)))))) (and def (htmlize-attrlist-to-fstruct def (symbol-name face))))) (defun htmlize-make-face-map (faces) ;; Return a hash table mapping Emacs faces to htmlize's fstructs. ;; The keys are either face symbols or attrlists, so the test ;; function must be `equal'. (let ((face-map (make-hash-table :test 'equal)) css-names) (dolist (face faces) (unless (gethash face face-map) ;; Haven't seen FACE yet; convert it to an fstruct and cache ;; it. (let ((fstruct (htmlize-face-to-fstruct face))) (setf (gethash face face-map) fstruct) (let* ((css-name (htmlize-fstruct-css-name fstruct)) (new-name css-name) (i 0)) ;; Uniquify the face's css-name by using NAME-1, NAME-2, ;; etc. (while (member new-name css-names) (setq new-name (format "%s-%s" css-name (cl-incf i)))) (unless (equal new-name css-name) (setf (htmlize-fstruct-css-name fstruct) new-name)) (push new-name css-names))))) face-map)) (defun htmlize-unstringify-face (face) "If FACE is a string, return it interned, otherwise return it unchanged." (if (stringp face) (intern face) face)) (defun htmlize-faces-in-buffer () "Return a list of faces used in the current buffer. This is the set of faces specified by the `face' text property and by buffer overlays that specify `face'." (let (faces) ;; Faces used by text properties. (let ((pos (point-min)) face-prop next) (while (< pos (point-max)) (setq face-prop (get-text-property pos 'face) next (or (next-single-property-change pos 'face) (point-max))) (setq faces (cl-nunion (htmlize-decode-face-prop face-prop) faces :test 'equal)) (setq pos next))) ;; Faces used by overlays. (dolist (overlay (overlays-in (point-min) (point-max))) (let ((face-prop (overlay-get overlay 'face))) (setq faces (cl-nunion (htmlize-decode-face-prop face-prop) faces :test 'equal)))) faces)) ;; htmlize-faces-at-point returns the faces in use at point. The ;; faces are sorted by increasing priority, i.e. the last face takes ;; precedence. ;; ;; This returns all the faces in the `face' property and all the faces ;; in the overlays at point. (defun htmlize-faces-at-point () (let (all-faces) ;; Faces from text properties. (let ((face-prop (get-text-property (point) 'face))) ;; we need to reverse the `face' prop because we want ;; more specific faces to come later (setq all-faces (nreverse (htmlize-decode-face-prop face-prop)))) ;; Faces from overlays. (let ((overlays ;; Collect overlays at point that specify `face'. (cl-delete-if-not (lambda (o) (overlay-get o 'face)) (nreverse (overlays-at (point) t)))) list face-prop) (dolist (overlay overlays) (setq face-prop (overlay-get overlay 'face) list (nconc (htmlize-decode-face-prop face-prop) list))) ;; Under "Merging Faces" the manual explicitly states ;; that faces specified by overlays take precedence over ;; faces specified by text properties. (setq all-faces (nconc all-faces list))) all-faces))
;; htmlize supports generating HTML in several flavors, some of which ;; use CSS, and others the <font> element. We take an OO approach and ;; define "methods" that indirect to the functions that depend on ;; `htmlize-output-type'. The currently used methods are `doctype', ;; `insert-head', `body-tag', `pre-tag', and `text-markup'. Not all ;; output types define all methods. ;; ;; Methods are called either with (htmlize-method METHOD ARGS...) ;; special form, or by accessing the function with ;; (htmlize-method-function 'METHOD) and calling (funcall FUNCTION). ;; The latter form is useful in tight loops because `htmlize-method' ;; conses. (defmacro htmlize-method (method &rest args) ;; Expand to (htmlize-TYPE-METHOD ...ARGS...). TYPE is the value of ;; `htmlize-output-type' at run time. `(funcall (htmlize-method-function ',method) ,@args)) (defun htmlize-method-function (method) ;; Return METHOD's function definition for the current output type. ;; The returned object can be safely funcalled. (let ((sym (intern (format "htmlize-%s-%s" htmlize-output-type method)))) (indirect-function (if (fboundp sym) sym (let ((default (intern (concat "htmlize-default-" (symbol-name method))))) (if (fboundp default) default 'ignore)))))) (defvar htmlize-memoization-table (make-hash-table :test 'equal)) (defmacro htmlize-memoize (key generator) "Return the value of GENERATOR, memoized as KEY. That means that GENERATOR will be evaluated and returned the first time it's called with the same value of KEY. All other times, the cached \(memoized) value will be returned." (let ((value (gensym))) `(let ((,value (gethash ,key htmlize-memoization-table))) (unless ,value (setq ,value ,generator) (setf (gethash ,key htmlize-memoization-table) ,value)) ,value)))
;;; Default methods. (defun htmlize-default-doctype () nil ; no doc-string ;; Note that the `font' output is technically invalid under this DTD ;; because the DTD doesn't allow embedding <font> in <pre>. "<!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 4.01//EN\">") (defun htmlize-default-body-tag (face-map) nil ; no doc-string face-map ; shut up the byte-compiler "<body>") (defun htmlize-default-pre-tag (face-map) nil ; no doc-string face-map ; shut up the byte-compiler "<pre>")
;;; CSS based output support. ;; Internal function; not a method. (defun htmlize-css-specs (fstruct) (let (result) (when (htmlize-fstruct-foreground fstruct) (push (format "color: %s;" (htmlize-fstruct-foreground fstruct)) result)) (when (htmlize-fstruct-background fstruct) (push (format "background-color: %s;" (htmlize-fstruct-background fstruct)) result)) (let ((size (htmlize-fstruct-size fstruct))) (when (and size (not (eq htmlize-ignore-face-size t))) (cond ((floatp size) (push (format "font-size: %d%%;" (* 100 size)) result)) ((not (eq htmlize-ignore-face-size 'absolute)) (push (format "font-size: %spt;" (/ size 10.0)) result))))) (when (htmlize-fstruct-boldp fstruct) (push "font-weight: bold;" result)) (when (htmlize-fstruct-italicp fstruct) (push "font-style: italic;" result)) (when (htmlize-fstruct-underlinep fstruct) (push "text-decoration: underline;" result)) (when (htmlize-fstruct-overlinep fstruct) (push "text-decoration: overline;" result)) (when (htmlize-fstruct-strikep fstruct) (push "text-decoration: line-through;" result)) (nreverse result))) (defun htmlize-css-insert-head (buffer-faces face-map) (insert " <style type=\"text/css\">\n <!--\n") (insert " body {\n " (mapconcat #'identity (htmlize-css-specs (gethash 'default face-map)) "\n ") "\n }\n") (dolist (face (cl-sort (cl-copy-list buffer-faces) #'string-lessp :key (lambda (f) (htmlize-fstruct-css-name (gethash f face-map))))) (let* ((fstruct (gethash face face-map)) (cleaned-up-face-name (let ((s ;; Use `prin1-to-string' rather than `symbol-name' ;; to get the face name because the "face" can also ;; be an attrlist, which is not a symbol. (prin1-to-string face))) ;; If the name contains `--' or `*/', remove them. (while (string-match "--" s) (setq s (replace-match "-" t t s))) (while (string-match "\\*/" s) (setq s (replace-match "XX" t t s))) s)) (specs (htmlize-css-specs fstruct))) (insert " ." (htmlize-fstruct-css-name fstruct)) (if (null specs) (insert " {") (insert " {\n /* " cleaned-up-face-name " */\n " (mapconcat #'identity specs "\n "))) (insert "\n }\n"))) (insert htmlize-hyperlink-style " -->\n </style>\n")) (defun htmlize-css-text-markup (fstruct-list buffer) ;; Open the markup needed to insert text colored with FACES into ;; BUFFER. Return the function that closes the markup. ;; In CSS mode, this is easy: just nest the text in one <span ;; class=...> tag for each face in FSTRUCT-LIST. (dolist (fstruct fstruct-list) (princ "<span class=\"" buffer) (princ (htmlize-fstruct-css-name fstruct) buffer) (princ "\">" buffer)) (lambda () (dolist (_fstruct fstruct-list) (princ "</span>" buffer))))
;;; `inline-css' output support. (defun htmlize-inline-css-body-tag (face-map) (format "<body style=\"%s\">" (mapconcat #'identity (htmlize-css-specs (gethash 'default face-map)) " "))) (defun htmlize-inline-css-pre-tag (face-map) (if htmlize-pre-style (format "<pre style=\"%s\">" (mapconcat #'identity (htmlize-css-specs (gethash 'default face-map)) " ")) (format "<pre>"))) (defun htmlize-inline-css-text-markup (fstruct-list buffer) (let* ((merged (htmlize-merge-faces fstruct-list)) (style (htmlize-memoize merged (let ((specs (htmlize-css-specs merged))) (and specs (mapconcat #'identity (htmlize-css-specs merged) " ")))))) (when style (princ "<span style=\"" buffer) (princ style buffer) (princ "\">" buffer)) (lambda () (when style (princ "</span>" buffer)))))
;;; `font' tag based output support. (defun htmlize-font-body-tag (face-map) (let ((fstruct (gethash 'default face-map))) (format "<body text=\"%s\" bgcolor=\"%s\">" (htmlize-fstruct-foreground fstruct) (htmlize-fstruct-background fstruct)))) (defun htmlize-font-pre-tag (face-map) (if htmlize-pre-style (let ((fstruct (gethash 'default face-map))) (format "<pre text=\"%s\" bgcolor=\"%s\">" (htmlize-fstruct-foreground fstruct) (htmlize-fstruct-background fstruct))) (format "<pre>"))) (defun htmlize-font-text-markup (fstruct-list buffer) ;; In `font' mode, we use the traditional HTML means of altering ;; presentation: <font> tag for colors, <b> for bold, <u> for ;; underline, and <strike> for strike-through. (let* ((merged (htmlize-merge-faces fstruct-list)) (markup (htmlize-memoize merged (cons (concat (and (htmlize-fstruct-foreground merged) (format "<font color=\"%s\">" (htmlize-fstruct-foreground merged))) (and (htmlize-fstruct-boldp merged) "<b>") (and (htmlize-fstruct-italicp merged) "<i>") (and (htmlize-fstruct-underlinep merged) "<u>") (and (htmlize-fstruct-strikep merged) "<strike>")) (concat (and (htmlize-fstruct-strikep merged) "</strike>") (and (htmlize-fstruct-underlinep merged) "</u>") (and (htmlize-fstruct-italicp merged) "</i>") (and (htmlize-fstruct-boldp merged) "</b>") (and (htmlize-fstruct-foreground merged) "</font>")))))) (princ (car markup) buffer) (lambda () (princ (cdr markup) buffer))))
;;; Utility functions. (defun htmlize-buffer-1 () ;; Internal function; don't call it from outside this file. Htmlize ;; current buffer, writing the resulting HTML to a new buffer, and ;; return it. Unlike htmlize-buffer, this doesn't change current ;; buffer or use switch-to-buffer. (save-excursion ;; Protect against the hook changing the current buffer. (save-excursion (run-hooks 'htmlize-before-hook)) ;; Convince font-lock support modes to fontify the entire buffer ;; in advance. (message "Fontifing %s..." buffer-file-name) (font-lock-ensure) (message "Fontifing %s...done" buffer-file-name) (message "Htmlizing %s..." buffer-file-name) (clrhash htmlize-extended-character-cache) (clrhash htmlize-memoization-table) ;; It's important that the new buffer inherits default-directory ;; from the current buffer. (let ((htmlbuf (generate-new-buffer (if (buffer-file-name) (htmlize-make-file-name (file-name-nondirectory (buffer-file-name))) "*html*"))) (completed nil)) (unwind-protect (let* ((buffer-faces (htmlize-faces-in-buffer)) (face-map (htmlize-make-face-map (cl-adjoin 'default buffer-faces))) (places (gensym)) (title (if (buffer-file-name) (file-name-nondirectory (buffer-file-name)) (buffer-name)))) (when htmlize-generate-hyperlinks (htmlize-create-auto-links)) (when htmlize-replace-form-feeds (htmlize-shadow-form-feeds)) ;; Initialize HTMLBUF and insert the HTML prolog. (with-current-buffer htmlbuf (buffer-disable-undo) (insert (htmlize-method doctype) ?\n (format "<!-- Created by htmlize-%s in %s mode. -->\n" htmlize-version htmlize-output-type) "<html>\n ") (put places 'head-start (point-marker)) (insert "<head>\n" " <title>" (htmlize-protect-string title) "</title>\n" (if htmlize-html-charset (format (concat " <meta http-equiv=\"Content-Type\" " "content=\"text/html; charset=%s\">\n") htmlize-html-charset) "") htmlize-head-tags) (htmlize-method insert-head buffer-faces face-map) (insert " </head>") (put places 'head-end (point-marker)) (insert "\n ") (put places 'body-start (point-marker)) (insert (htmlize-method body-tag face-map) "\n ") (put places 'content-start (point-marker)) (insert (htmlize-method pre-tag face-map) "\n")) (let ((text-markup ;; Get the inserter method, so we can funcall it inside ;; the loop. Not calling `htmlize-method' in the loop ;; body yields a measurable speed increase. (htmlize-method-function 'text-markup)) ;; Declare variables used in loop body outside the loop ;; because it's faster to establish `let' bindings only ;; once. next-change text face-list trailing-ellipsis fstruct-list last-fstruct-list (close-markup (lambda ()))) ;; This loop traverses and reads the source buffer, appending ;; the resulting HTML to HTMLBUF. This method is fast ;; because: 1) it doesn't require examining the text ;; properties char by char (htmlize-next-face-change is used ;; to move between runs with the same face), and 2) it doesn't ;; require frequent buffer switches, which are slow because ;; they rebind all buffer-local vars. (goto-char (point-min)) (while (not (eobp)) (setq next-change (htmlize-next-face-change (point))) ;; Get faces in use between (point) and NEXT-CHANGE, and ;; convert them to fstructs. (setq face-list (htmlize-faces-at-point) fstruct-list (delq nil (mapcar (lambda (f) (gethash f face-map)) face-list))) (cl-multiple-value-setq (text trailing-ellipsis) (htmlize-extract-text (point) next-change trailing-ellipsis)) ;; Don't bother writing anything if there's no text (this ;; happens in invisible regions). (when (> (length text) 0) ;; Open the new markup if necessary and insert the text. (when (not (cl-equalp fstruct-list last-fstruct-list)) (funcall close-markup) (setq last-fstruct-list fstruct-list) (setq close-markup (funcall text-markup fstruct-list htmlbuf))) (princ text htmlbuf)) (goto-char next-change)) ;; We've gone through the buffer; close the markup from ;; the last run, if any. (funcall close-markup)) ;; Insert the epilog and post-process the buffer. (with-current-buffer htmlbuf (insert "</pre>") (put places 'content-end (point-marker)) (insert "\n </body>") (put places 'body-end (point-marker)) (insert "\n</html>\n") (htmlize-defang-local-variables) (goto-char (point-min)) (when htmlize-html-major-mode ;; What sucks about this is that the minor modes, most notably ;; font-lock-mode, won't be initialized. Oh well. (funcall htmlize-html-major-mode)) (set (make-local-variable 'htmlize-buffer-places) (symbol-plist places)) (run-hooks 'htmlize-after-hook) (buffer-enable-undo)) (setq completed t) htmlbuf) (if completed (message "Htmlizing %s...done" buffer-file-name) (kill-buffer htmlbuf) (message "Htmlizing %s...failed" buffer-file-name)) (htmlize-delete-tmp-overlays)))))
;;;###autoload (defun htmlize-buffer (&optional buffer interactive) "Convert BUFFER to HTML, preserving colors and decorations. The generated HTML is available in a new buffer, which is returned. When invoked interactively (or if optional INTERACTIVE is non-nil), the new buffer is selected in the current window. The title of the generated document will be set to the buffer's file name or, if that is not available, to the buffer's name. Note that htmlize doesn't fontify your buffers, it only uses the decorations that are already present. If you don't set up font-lock or something else to fontify your buffers, the resulting HTML will be plain. Likewise, if you don't like the choice of colors, fix the mode that created them, or simply alter the faces it uses." (interactive "i\np") (let ((htmlbuf (with-current-buffer (or buffer (current-buffer)) (htmlize-buffer-1)))) (when interactive (switch-to-buffer htmlbuf)) htmlbuf)) ;;;###autoload (defun htmlize-region (beg end &optional interactive) "Convert the region to HTML, preserving colors and decorations. See `htmlize-buffer' for details." (interactive "r\np") ;; Don't let zmacs region highlighting end up in HTML. (when (fboundp 'zmacs-deactivate-region) (zmacs-deactivate-region)) (let ((htmlbuf (save-restriction (narrow-to-region beg end) (htmlize-buffer-1)))) (when interactive (switch-to-buffer htmlbuf)) htmlbuf)) (defun htmlize-region-for-paste (beg end) "Htmlize the region and return just the HTML as a string. This forces the `inline-css' style and only returns the HTML body, but without the BODY tag. This should make it useful for inserting the text to another HTML buffer." (let* ((htmlize-output-type 'inline-css) (htmlbuf (htmlize-region beg end))) (unwind-protect (with-current-buffer htmlbuf (buffer-substring (plist-get htmlize-buffer-places 'content-start) (plist-get htmlize-buffer-places 'content-end))) (kill-buffer htmlbuf)))) (defun htmlize-region-save-screenshot (beg end) "Save the htmlized (see `htmlize-region-for-paste') region in the kill ring. Uses `inline-css', with style information in `<pre>' tags, so that the rendering of the marked up text approximates the buffer as closely as possible." (interactive "r") (let ((htmlize-pre-style t)) (kill-new (htmlize-region-for-paste beg end))) (deactivate-mark)) (defun htmlize-make-file-name (file) "Make an HTML file name from FILE. In its default implementation, this simply appends `.html' to FILE. This function is called by htmlize to create the buffer file name, and by `htmlize-file' to create the target file name. More elaborate transformations are conceivable, such as changing FILE's extension to `.html' (\"file.c\" -> \"file.html\"). If you want them, overload this function to do it and htmlize will comply." (concat file ".html")) ;;;###autoload (defun htmlize-file (file &optional target) "Load FILE, fontify it, convert it to HTML, and save the result. Contents of FILE are inserted into a temporary buffer, whose major mode is set with `normal-mode' as appropriate for the file type. The buffer is subsequently fontified with `font-lock' and converted to HTML. Note that, unlike `htmlize-buffer', this function explicitly turns on font-lock. If a form of highlighting other than font-lock is desired, please use `htmlize-buffer' directly on buffers so highlighted. Buffers currently visiting FILE are unaffected by this function. The function does not change current buffer or move the point. If TARGET is specified and names a directory, the resulting file will be saved there instead of to FILE's directory. If TARGET is specified and does not name a directory, it will be used as output file name." (interactive (list (read-file-name "HTML-ize file: " nil nil nil (and (buffer-file-name) (file-name-nondirectory (buffer-file-name)))))) (let ((output-file (if (and target (not (file-directory-p target))) target (expand-file-name (htmlize-make-file-name (file-name-nondirectory file)) (or target (file-name-directory file)))))) (with-temp-buffer ;; Insert FILE into the temporary buffer. (insert-file-contents file) ;; Set the file name so normal-mode and htmlize-buffer-1 pick it ;; up. Restore it afterwards so with-temp-buffer's kill-buffer ;; doesn't complain about killing a modified buffer. (let ((buffer-file-name file)) ;; Set the major mode for the sake of font-lock. (normal-mode) ;; htmlize the buffer and save the HTML. (with-current-buffer (htmlize-buffer-1) (unwind-protect (progn (run-hooks 'htmlize-file-hook) (write-region (point-min) (point-max) output-file)) (kill-buffer (current-buffer))))))) ;; I haven't decided on a useful return value yet, so just return ;; nil. nil) ;;;###autoload (defun htmlize-many-files (files &optional target-directory) "Convert FILES to HTML and save the corresponding HTML versions. FILES should be a list of file names to convert. This function calls `htmlize-file' on each file; see that function for details. When invoked interactively, you are prompted for a list of files to convert, terminated with RET. If TARGET-DIRECTORY is specified, the HTML files will be saved to that directory. Normally, each HTML file is saved to the directory of the corresponding source file." (interactive (list (let (list file) ;; Use empty string as DEFAULT because setting DEFAULT to nil ;; defaults to the directory name, which is not what we want. (while (not (equal (setq file (read-file-name "HTML-ize file (RET to finish): " (and list (file-name-directory (car list))) "" t)) "")) (push file list)) (nreverse list)))) ;; Verify that TARGET-DIRECTORY is indeed a directory. If it's a ;; file, htmlize-file will use it as target, and that doesn't make ;; sense. (and target-directory (not (file-directory-p target-directory)) (error "target-directory must name a directory: %s" target-directory)) (dolist (file files) (htmlize-file file target-directory))) (declare-function dired-get-marked-files "dired" (&optional localp arg filter distinguish-one-marked error)) ;;;###autoload (defun htmlize-many-files-dired (arg &optional target-directory) "HTMLize dired-marked files." (interactive "P") (htmlize-many-files (dired-get-marked-files nil arg) target-directory)) (provide 'htmlize) ;; Local Variables: ;; indent-tabs-mode: nil ;; End: ;;; htmlize.el ends here
htmlize-release-1.59/NEWS0000664000175000017500000000301715037657164015114 0ustar dogslegdogsleghtmlize NEWS -- history of user-visible changes. * Changes in htmlize 1.51 ** `htmlize-face-overrides' can be used to override Emacs's face definitions. * Changes in htmlize 1.47 ** GNU Emacs 21 is no longer supported. * Changes in htmlize 1.45 ** Correctly handle :inherit specifying a list of faces. (This bug would cause an error in AUX TeX buffers.) * Changes in htmlize 1.44 ** Faces specified in the `face' property are now prioritized the same way that Emacs redisplay does it: faces that appear earlier have precedence over those that appear later. * Changes in htmlize 1.41 ** `before-string' and `after-string' overlay properties are now recognized by htmlize and inserted into the HTML. ** Images specified by `display' property are recognized and inserted into the HTML as . *** If the image data comes from a file, the image will be rendered as a relative URI that would resolve to that file. Images whose data comes from a string will be rendered inline as data: URIs. The flag `htmlize-force-inline-images' can be used to force inserting *all* images inline as data: URIs. ** The image's ALT text will be the text that the `display' property is replacing, if non-empty. ** Arbitrary links can now be added to the generated HTML. If htmlize encounters buffer text with `htmlize-link' property, it will wrap the text in .... If the property value is a string, it is interpreted as the URI. If it is a list, it should be a property list whose currently only defined key is :uri. htmlize-release-1.59/LICENSE0000664000175000017500000010451515037657164015427 0ustar dogslegdogsleg GNU GENERAL PUBLIC LICENSE Version 3, 29 June 2007 Copyright (C) 2007 Free Software Foundation, Inc. Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble The GNU General Public License is a free, copyleft license for software and other kinds of works. The licenses for most software and other practical works are designed to take away your freedom to share and change the works. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change all versions of a program--to make sure it remains free software for all its users. We, the Free Software Foundation, use the GNU General Public License for most of our software; it applies also to any other work released this way by its authors. You can apply it to your programs, too. When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for them if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs, and that you know you can do these things. To protect your rights, we need to prevent others from denying you these rights or asking you to surrender the rights. Therefore, you have certain responsibilities if you distribute copies of the software, or if you modify it: responsibilities to respect the freedom of others. For example, if you distribute copies of such a program, whether gratis or for a fee, you must pass on to the recipients the same freedoms that you received. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights. Developers that use the GNU GPL protect your rights with two steps: (1) assert copyright on the software, and (2) offer you this License giving you legal permission to copy, distribute and/or modify it. For the developers' and authors' protection, the GPL clearly explains that there is no warranty for this free software. For both users' and authors' sake, the GPL requires that modified versions be marked as changed, so that their problems will not be attributed erroneously to authors of previous versions. Some devices are designed to deny users access to install or run modified versions of the software inside them, although the manufacturer can do so. This is fundamentally incompatible with the aim of protecting users' freedom to change the software. The systematic pattern of such abuse occurs in the area of products for individuals to use, which is precisely where it is most unacceptable. Therefore, we have designed this version of the GPL to prohibit the practice for those products. If such problems arise substantially in other domains, we stand ready to extend this provision to those domains in future versions of the GPL, as needed to protect the freedom of users. Finally, every program is threatened constantly by software patents. States should not allow patents to restrict development and use of software on general-purpose computers, but in those that do, we wish to avoid the special danger that patents applied to a free program could make it effectively proprietary. To prevent this, the GPL assures that patents cannot be used to render the program non-free. The precise terms and conditions for copying, distribution and modification follow. TERMS AND CONDITIONS 0. Definitions. "This License" refers to version 3 of the GNU General Public License. "Copyright" also means copyright-like laws that apply to other kinds of works, such as semiconductor masks. "The Program" refers to any copyrightable work licensed under this License. Each licensee is addressed as "you". "Licensees" and "recipients" may be individuals or organizations. To "modify" a work means to copy from or adapt all or part of the work in a fashion requiring copyright permission, other than the making of an exact copy. The resulting work is called a "modified version" of the earlier work or a work "based on" the earlier work. A "covered work" means either the unmodified Program or a work based on the Program. To "propagate" a work means to do anything with it that, without permission, would make you directly or secondarily liable for infringement under applicable copyright law, except executing it on a computer or modifying a private copy. Propagation includes copying, distribution (with or without modification), making available to the public, and in some countries other activities as well. To "convey" a work means any kind of propagation that enables other parties to make or receive copies. Mere interaction with a user through a computer network, with no transfer of a copy, is not conveying. An interactive user interface displays "Appropriate Legal Notices" to the extent that it includes a convenient and prominently visible feature that (1) displays an appropriate copyright notice, and (2) tells the user that there is no warranty for the work (except to the extent that warranties are provided), that licensees may convey the work under this License, and how to view a copy of this License. If the interface presents a list of user commands or options, such as a menu, a prominent item in the list meets this criterion. 1. Source Code. The "source code" for a work means the preferred form of the work for making modifications to it. "Object code" means any non-source form of a work. A "Standard Interface" means an interface that either is an official standard defined by a recognized standards body, or, in the case of interfaces specified for a particular programming language, one that is widely used among developers working in that language. The "System Libraries" of an executable work include anything, other than the work as a whole, that (a) is included in the normal form of packaging a Major Component, but which is not part of that Major Component, and (b) serves only to enable use of the work with that Major Component, or to implement a Standard Interface for which an implementation is available to the public in source code form. A "Major Component", in this context, means a major essential component (kernel, window system, and so on) of the specific operating system (if any) on which the executable work runs, or a compiler used to produce the work, or an object code interpreter used to run it. The "Corresponding Source" for a work in object code form means all the source code needed to generate, install, and (for an executable work) run the object code and to modify the work, including scripts to control those activities. However, it does not include the work's System Libraries, or general-purpose tools or generally available free programs which are used unmodified in performing those activities but which are not part of the work. For example, Corresponding Source includes interface definition files associated with source files for the work, and the source code for shared libraries and dynamically linked subprograms that the work is specifically designed to require, such as by intimate data communication or control flow between those subprograms and other parts of the work. The Corresponding Source need not include anything that users can regenerate automatically from other parts of the Corresponding Source. The Corresponding Source for a work in source code form is that same work. 2. Basic Permissions. All rights granted under this License are granted for the term of copyright on the Program, and are irrevocable provided the stated conditions are met. This License explicitly affirms your unlimited permission to run the unmodified Program. The output from running a covered work is covered by this License only if the output, given its content, constitutes a covered work. This License acknowledges your rights of fair use or other equivalent, as provided by copyright law. You may make, run and propagate covered works that you do not convey, without conditions so long as your license otherwise remains in force. You may convey covered works to others for the sole purpose of having them make modifications exclusively for you, or provide you with facilities for running those works, provided that you comply with the terms of this License in conveying all material for which you do not control copyright. Those thus making or running the covered works for you must do so exclusively on your behalf, under your direction and control, on terms that prohibit them from making any copies of your copyrighted material outside their relationship with you. Conveying under any other circumstances is permitted solely under the conditions stated below. Sublicensing is not allowed; section 10 makes it unnecessary. 3. Protecting Users' Legal Rights From Anti-Circumvention Law. No covered work shall be deemed part of an effective technological measure under any applicable law fulfilling obligations under article 11 of the WIPO copyright treaty adopted on 20 December 1996, or similar laws prohibiting or restricting circumvention of such measures. When you convey a covered work, you waive any legal power to forbid circumvention of technological measures to the extent such circumvention is effected by exercising rights under this License with respect to the covered work, and you disclaim any intention to limit operation or modification of the work as a means of enforcing, against the work's users, your or third parties' legal rights to forbid circumvention of technological measures. 4. Conveying Verbatim Copies. You may convey verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice; keep intact all notices stating that this License and any non-permissive terms added in accord with section 7 apply to the code; keep intact all notices of the absence of any warranty; and give all recipients a copy of this License along with the Program. You may charge any price or no price for each copy that you convey, and you may offer support or warranty protection for a fee. 5. Conveying Modified Source Versions. You may convey a work based on the Program, or the modifications to produce it from the Program, in the form of source code under the terms of section 4, provided that you also meet all of these conditions: a) The work must carry prominent notices stating that you modified it, and giving a relevant date. b) The work must carry prominent notices stating that it is released under this License and any conditions added under section 7. This requirement modifies the requirement in section 4 to "keep intact all notices". c) You must license the entire work, as a whole, under this License to anyone who comes into possession of a copy. This License will therefore apply, along with any applicable section 7 additional terms, to the whole of the work, and all its parts, regardless of how they are packaged. This License gives no permission to license the work in any other way, but it does not invalidate such permission if you have separately received it. d) If the work has interactive user interfaces, each must display Appropriate Legal Notices; however, if the Program has interactive interfaces that do not display Appropriate Legal Notices, your work need not make them do so. A compilation of a covered work with other separate and independent works, which are not by their nature extensions of the covered work, and which are not combined with it such as to form a larger program, in or on a volume of a storage or distribution medium, is called an "aggregate" if the compilation and its resulting copyright are not used to limit the access or legal rights of the compilation's users beyond what the individual works permit. Inclusion of a covered work in an aggregate does not cause this License to apply to the other parts of the aggregate. 6. Conveying Non-Source Forms. You may convey a covered work in object code form under the terms of sections 4 and 5, provided that you also convey the machine-readable Corresponding Source under the terms of this License, in one of these ways: a) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by the Corresponding Source fixed on a durable physical medium customarily used for software interchange. b) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by a written offer, valid for at least three years and valid for as long as you offer spare parts or customer support for that product model, to give anyone who possesses the object code either (1) a copy of the Corresponding Source for all the software in the product that is covered by this License, on a durable physical medium customarily used for software interchange, for a price no more than your reasonable cost of physically performing this conveying of source, or (2) access to copy the Corresponding Source from a network server at no charge. c) Convey individual copies of the object code with a copy of the written offer to provide the Corresponding Source. This alternative is allowed only occasionally and noncommercially, and only if you received the object code with such an offer, in accord with subsection 6b. d) Convey the object code by offering access from a designated place (gratis or for a charge), and offer equivalent access to the Corresponding Source in the same way through the same place at no further charge. You need not require recipients to copy the Corresponding Source along with the object code. If the place to copy the object code is a network server, the Corresponding Source may be on a different server (operated by you or a third party) that supports equivalent copying facilities, provided you maintain clear directions next to the object code saying where to find the Corresponding Source. Regardless of what server hosts the Corresponding Source, you remain obligated to ensure that it is available for as long as needed to satisfy these requirements. e) Convey the object code using peer-to-peer transmission, provided you inform other peers where the object code and Corresponding Source of the work are being offered to the general public at no charge under subsection 6d. A separable portion of the object code, whose source code is excluded from the Corresponding Source as a System Library, need not be included in conveying the object code work. A "User Product" is either (1) a "consumer product", which means any tangible personal property which is normally used for personal, family, or household purposes, or (2) anything designed or sold for incorporation into a dwelling. In determining whether a product is a consumer product, doubtful cases shall be resolved in favor of coverage. For a particular product received by a particular user, "normally used" refers to a typical or common use of that class of product, regardless of the status of the particular user or of the way in which the particular user actually uses, or expects or is expected to use, the product. A product is a consumer product regardless of whether the product has substantial commercial, industrial or non-consumer uses, unless such uses represent the only significant mode of use of the product. "Installation Information" for a User Product means any methods, procedures, authorization keys, or other information required to install and execute modified versions of a covered work in that User Product from a modified version of its Corresponding Source. The information must suffice to ensure that the continued functioning of the modified object code is in no case prevented or interfered with solely because modification has been made. If you convey an object code work under this section in, or with, or specifically for use in, a User Product, and the conveying occurs as part of a transaction in which the right of possession and use of the User Product is transferred to the recipient in perpetuity or for a fixed term (regardless of how the transaction is characterized), the Corresponding Source conveyed under this section must be accompanied by the Installation Information. But this requirement does not apply if neither you nor any third party retains the ability to install modified object code on the User Product (for example, the work has been installed in ROM). The requirement to provide Installation Information does not include a requirement to continue to provide support service, warranty, or updates for a work that has been modified or installed by the recipient, or for the User Product in which it has been modified or installed. Access to a network may be denied when the modification itself materially and adversely affects the operation of the network or violates the rules and protocols for communication across the network. Corresponding Source conveyed, and Installation Information provided, in accord with this section must be in a format that is publicly documented (and with an implementation available to the public in source code form), and must require no special password or key for unpacking, reading or copying. 7. Additional Terms. "Additional permissions" are terms that supplement the terms of this License by making exceptions from one or more of its conditions. Additional permissions that are applicable to the entire Program shall be treated as though they were included in this License, to the extent that they are valid under applicable law. If additional permissions apply only to part of the Program, that part may be used separately under those permissions, but the entire Program remains governed by this License without regard to the additional permissions. When you convey a copy of a covered work, you may at your option remove any additional permissions from that copy, or from any part of it. (Additional permissions may be written to require their own removal in certain cases when you modify the work.) You may place additional permissions on material, added by you to a covered work, for which you have or can give appropriate copyright permission. Notwithstanding any other provision of this License, for material you add to a covered work, you may (if authorized by the copyright holders of that material) supplement the terms of this License with terms: a) Disclaiming warranty or limiting liability differently from the terms of sections 15 and 16 of this License; or b) Requiring preservation of specified reasonable legal notices or author attributions in that material or in the Appropriate Legal Notices displayed by works containing it; or c) Prohibiting misrepresentation of the origin of that material, or requiring that modified versions of such material be marked in reasonable ways as different from the original version; or d) Limiting the use for publicity purposes of names of licensors or authors of the material; or e) Declining to grant rights under trademark law for use of some trade names, trademarks, or service marks; or f) Requiring indemnification of licensors and authors of that material by anyone who conveys the material (or modified versions of it) with contractual assumptions of liability to the recipient, for any liability that these contractual assumptions directly impose on those licensors and authors. All other non-permissive additional terms are considered "further restrictions" within the meaning of section 10. If the Program as you received it, or any part of it, contains a notice stating that it is governed by this License along with a term that is a further restriction, you may remove that term. If a license document contains a further restriction but permits relicensing or conveying under this License, you may add to a covered work material governed by the terms of that license document, provided that the further restriction does not survive such relicensing or conveying. If you add terms to a covered work in accord with this section, you must place, in the relevant source files, a statement of the additional terms that apply to those files, or a notice indicating where to find the applicable terms. Additional terms, permissive or non-permissive, may be stated in the form of a separately written license, or stated as exceptions; the above requirements apply either way. 8. Termination. You may not propagate or modify a covered work except as expressly provided under this License. Any attempt otherwise to propagate or modify it is void, and will automatically terminate your rights under this License (including any patent licenses granted under the third paragraph of section 11). However, if you cease all violation of this License, then your license from a particular copyright holder is reinstated (a) provisionally, unless and until the copyright holder explicitly and finally terminates your license, and (b) permanently, if the copyright holder fails to notify you of the violation by some reasonable means prior to 60 days after the cessation. Moreover, your license from a particular copyright holder is reinstated permanently if the copyright holder notifies you of the violation by some reasonable means, this is the first time you have received notice of violation of this License (for any work) from that copyright holder, and you cure the violation prior to 30 days after your receipt of the notice. Termination of your rights under this section does not terminate the licenses of parties who have received copies or rights from you under this License. If your rights have been terminated and not permanently reinstated, you do not qualify to receive new licenses for the same material under section 10. 9. Acceptance Not Required for Having Copies. You are not required to accept this License in order to receive or run a copy of the Program. Ancillary propagation of a covered work occurring solely as a consequence of using peer-to-peer transmission to receive a copy likewise does not require acceptance. However, nothing other than this License grants you permission to propagate or modify any covered work. These actions infringe copyright if you do not accept this License. Therefore, by modifying or propagating a covered work, you indicate your acceptance of this License to do so. 10. Automatic Licensing of Downstream Recipients. Each time you convey a covered work, the recipient automatically receives a license from the original licensors, to run, modify and propagate that work, subject to this License. You are not responsible for enforcing compliance by third parties with this License. An "entity transaction" is a transaction transferring control of an organization, or substantially all assets of one, or subdividing an organization, or merging organizations. If propagation of a covered work results from an entity transaction, each party to that transaction who receives a copy of the work also receives whatever licenses to the work the party's predecessor in interest had or could give under the previous paragraph, plus a right to possession of the Corresponding Source of the work from the predecessor in interest, if the predecessor has it or can get it with reasonable efforts. You may not impose any further restrictions on the exercise of the rights granted or affirmed under this License. For example, you may not impose a license fee, royalty, or other charge for exercise of rights granted under this License, and you may not initiate litigation (including a cross-claim or counterclaim in a lawsuit) alleging that any patent claim is infringed by making, using, selling, offering for sale, or importing the Program or any portion of it. 11. Patents. A "contributor" is a copyright holder who authorizes use under this License of the Program or a work on which the Program is based. The work thus licensed is called the contributor's "contributor version". A contributor's "essential patent claims" are all patent claims owned or controlled by the contributor, whether already acquired or hereafter acquired, that would be infringed by some manner, permitted by this License, of making, using, or selling its contributor version, but do not include claims that would be infringed only as a consequence of further modification of the contributor version. For purposes of this definition, "control" includes the right to grant patent sublicenses in a manner consistent with the requirements of this License. Each contributor grants you a non-exclusive, worldwide, royalty-free patent license under the contributor's essential patent claims, to make, use, sell, offer for sale, import and otherwise run, modify and propagate the contents of its contributor version. In the following three paragraphs, a "patent license" is any express agreement or commitment, however denominated, not to enforce a patent (such as an express permission to practice a patent or covenant not to sue for patent infringement). To "grant" such a patent license to a party means to make such an agreement or commitment not to enforce a patent against the party. If you convey a covered work, knowingly relying on a patent license, and the Corresponding Source of the work is not available for anyone to copy, free of charge and under the terms of this License, through a publicly available network server or other readily accessible means, then you must either (1) cause the Corresponding Source to be so available, or (2) arrange to deprive yourself of the benefit of the patent license for this particular work, or (3) arrange, in a manner consistent with the requirements of this License, to extend the patent license to downstream recipients. "Knowingly relying" means you have actual knowledge that, but for the patent license, your conveying the covered work in a country, or your recipient's use of the covered work in a country, would infringe one or more identifiable patents in that country that you have reason to believe are valid. If, pursuant to or in connection with a single transaction or arrangement, you convey, or propagate by procuring conveyance of, a covered work, and grant a patent license to some of the parties receiving the covered work authorizing them to use, propagate, modify or convey a specific copy of the covered work, then the patent license you grant is automatically extended to all recipients of the covered work and works based on it. A patent license is "discriminatory" if it does not include within the scope of its coverage, prohibits the exercise of, or is conditioned on the non-exercise of one or more of the rights that are specifically granted under this License. You may not convey a covered work if you are a party to an arrangement with a third party that is in the business of distributing software, under which you make payment to the third party based on the extent of your activity of conveying the work, and under which the third party grants, to any of the parties who would receive the covered work from you, a discriminatory patent license (a) in connection with copies of the covered work conveyed by you (or copies made from those copies), or (b) primarily for and in connection with specific products or compilations that contain the covered work, unless you entered into that arrangement, or that patent license was granted, prior to 28 March 2007. Nothing in this License shall be construed as excluding or limiting any implied license or other defenses to infringement that may otherwise be available to you under applicable patent law. 12. No Surrender of Others' Freedom. If conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot convey a covered work so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not convey it at all. For example, if you agree to terms that obligate you to collect a royalty for further conveying from those to whom you convey the Program, the only way you could satisfy both those terms and this License would be to refrain entirely from conveying the Program. 13. Use with the GNU Affero General Public License. Notwithstanding any other provision of this License, you have permission to link or combine any covered work with a work licensed under version 3 of the GNU Affero General Public License into a single combined work, and to convey the resulting work. The terms of this License will continue to apply to the part which is the covered work, but the special requirements of the GNU Affero General Public License, section 13, concerning interaction through a network will apply to the combination as such. 14. Revised Versions of this License. The Free Software Foundation may publish revised and/or new versions of the GNU General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Program specifies that a certain numbered version of the GNU General Public License "or any later version" applies to it, you have the option of following the terms and conditions either of that numbered version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of the GNU General Public License, you may choose any version ever published by the Free Software Foundation. If the Program specifies that a proxy can decide which future versions of the GNU General Public License can be used, that proxy's public statement of acceptance of a version permanently authorizes you to choose that version for the Program. Later license versions may give you additional or different permissions. However, no additional obligations are imposed on any author or copyright holder as a result of your choosing to follow a later version. 15. Disclaimer of Warranty. THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 16. Limitation of Liability. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. 17. Interpretation of Sections 15 and 16. If the disclaimer of warranty and limitation of liability provided above cannot be given local legal effect according to their terms, reviewing courts shall apply local law that most closely approximates an absolute waiver of all civil liability in connection with the Program, unless a warranty or assumption of liability accompanies a copy of the Program in return for a fee. END OF TERMS AND CONDITIONS How to Apply These Terms to Your New Programs If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms. To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively state the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. Copyright (C) This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see . Also add information on how to contact you by electronic and paper mail. If the program does terminal interaction, make it output a short notice like this when it starts in an interactive mode: Copyright (C) This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details. The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, your program's commands might be different; for a GUI interface, you would use an "about box". You should also get your employer (if you work as a programmer) or school, if any, to sign a "copyright disclaimer" for the program, if necessary. For more information on this, and how to apply and follow the GNU GPL, see . The GNU General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Lesser General Public License instead of this License. But first, please read . htmlize-release-1.59/README.md0000664000175000017500000000330515037657164015674 0ustar dogslegdogsleg# Htmlize — Convert buffer text and decorations to HTML [![NonGNU ELPA](https://elpa.nongnu.org/nongnu/htmlize.svg)](https://elpa.nongnu.org/nongnu/htmlize.html) [![MELPA Stable](https://stable.melpa.org/packages/htmlize-badge.svg)](https://stable.melpa.org/#/htmlize) [![MELPA](https://melpa.org/packages/htmlize-badge.svg)](https://melpa.org/#/htmlize) This package converts the buffer text and the associated decorations to HTML. To use it, just switch to the buffer you want HTML-ized and type M-x htmlize-buffer. You will be switched to a new buffer that contains the resulting HTML code. You can edit and inspect this buffer, or you can just save it with C-x C-w. M-x htmlize-file will find a file, fontify it, and save the HTML version in `FILE.html`, without any additional intervention. M-x htmlize-many-files allows you to htmlize any number of files in the same manner. M-x htmlize-many-files-dired does the same for files marked in a dired buffer. Htmlize supports three types of HTML output, selected by setting `htmlize-output-type`: `css`, `inline-css` (optimized for code snippets), and `font` (simpler output, doesn't rely on CSS). See [`htmlize.el.html`][1] for an example of generated HTML. You can also use htmlize from your Emacs Lisp code. When called non-interactively, `htmlize-buffer` and `htmlize-region` will return the resulting HTML buffer, but will not change current buffer or move the point. Htmlize will do its best to work on non-windowing Emacs sessions but the result will be limited to colors supported by the terminal. [1]: http://htmlpreview.github.io/?https://github.com/emacsorphanage/htmlize/blob/master/htmlize.el.html htmlize-release-1.59/htmlize.el0000664000175000017500000022535115037657164016422 0ustar dogslegdogsleg;;; htmlize.el --- Convert buffer text and decorations to HTML -*- lexical-binding: t -*- ;; Copyright (C) 1997-2003,2005,2006,2009,2011,2012,2014,2017,2018,2020 Hrvoje Niksic ;; Author: Hrvoje Niksic ;; Homepage: https://github.com/emacsorphanage/htmlize ;; Keywords: hypermedia, extensions ;; Package-Version: 1.59 ;; Package-Requires: ((emacs "26.1")) ;; SPDX-License-Identifier: GPL-3.0-or-later ;; This file is free software: you can redistribute it and/or modify ;; it under the terms of the GNU General Public License as published ;; by the Free Software Foundation, either version 3 of the License, ;; or (at your option) any later version. ;; ;; This file is distributed in the hope that it will be useful, ;; but WITHOUT ANY WARRANTY; without even the implied warranty of ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ;; GNU General Public License for more details. ;; ;; You should have received a copy of the GNU General Public License ;; along with this file. If not, see . ;;; Commentary: ;; This package converts the buffer text and the associated ;; decorations to HTML. ;; To use it, just switch to the buffer you want HTML-ized and type ;; `M-x htmlize-buffer'. You will be switched to a new buffer that ;; contains the resulting HTML code. You can edit and inspect this ;; buffer, or you can just save it with C-x C-w. `M-x htmlize-file' ;; will find a file, fontify it, and save the HTML version in ;; FILE.html, without any additional intervention. `M-x ;; htmlize-many-files' allows you to htmlize any number of files in ;; the same manner. `M-x htmlize-many-files-dired' does the same for ;; files marked in a dired buffer. ;; Htmlize supports three types of HTML output, selected by setting ;; `htmlize-output-type': `css', `inline-css', and `font'. In `css' ;; mode, htmlize uses cascading style sheets to specify colors; it ;; generates classes that correspond to Emacs faces and uses ... to color parts of text. In this mode, the ;; produced HTML is valid under the 4.01 strict DTD, as confirmed by ;; the W3C validator. `inline-css' is like `css', except the CSS is ;; put directly in the STYLE attribute of the SPAN element, making it ;; possible to paste the generated HTML into existing HTML documents. ;; In `font' mode, htmlize uses ... to ;; colorize HTML, which is not standard-compliant, but works better in ;; older browsers. `css' mode is the default. ;; You can also use htmlize from your Emacs Lisp code. When called ;; non-interactively, `htmlize-buffer' and `htmlize-region' will ;; return the resulting HTML buffer, but will not change current ;; buffer or move the point. Htmlize will do its best to work on ;; non-windowing Emacs sessions but the result will be limited to ;; colors supported by the terminal. ;; The latest version is available at: ;; ;; ;; Thanks go to the many people who have sent reports and contributed ;; comments, suggestions, and fixes. They include Ron Gut, Bob ;; Weiner, Toni Drabik, Peter Breton, Ville Skytta, Thomas Vogels, ;; Juri Linkov, Maciek Pasternacki, and many others. ;; User quotes: "You sir, are a sick, sick, _sick_ person. :)" ;; -- Bill Perry, author of Emacs/W3 ;;; Code: (require 'cl-lib) (defconst htmlize-version "1.59") (defgroup htmlize nil "Convert buffer text and faces to HTML." :group 'hypermedia) (defcustom htmlize-head-tags "" "Additional tags to insert within HEAD of the generated document." :type 'string :group 'htmlize) (defcustom htmlize-output-type 'css "Output type of generated HTML, one of `css', `inline-css', or `font'. When set to `css' (the default), htmlize will generate a style sheet with description of faces, and use it in the HTML document, specifying the faces in the actual text with . When set to `inline-css', the style will be generated as above, but placed directly in the STYLE attribute of the span ELEMENT: . This makes it easier to paste the resulting HTML to other documents. When set to `font', the properties will be set using layout tags , , , , and . `css' output is normally preferred, but `font' is still useful for supporting old, pre-CSS browsers, and both `inline-css' and `font' for easier embedding of colorized text in foreign HTML documents (no style sheet to carry around)." :type '(choice (const css) (const inline-css) (const font)) :group 'htmlize) (defcustom htmlize-use-images t "Whether htmlize generates `img' for images attached to buffer contents." :type 'boolean :group 'htmlize) (defcustom htmlize-force-inline-images nil "Non-nil means generate all images inline using data URLs. Normally htmlize converts image descriptors with :file properties to relative URIs, and those with :data properties to data URIs. With this flag set, the images specified as a file name are loaded into memory and embedded in the HTML as data URIs." :type 'boolean :group 'htmlize) (defcustom htmlize-max-alt-text 100 "Maximum size of text to use as ALT text in images. Normally when htmlize encounters text covered by the `display' property that specifies an image, it generates an `alt' attribute containing the original text. If the text is larger than `htmlize-max-alt-text' characters, this will not be done." :type 'integer :group 'htmlize) (defcustom htmlize-transform-image 'htmlize-default-transform-image "Function called to modify the image descriptor. The function is called with the image descriptor found in the buffer and the text the image is supposed to replace. It should return a (possibly different) image descriptor property list or a replacement string to use instead of of the original buffer text. Returning nil is the same as returning the original text." :type 'boolean :group 'htmlize) (defcustom htmlize-generate-hyperlinks t "Non-nil means auto-generate the links from URLs and mail addresses in buffer. This is on by default; set it to nil if you don't want htmlize to autogenerate such links. Note that this option only turns off automatic search for contents that looks like URLs and converting them to links. It has no effect on whether htmlize respects the `htmlize-link' property." :type 'boolean :group 'htmlize) (defcustom htmlize-hyperlink-style " a { color: inherit; background-color: inherit; font: inherit; text-decoration: inherit; } a:hover { text-decoration: underline; } " "The CSS style used for hyperlinks when in CSS mode." :type 'string :group 'htmlize) (defcustom htmlize-replace-form-feeds t "Non-nil means replace form feeds in source code with HTML separators. Form feeds are the ^L characters at line beginnings that are sometimes used to separate sections of source code. If this variable is set to `t', form feed characters are replaced with the
separator. If this is a string, it specifies the replacement to use. Note that
 is
temporarily closed before the separator is inserted, so the default
replacement is effectively \"

\".  If you specify
another replacement, don't forget to close and reopen the 
 if you
want the output to remain valid HTML.

If you need more elaborate processing, set this to nil and use
htmlize-after-hook."
  :type 'boolean
  :group 'htmlize)

(defcustom htmlize-html-charset nil
  "The charset declared by the resulting HTML documents.
When non-nil, causes htmlize to insert the following in the HEAD section
of the generated HTML:

  

where CHARSET is the value you've set for htmlize-html-charset.  Valid
charsets are defined by MIME and include strings like \"iso-8859-1\",
\"iso-8859-15\", \"utf-8\", etc.

If you are using non-Latin-1 charsets, you might need to set this for
your documents to render correctly.  Also, the W3C validator requires
submitted HTML documents to declare a charset.  So if you care about
validation, you can use this to prevent the validator from bitching.

Needless to say, if you set this, you should actually make sure that
the buffer is in the encoding you're claiming it is in.  (This is
normally achieved by using the correct file coding system for the
buffer.)  If you don't understand what that means, you should probably
leave this option in its default setting."
  :type '(choice (const :tag "Unset" nil)
                 string)
  :group 'htmlize)

(defcustom htmlize-convert-nonascii-to-entities t
  "Whether non-ASCII characters should be converted to HTML entities.

When this is non-nil, characters with codes in the 128-255 range will be
considered Latin 1 and rewritten as \"&#CODE;\".  Characters with codes
above 255 will be converted to \"&#UCS;\", where UCS denotes the Unicode
code point of the character.  If the code point cannot be determined,
the character will be copied unchanged, as would be the case if the
option were nil.

When the option is nil, the non-ASCII characters are copied to HTML
without modification.  In that case, the web server and/or the browser
must be set to understand the encoding that was used when saving the
buffer.  (You might also want to specify it by setting
`htmlize-html-charset'.)

Note that in an HTML entity \"&#CODE;\", CODE is always a UCS code point,
which has nothing to do with the charset the page is in.  For example,
\"©\" *always* refers to the copyright symbol, regardless of charset
specified by the META tag or the charset sent by the HTTP server.  In
other words, \"©\" is exactly equivalent to \"©\".

For most people htmlize will work fine with this option left at the
default setting; don't change it unless you know what you're doing."
  :type 'sexp
  :group 'htmlize)

(defcustom htmlize-ignore-face-size 'absolute
  "Whether face size should be ignored when generating HTML.
If this is nil, face sizes are used.  If set to t, sizes are ignored
If set to `absolute', only absolute size specifications are ignored.
Please note that font sizes only work with CSS-based output types."
  :type '(choice (const :tag "Don't ignore" nil)
                 (const :tag "Ignore all" t)
                 (const :tag "Ignore absolute" absolute))
  :group 'htmlize)

(defcustom htmlize-css-name-prefix ""
  "The prefix used for CSS names.
The CSS names that htmlize generates from face names are often too
generic for CSS files; for example, `font-lock-type-face' is transformed
to `type'.  Use this variable to add a prefix to the generated names.
The string \"htmlize-\" is an example of a reasonable prefix."
  :type 'string
  :group 'htmlize)

(defcustom htmlize-use-rgb-txt t
  "Whether `rgb.txt' should be used to convert color names to RGB.

This conversion means determining, for instance, that the color
\"IndianRed\" corresponds to the (205, 92, 92) RGB triple.  `rgb.txt'
is the X color database that maps hundreds of color names to such RGB
triples.  When this variable is non-nil, `htmlize' uses `rgb.txt' to
look up color names.

If this variable is nil, htmlize queries Emacs for RGB components of
colors using `color-instance-rgb-components' and `color-values'.
This can yield incorrect results on non-true-color displays.

If the `rgb.txt' file is not found (which will be the case if you're
running Emacs on non-X11 systems), this option is ignored."
  :type 'boolean
  :group 'htmlize)

(defvar htmlize-face-overrides nil
  "Overrides for face definitions.

Normally face definitions are taken from Emacs settings for fonts
in the current frame.  For faces present in this plist, the
definitions will be used instead.  Keys in the plist are symbols
naming the face and values are the overriding definitions.  For
example:

  (setq htmlize-face-overrides
        \\='(font-lock-warning-face \"black\"
          font-lock-function-name-face \"red\"
          font-lock-comment-face \"blue\"
          default (:foreground \"dark-green\" :background \"yellow\")))

This variable can be also be `let' bound when running `htmlize-buffer'.")

(defcustom htmlize-untabify t
  "Non-nil means untabify buffer contents during htmlization."
  :type 'boolean
  :group 'htmlize)

(defcustom htmlize-html-major-mode nil
  "The mode the newly created HTML buffer will be put in.
Set this to nil if you prefer the default (fundamental) mode."
  :type '(radio (const :tag "No mode (fundamental)" nil)
                (function-item html-mode)
                (function :tag "User-defined major mode"))
  :group 'htmlize)

(defcustom htmlize-pre-style nil
  "When non-nil, `
' tags will be decorated with style
information in `font' and `inline-css' modes. This allows a
consistent background for captures of regions."
  :type 'boolean
  :group 'htmlize)

(defvar htmlize-before-hook nil
  "Hook run before htmlizing a buffer.
The hook functions are run in the source buffer (not the resulting HTML
buffer).")

(defvar htmlize-after-hook nil
  "Hook run after htmlizing a buffer.
Unlike `htmlize-before-hook', these functions are run in the generated
HTML buffer.  You may use them to modify the outlook of the final HTML
output.")

(defvar htmlize-file-hook nil
  "Hook run by `htmlize-file' after htmlizing a file, but before saving it.")

(defvar htmlize-buffer-places)

(defconst htmlize-image-mime-type-alist
  '((svg . "svg+xml"))
  "Alist mapping Emacs image types to Mime media types.
https://www.iana.org/assignments/media-types/media-types.xhtml#image")


;;; Some cross-Emacs compatibility.

;; We need a function that efficiently finds the next change of a
;; property regardless of whether the change occurred because of a
;; text property or an extent/overlay.
(defun htmlize-next-change (pos prop &optional limit)
  (if prop
      (next-single-char-property-change pos prop nil limit)
    (next-char-property-change pos limit)))

(defun htmlize-overlay-faces-at (pos)
  (delq nil (mapcar (lambda (o) (overlay-get o 'face)) (overlays-at pos))))

(defun htmlize-next-face-change (pos &optional limit)
  ;; (htmlize-next-change pos 'face limit) would skip over entire
  ;; overlays that specify the `face' property, even when they
  ;; contain smaller text properties that also specify `face'.
  ;; Emacs display engine merges those faces, and so must we.
  (unless limit
    (setq limit (point-max)))
  (let ((next-prop (next-single-property-change pos 'face nil limit))
        (overlay-faces (htmlize-overlay-faces-at pos)))
    (while (progn
             (setq pos (next-overlay-change pos))
             (and (< pos next-prop)
                  (equal overlay-faces (htmlize-overlay-faces-at pos)))))
    (setq pos (min pos next-prop))
    ;; Additionally, we include the entire region that specifies the
    ;; `display' property.
    (when (get-char-property pos 'display)
      (setq pos (next-single-char-property-change pos 'display nil limit)))
    pos))


;;; Transformation of buffer text: HTML escapes, untabification, etc.

(defvar htmlize-basic-character-table
  ;; Map characters in the 0-127 range to either one-character strings
  ;; or to numeric entities.
  (let ((table (make-vector 128 ?\0)))
    ;; Map characters in the 32-126 range to themselves, others to
    ;; &#CODE entities;
    (dotimes (i 128)
      (setf (aref table i) (if (and (>= i 32) (<= i 126))
                               (char-to-string i)
                             (format "&#%d;" i))))
    ;; Set exceptions manually.
    (setf
     ;; Don't escape newline, carriage return, and TAB.
     (aref table ?\n) "\n"
     (aref table ?\r) "\r"
     (aref table ?\t) "\t"
     ;; Escape &, <, and >.
     (aref table ?&) "&"
     (aref table ?<) "<"
     (aref table ?>) ">"
     ;; Not escaping '"' buys us a measurable speedup.  It's only
     ;; necessary to quote it for strings used in attribute values,
     ;; which htmlize doesn't typically do.
     ;; (aref table ?\") """
     )
    table))

;; A cache of HTML representation of non-ASCII characters.  Depending
;; on the setting of `htmlize-convert-nonascii-to-entities', this maps
;; non-ASCII characters to either "&#;" or "" (mapconcat's
;; mapper must always return strings).  It's only filled as characters
;; are encountered, so that in a buffer with e.g. French text, it will
;; only ever contain French accented characters as keys.  It's cleared
;; on each entry to htmlize-buffer-1 to allow modifications of
;; `htmlize-convert-nonascii-to-entities' to take effect.
(defvar htmlize-extended-character-cache (make-hash-table :test 'eq))

(defun htmlize-protect-string (string)
  "HTML-protect string, escaping HTML metacharacters and I18N chars."
  ;; Only protecting strings that actually contain unsafe or non-ASCII
  ;; chars removes a lot of unnecessary funcalls and consing.
  (if (not (string-match "[^\r\n\t -%'-;=?-~]" string))
      string
    (mapconcat (lambda (char)
                 (cond
                  ((< char 128)
                   ;; ASCII: use htmlize-basic-character-table.
                   (aref htmlize-basic-character-table char))
                  ((gethash char htmlize-extended-character-cache)
                   ;; We've already seen this char; return the cached
                   ;; string.
                   )
                  ((not htmlize-convert-nonascii-to-entities)
                   ;; If conversion to entities is not desired, always
                   ;; copy the char literally.
                   (setf (gethash char htmlize-extended-character-cache)
                         (char-to-string char)))
                  ((< char 256)
                   ;; Latin 1: no need to call encode-char.
                   (setf (gethash char htmlize-extended-character-cache)
                         (format "&#%d;" char)))
                  ((encode-char char 'ucs)
                   ;; Must check if encode-char works for CHAR;
                   ;; it fails for Arabic and possibly elsewhere.
                   (setf (gethash char htmlize-extended-character-cache)
                         (format "&#%d;" (encode-char char 'ucs))))
                  (t
                   ;; encode-char doesn't work for this char.  Copy it
                   ;; unchanged and hope for the best.
                   (setf (gethash char htmlize-extended-character-cache)
                         (char-to-string char)))))
               string "")))

(defun htmlize-attr-escape (string)
  ;; Like htmlize-protect-string, but also escapes double-quoted
  ;; strings to make it usable in attribute values.
  (setq string (htmlize-protect-string string))
  (if (not (string-match "\"" string))
      string
    (mapconcat (lambda (char)
                 (if (eql char ?\")
                     """
                   (char-to-string char)))
               string "")))

(defsubst htmlize-concat (list)
  (if (and (consp list) (null (cdr list)))
      ;; Don't create a new string in the common case where the list only
      ;; consists of one element.
      (car list)
    (apply #'concat list)))

(defun htmlize-format-link (linkprops text)
  (let ((uri (if (stringp linkprops)
                 linkprops
               (plist-get linkprops :uri)))
        (escaped-text (htmlize-protect-string text)))
    (if uri
        (format "%s" (htmlize-attr-escape uri) escaped-text)
      escaped-text)))

(defun htmlize-escape-or-link (string)
  ;; Escape STRING and/or add hyperlinks.  STRING comes from a
  ;; `display' property.
  (let ((pos 0) (end (length string)) outlist)
    (while (< pos end)
      (let* ((link (get-char-property pos 'htmlize-link string))
             (next-link-change (next-single-property-change
                                pos 'htmlize-link string end))
             (chunk (substring string pos next-link-change)))
        (push
         (cond (link
                (htmlize-format-link link chunk))
               ((get-char-property 0 'htmlize-literal chunk)
                chunk)
               (t
                (htmlize-protect-string chunk)))
         outlist)
        (setq pos next-link-change)))
    (htmlize-concat (nreverse outlist))))

(defun htmlize-display-prop-to-html (display text)
  (let (desc)
    (cond ((stringp display)
           ;; Emacs ignores recursive display properties.
           (htmlize-escape-or-link display))
          ((not (eq (car-safe display) 'image))
           (htmlize-protect-string text))
          ((null (setq desc (funcall htmlize-transform-image
                                     (cdr display) text)))
           (htmlize-escape-or-link text))
          ((stringp desc)
           (htmlize-escape-or-link desc))
          (t
           (htmlize-generate-image desc text)))))

(defun htmlize-string-to-html (string)
  ;; Convert the string to HTML, including images attached as
  ;; `display' property and links as `htmlize-link' property.  In a
  ;; string without images or links, this is equivalent to
  ;; `htmlize-protect-string'.
  (let ((pos 0) (end (length string)) outlist)
    (while (< pos end)
      (let* ((display (get-char-property pos 'display string))
             (next-display-change (next-single-property-change
                                   pos 'display string end))
             (chunk (substring string pos next-display-change)))
        (push
         (if display
             (htmlize-display-prop-to-html display chunk)
           (htmlize-escape-or-link chunk))
         outlist)
        (setq pos next-display-change)))
    (htmlize-concat (nreverse outlist))))

(defun htmlize-default-transform-image (imgprops _text)
  "Default transformation of image descriptor to something usable in HTML.

If `htmlize-use-images' is nil, the function always returns nil, meaning
use original text.  Otherwise, it tries to find the image for images that
specify a file name.  If `htmlize-force-inline-images' is non-nil, it also
converts the :file attribute to :data and returns the modified property
list."
  (when htmlize-use-images
    (when (plist-get imgprops :file)
      (let ((location (plist-get (cdr (find-image (list imgprops))) :file)))
        (when location
          (setq imgprops (plist-put (cl-copy-list imgprops) :file location)))))
    (if htmlize-force-inline-images
        (let ((location (plist-get imgprops :file))
              data)
          (when location
            (with-temp-buffer
              (condition-case nil
                  (progn
                    (insert-file-contents-literally location)
                    (setq data (buffer-string)))
                (error nil))))
          ;; if successful, return the new plist, otherwise return
          ;; nil, which will use the original text
          (and data
               (plist-put (plist-put imgprops :file nil)
                          :data data)))
      imgprops)))

(defun htmlize-alt-text (_imgprops origtext)
  (and (/= (length origtext) 0)
       (<= (length origtext) htmlize-max-alt-text)
       (not (string-match "[\0-\x1f]" origtext))
       origtext))

(defun htmlize-generate-image (imgprops origtext)
  (let* ((alt-text (htmlize-alt-text imgprops origtext))
         (alt-attr (if alt-text
                       (format " alt=\"%s\"" (htmlize-attr-escape alt-text))
                     "")))
    (cond ((plist-get imgprops :file)
           ;; Try to find the image in image-load-path
           (let* ((found-props (cdr (find-image (list imgprops))))
                  (file (or (plist-get found-props :file)
                            (plist-get imgprops :file))))
             (format ""
                     (htmlize-attr-escape (file-relative-name file))
                     alt-attr)))
          ((plist-get imgprops :data)
           (let ((image-type (plist-get imgprops :type)))
             (format ""
                     (or (alist-get image-type htmlize-image-mime-type-alist)
                         image-type "")
                     (base64-encode-string (plist-get imgprops :data))
                     alt-attr))))))

(defconst htmlize-ellipsis (propertize "..." 'htmlize-ellipsis t))

(defun htmlize-match-inv-spec (inv)
  (cl-member inv buffer-invisibility-spec
             :key (lambda (i)
                    (if (symbolp i) i (car i)))))

(defun htmlize-decode-invisibility-spec (invisible)
  ;; Return t, nil, or `ellipsis', depending on how invisible text should
  ;; be inserted.

  (if (not (listp buffer-invisibility-spec))
      ;; If buffer-invisibility-spec is not a list, then all
      ;; characters with non-nil `invisible' property are visible.
      (not invisible)

    ;; Otherwise, the value of a non-nil `invisible' property can be:
    ;; 1. a symbol -- make the text invisible if it matches
    ;;    buffer-invisibility-spec.
    ;; 2. a list of symbols -- make the text invisible if
    ;;    any symbol in the list matches
    ;;    buffer-invisibility-spec.
    ;; If the match of buffer-invisibility-spec has a non-nil
    ;; CDR, replace the invisible text with an ellipsis.
    (let ((match (if (symbolp invisible)
                     (htmlize-match-inv-spec invisible)
                   (cl-some #'htmlize-match-inv-spec invisible))))
      (cond ((null match) t)
            ((cdr-safe (car match)) 'ellipsis)
            (t nil)))))

(defun htmlize-add-before-after-strings (beg end text)
  ;; Find overlays specifying before-string and after-string in [beg,
  ;; pos).  If any are found, splice them into TEXT and return the new
  ;; text.
  (let (additions)
    (dolist (overlay (overlays-in beg end))
      (let ((before (overlay-get overlay 'before-string))
            (after (overlay-get overlay 'after-string)))
        (when after
          (push (cons (- (overlay-end overlay) beg)
                      after)
                additions))
        (when before
          (push (cons (- (overlay-start overlay) beg)
                      before)
                additions))))
    (if additions
        (let ((textlist nil)
              (strpos 0))
          (dolist (add (cl-stable-sort additions #'< :key #'car))
            (let ((addpos (car add))
                  (addtext (cdr add)))
              (push (substring text strpos addpos) textlist)
              (push addtext textlist)
              (setq strpos addpos)))
          (push (substring text strpos) textlist)
          (apply #'concat (nreverse textlist)))
      text)))

(defun htmlize-copy-prop (prop beg end string)
  ;; Copy the specified property from the specified region of the
  ;; buffer to the target string.  We cannot rely on Emacs to copy the
  ;; property because we want to handle properties coming from both
  ;; text properties and overlays.
  (let ((pos beg))
    (while (< pos end)
      (let ((value (get-char-property pos prop))
            (next-change (htmlize-next-change pos prop end)))
        (when value
          (put-text-property (- pos beg) (- next-change beg)
                             prop value string))
        (setq pos next-change)))))

(defun htmlize-get-text-with-display (beg end)
  ;; Like buffer-substring-no-properties, except it copies the
  ;; `display' property from the buffer, if found.
  (let ((text (buffer-substring-no-properties beg end)))
    (htmlize-copy-prop 'display beg end text)
    (htmlize-copy-prop 'htmlize-link beg end text)
    (setq text (htmlize-add-before-after-strings beg end text))
    text))

(defun htmlize-buffer-substring-no-invisible (beg end)
  ;; Like buffer-substring-no-properties, but don't copy invisible
  ;; parts of the region.  Where buffer-substring-no-properties
  ;; mandates an ellipsis to be shown, htmlize-ellipsis is inserted.
  (let ((pos beg)
        visible-list invisible show last-show next-change)
    ;; Iterate over the changes in the `invisible' property and filter
    ;; out the portions where it's non-nil, i.e. where the text is
    ;; invisible.
    (while (< pos end)
      (setq invisible (get-char-property pos 'invisible)
            next-change (htmlize-next-change pos 'invisible end)
            show (htmlize-decode-invisibility-spec invisible))
      (cond ((eq show t)
             (push (htmlize-get-text-with-display pos next-change)
                   visible-list))
            ((and (eq show 'ellipsis)
                  (not (eq last-show 'ellipsis)))
             ;; Conflate successive ellipses.
             (push htmlize-ellipsis visible-list)))
      (setq pos next-change last-show show))
    (htmlize-concat (nreverse visible-list))))

(defun htmlize-trim-ellipsis (text)
  ;; Remove htmlize-ellipses ("...") from the beginning of TEXT if it
  ;; starts with it.  It checks for the special property of the
  ;; ellipsis so it doesn't work on ordinary text that begins with
  ;; "...".
  (if (get-text-property 0 'htmlize-ellipsis text)
      (substring text (length htmlize-ellipsis))
    text))

(defconst htmlize-tab-spaces
  ;; A table of strings with spaces.  (aref htmlize-tab-spaces 5) is
  ;; like (make-string 5 ?\s), except it doesn't cons.
  (let ((v (make-vector 32 nil)))
    (dotimes (i (length v))
      (setf (aref v i) (make-string i ?\s)))
    v))

(defun htmlize-untabify-string (text start-column)
  "Untabify TEXT, assuming it starts at START-COLUMN."
  (let ((column start-column)
        (last-match 0)
        (chunk-start 0)
        chunks match-pos tab-size)
    (while (string-match "[\t\n]" text last-match)
      (setq match-pos (match-beginning 0))
      (cond ((eq (aref text match-pos) ?\t)
             ;; Encountered a tab: create a chunk of text followed by
             ;; the expanded tab.
             (push (substring text chunk-start match-pos) chunks)
             ;; Increase COLUMN by the length of the text we've
             ;; skipped since last tab or newline.  (Encountering
             ;; newline resets it.)
             (cl-incf column (- match-pos last-match))
             ;; Calculate tab size based on tab-width and COLUMN.
             (setq tab-size (- tab-width (% column tab-width)))
             ;; Expand the tab, carefully recreating the `display'
             ;; property if one was on the TAB.
             (let ((display (get-text-property match-pos 'display text))
                   (expanded-tab (aref htmlize-tab-spaces tab-size)))
               (when display
                 (setq expanded-tab (copy-sequence expanded-tab))
                 (put-text-property 0 tab-size 'display display expanded-tab))
               (push expanded-tab chunks))
             (cl-incf column tab-size)
             (setq chunk-start (1+ match-pos)))
            (t
             ;; Reset COLUMN at beginning of line.
             (setq column 0)))
      (setq last-match (1+ match-pos)))
    ;; If no chunks have been allocated, it means there have been no
    ;; tabs to expand.  Return TEXT unmodified.
    (if (null chunks)
        text
      (when (< chunk-start (length text))
        ;; Push the remaining chunk.
        (push (substring text chunk-start) chunks))
      ;; Generate the output from the available chunks.
      (htmlize-concat (nreverse chunks)))))

(defun htmlize-extract-text (beg end trailing-ellipsis)
  ;; Extract buffer text, sans the invisible parts.  Then
  ;; untabify it and escape the HTML metacharacters.
  (let ((text (htmlize-buffer-substring-no-invisible beg end)))
    (when trailing-ellipsis
      (setq text (htmlize-trim-ellipsis text)))
    ;; If TEXT ends up empty, don't change trailing-ellipsis.
    (when (> (length text) 0)
      (setq trailing-ellipsis
            (get-text-property (1- (length text))
                               'htmlize-ellipsis text)))
    (when htmlize-untabify
      (setq text (htmlize-untabify-string text (current-column))))
    (setq text (htmlize-string-to-html text))
    (cl-values text trailing-ellipsis)))

(defun htmlize-despam-address (string)
  "Replace every occurrence of '@' in STRING with %40.
This is used to protect mailto links without modifying their meaning."
  ;; Suggested by Ville Skytta.
  (while (string-match "@" string)
    (setq string (replace-match "%40" nil t string)))
  string)

(defun htmlize-make-tmp-overlay (beg end props)
  (let ((overlay (make-overlay beg end)))
    (overlay-put overlay 'htmlize-tmp-overlay t)
    (while props
      (overlay-put overlay (pop props) (pop props)))
    overlay))

(defun htmlize-delete-tmp-overlays ()
  (dolist (overlay (overlays-in (point-min) (point-max)))
    (when (overlay-get overlay 'htmlize-tmp-overlay)
      (delete-overlay overlay))))

(defun htmlize-make-link-overlay (beg end uri)
  (htmlize-make-tmp-overlay beg end `(htmlize-link (:uri ,uri))))

(defun htmlize-create-auto-links ()
  "Add `htmlize-link' property to all mailto links in the buffer."
  (save-excursion
    (goto-char (point-min))
    (while (re-search-forward
            "<\\(\\(mailto:\\)?\\([-=+_.a-zA-Z0-9]+@[-_.a-zA-Z0-9]+\\)\\)>"
            nil t)
      (let* ((address (match-string 3))
             (beg (match-beginning 0)) (end (match-end 0))
             (uri (concat "mailto:" (htmlize-despam-address address))))
        (htmlize-make-link-overlay beg end uri)))
    (goto-char (point-min))
    (while (re-search-forward "<\\(\\(URL:\\)?\\([a-zA-Z]+://[^;]+\\)\\)>"
                              nil t)
      (htmlize-make-link-overlay
       (match-beginning 0) (match-end 0) (match-string 3)))))


;;; Tests for htmlize-create-auto-links:

;; 
;; 
;; 
;; 
;; 
;; 

(defun htmlize-shadow-form-feeds ()
  (let ((s (propertize "\n
" 'htmlize-literal t))) (let ((disp `(display ,s))) (while (re-search-forward "\n\^L" nil t) (let* ((beg (match-beginning 0)) (end (match-end 0)) (form-feed-pos (1+ beg)) ;; don't process ^L if invisible or covered by `display' (show (and (htmlize-decode-invisibility-spec (get-char-property form-feed-pos 'invisible)) (not (get-char-property form-feed-pos 'display))))) (when show (htmlize-make-tmp-overlay beg end disp))))))) (defun htmlize-defang-local-variables () ;; Juri Linkov reports that an HTML-ized "Local variables" can lead ;; visiting the HTML to fail with "Local variables list is not ;; properly terminated". He suggested changing the phrase to ;; syntactically equivalent HTML that Emacs doesn't recognize. (goto-char (point-min)) (while (search-forward "Local Variables:" nil t) (replace-match "Local Variables:" nil t))) ;;; Color handling. (defvar htmlize-x-library-search-path `(,data-directory "/etc/X11/rgb.txt" "/usr/share/X11/rgb.txt" ;; the remainder of this list really belongs in a museum "/usr/X11R6/lib/X11/" "/usr/X11R5/lib/X11/" "/usr/lib/X11R6/X11/" "/usr/lib/X11R5/X11/" "/usr/local/X11R6/lib/X11/" "/usr/local/X11R5/lib/X11/" "/usr/local/lib/X11R6/X11/" "/usr/local/lib/X11R5/X11/" "/usr/X11/lib/X11/" "/usr/lib/X11/" "/usr/local/lib/X11/" "/usr/X386/lib/X11/" "/usr/x386/lib/X11/" "/usr/XFree86/lib/X11/" "/usr/unsupported/lib/X11/" "/usr/athena/lib/X11/" "/usr/local/x11r5/lib/X11/" "/usr/lpp/Xamples/lib/X11/" "/usr/openwin/lib/X11/" "/usr/openwin/share/lib/X11/")) (defun htmlize-get-color-rgb-hash (&optional rgb-file) "Return a hash table mapping X color names to RGB values. The keys in the hash table are X11 color names, and the values are the #rrggbb RGB specifications, extracted from `rgb.txt'. If RGB-FILE is nil, the function will try hard to find a suitable file in the system directories. If no rgb.txt file is found, return nil." (let ((rgb-file (or rgb-file (locate-file "rgb.txt" htmlize-x-library-search-path))) (hash nil)) (when rgb-file (with-temp-buffer (insert-file-contents rgb-file) (setq hash (make-hash-table :test 'equal)) (while (not (eobp)) (cond ((looking-at "^\\s-*\\([!#]\\|$\\)") ;; Skip comments and empty lines. ) ((looking-at "[ \t]*\\([0-9]+\\)[ \t]+\\([0-9]+\\)[ \t]+\\([0-9]+\\)[ \t]+\\(.*\\)") (setf (gethash (downcase (match-string 4)) hash) (format "#%02x%02x%02x" (string-to-number (match-string 1)) (string-to-number (match-string 2)) (string-to-number (match-string 3))))) (t (error "Unrecognized line in %s: %s" rgb-file (buffer-substring (point) (progn (end-of-line) (point)))))) (forward-line 1)))) hash)) ;; Compile the RGB map when loaded. On systems where rgb.txt is ;; missing, the value of the variable will be nil, and rgb.txt will ;; not be used. (defvar htmlize-color-rgb-hash (htmlize-get-color-rgb-hash)) ;;; Face handling. (defun htmlize-face-color-internal (face fg) ;; Used only under GNU Emacs. Return the color of FACE, but don't ;; return "unspecified-fg" or "unspecified-bg". If the face is ;; `default' and the color is unspecified, look up the color in ;; frame parameters. (let* ((function (if fg #'face-foreground #'face-background)) (color (funcall function face nil t))) (when (and (eq face 'default) (null color)) (setq color (cdr (assq (if fg 'foreground-color 'background-color) (frame-parameters))))) (when (or (eq color 'unspecified) (equal color "unspecified-fg") (equal color "unspecified-bg")) (setq color nil)) (when (and (eq face 'default) (null color)) ;; Assuming black on white doesn't seem right, but I can't think ;; of anything better to do. (setq color (if fg "black" "white"))) color)) (defun htmlize-face-foreground (face) ;; Return the name of the foreground color of FACE. If FACE does ;; not specify a foreground color, return nil. (htmlize-face-color-internal face t)) (defun htmlize-face-background (face) ;; Return the name of the background color of FACE. If FACE does ;; not specify a background color, return nil. ;; GNU Emacs. (htmlize-face-color-internal face nil)) ;; Convert COLOR to the #RRGGBB string. If COLOR is already in that ;; format, it's left unchanged. (defun htmlize-color-to-rgb (color) (let ((rgb-string nil)) (cond ((null color) ;; Ignore nil COLOR because it means that the face is not ;; specifying any color. Hence (htmlize-color-to-rgb nil) ;; returns nil. ) ((string-match "\\`#[0-9a-fA-F]\\{6\\}" color) ;; The color is already in #rrggbb format. (setq rgb-string color)) ((and htmlize-use-rgb-txt htmlize-color-rgb-hash) ;; Use of rgb.txt is requested, and it's available on the ;; system. Use it. (setq rgb-string (gethash (downcase color) htmlize-color-rgb-hash))) (t ;; We're getting the RGB components from Emacs. (let ((rgb (mapcar (lambda (arg) (/ arg 256)) (color-values color)))) (when rgb (setq rgb-string (apply #'format "#%02x%02x%02x" rgb)))))) ;; If RGB-STRING is still nil, it means the color cannot be found, ;; for whatever reason. In that case just punt and return COLOR. ;; Most browsers support a decent set of color names anyway. (or rgb-string color))) ;; We store the face properties we care about into an ;; `htmlize-fstruct' type. That way we only have to analyze face ;; properties, which can be time consuming, once per each face. The ;; mapping between Emacs faces and htmlize-fstructs is established by ;; htmlize-make-face-map. The name "fstruct" refers to variables of ;; type `htmlize-fstruct', while the term "face" is reserved for Emacs ;; faces. (cl-defstruct htmlize-fstruct foreground ; foreground color, #rrggbb background ; background color, #rrggbb size ; size boldp ; whether face is bold italicp ; whether face is italic underlinep ; whether face is underlined overlinep ; whether face is overlined strikep ; whether face is struck through css-name ; CSS name of face ) (defun htmlize-face-set-from-keyword-attr (fstruct attr value) ;; For ATTR and VALUE, set the equivalent value in FSTRUCT. (cl-case attr (:foreground (setf (htmlize-fstruct-foreground fstruct) (htmlize-color-to-rgb value))) (:background (setf (htmlize-fstruct-background fstruct) (htmlize-color-to-rgb value))) (:height (setf (htmlize-fstruct-size fstruct) value)) (:weight (when (string-match (symbol-name value) "bold") (setf (htmlize-fstruct-boldp fstruct) t))) (:slant (setf (htmlize-fstruct-italicp fstruct) (or (eq value 'italic) (eq value 'oblique)))) (:bold (setf (htmlize-fstruct-boldp fstruct) value)) (:italic (setf (htmlize-fstruct-italicp fstruct) value)) (:underline (setf (htmlize-fstruct-underlinep fstruct) value)) (:overline (setf (htmlize-fstruct-overlinep fstruct) value)) (:strike-through (setf (htmlize-fstruct-strikep fstruct) value)))) (defun htmlize-face-size (face) ;; The size (height) of FACE, taking inheritance into account. ;; Only works in Emacs 21 and later. (let* ((face-list (list face)) (head face-list) (tail face-list)) (while head (let ((inherit (face-attribute (car head) :inherit))) (cond ((listp inherit) (setq tail (last inherit))) ((eq inherit 'unspecified)) (t (setcdr tail (list inherit)) (setq tail (cdr tail))))) (pop head)) (let ((size-list (cl-loop for f in face-list for h = (and (facep f) (face-attribute f :height)) collect (if (eq h 'unspecified) nil h)))) (cl-reduce 'htmlize-merge-size (cons nil size-list))))) (defun htmlize-face-css-name (face) ;; Generate the css-name property for the given face. Emacs places ;; no restrictions on the names of symbols that represent faces -- ;; any characters may be in the name, even control chars. We try ;; hard to beat the face name into shape, both esthetically and ;; according to CSS1 specs. (let ((name (downcase (symbol-name face)))) (when (string-match "\\`font-lock-" name) ;; font-lock-FOO-face -> FOO. (setq name (replace-match "" t t name))) (when (string-match "-face\\'" name) ;; Drop the redundant "-face" suffix. (setq name (replace-match "" t t name))) (while (string-match "[^-a-zA-Z0-9]" name) ;; Drop the non-alphanumerics. (setq name (replace-match "X" t t name))) (when (string-match "\\`[-0-9]" name) ;; CSS identifiers may not start with a digit. (setq name (concat "X" name))) ;; After these transformations, the face could come out empty. (when (equal name "") (setq name "face")) ;; Apply the prefix. (concat htmlize-css-name-prefix name))) (defun htmlize-face-to-fstruct-1 (face) "Convert Emacs face FACE to fstruct, internal." (let ((fstruct (make-htmlize-fstruct :foreground (htmlize-color-to-rgb (htmlize-face-foreground face)) :background (htmlize-color-to-rgb (htmlize-face-background face))))) ;; GNU Emacs (dolist (attr '(:weight :slant :underline :overline :strike-through)) (let ((value (face-attribute face attr nil t))) (when (and value (not (eq value 'unspecified))) (htmlize-face-set-from-keyword-attr fstruct attr value)))) (let ((size (htmlize-face-size face))) (unless (eql size 1.0) ; ignore non-spec (setf (htmlize-fstruct-size fstruct) size))) (setf (htmlize-fstruct-css-name fstruct) (htmlize-face-css-name face)) fstruct)) (defun htmlize-face-to-fstruct (face) (let* ((face-list (or (and (symbolp face) (cdr (assq face face-remapping-alist))) (list face))) (fstruct (htmlize-merge-faces (mapcar (lambda (face) (if (symbolp face) (or (htmlize-get-override-fstruct face) (htmlize-face-to-fstruct-1 face)) (htmlize-attrlist-to-fstruct face))) (nreverse face-list))))) (when (symbolp face) (setf (htmlize-fstruct-css-name fstruct) (htmlize-face-css-name face))) fstruct)) (defmacro htmlize-copy-attr-if-set (attr-list dest source) ;; Generate code with the following pattern: ;; (progn ;; (when (htmlize-fstruct-ATTR source) ;; (setf (htmlize-fstruct-ATTR dest) (htmlize-fstruct-ATTR source))) ;; ...) ;; for the given list of boolean attributes. (cons 'progn (cl-loop for attr in attr-list for attr-sym = (intern (format "htmlize-fstruct-%s" attr)) collect `(when (,attr-sym ,source) (setf (,attr-sym ,dest) (,attr-sym ,source)))))) (defun htmlize-merge-size (merged next) ;; Calculate the size of the merge of MERGED and NEXT. (cond ((null merged) next) ((integerp next) next) ((null next) merged) ((floatp merged) (* merged next)) ((integerp merged) (round (* merged next))))) (defun htmlize-merge-two-faces (merged next) (htmlize-copy-attr-if-set (foreground background boldp italicp underlinep overlinep strikep) merged next) (setf (htmlize-fstruct-size merged) (htmlize-merge-size (htmlize-fstruct-size merged) (htmlize-fstruct-size next))) merged) (defun htmlize-merge-faces (fstruct-list) (cond ((null fstruct-list) ;; Nothing to do, return a dummy face. (make-htmlize-fstruct)) ((null (cdr fstruct-list)) ;; Optimize for the common case of a single face, simply ;; return it. (car fstruct-list)) (t (cl-reduce #'htmlize-merge-two-faces (cons (make-htmlize-fstruct) fstruct-list))))) ;; GNU Emacs 20+ supports attribute lists in `face' properties. For ;; example, you can use `(:foreground "red" :weight bold)' as an ;; overlay's "face", or you can even use a list of such lists, etc. ;; We call those "attrlists". ;; ;; htmlize supports attrlist by converting them to fstructs, the same ;; as with regular faces. (defun htmlize-attrlist-to-fstruct (attrlist &optional name) ;; Like htmlize-face-to-fstruct, but accepts an ATTRLIST as input. (let ((fstruct (make-htmlize-fstruct))) (cond ((eq (car attrlist) 'foreground-color) ;; ATTRLIST is (foreground-color . COLOR) (setf (htmlize-fstruct-foreground fstruct) (htmlize-color-to-rgb (cdr attrlist)))) ((eq (car attrlist) 'background-color) ;; ATTRLIST is (background-color . COLOR) (setf (htmlize-fstruct-background fstruct) (htmlize-color-to-rgb (cdr attrlist)))) (t ;; ATTRLIST is a plist. (while attrlist (let ((attr (pop attrlist)) (value (pop attrlist))) (when (and value (not (eq value 'unspecified))) (htmlize-face-set-from-keyword-attr fstruct attr value)))))) (setf (htmlize-fstruct-css-name fstruct) (or name "custom")) fstruct)) (defun htmlize-decode-face-prop (prop) "Turn face property PROP into a list of face-like objects." ;; PROP can be a symbol naming a face, a string naming such a ;; symbol, a cons (foreground-color . COLOR) or (background-color ;; COLOR), a property list (:attr1 val1 :attr2 val2 ...), or a list ;; of any of those. ;; ;; (htmlize-decode-face-prop 'face) -> (face) ;; (htmlize-decode-face-prop '(face1 face2)) -> (face1 face2) ;; (htmlize-decode-face-prop '(:attr "val")) -> ((:attr "val")) ;; (htmlize-decode-face-prop '((:attr "val") face (foreground-color "red"))) ;; -> ((:attr "val") face (foreground-color "red")) ;; ;; Unrecognized atoms or non-face symbols/strings are silently ;; stripped away. (cond ((null prop) nil) ((symbolp prop) (and (facep prop) (list prop))) ((stringp prop) (and (facep (intern-soft prop)) (list prop))) ((atom prop) nil) ((and (symbolp (car prop)) (eq ?: (aref (symbol-name (car prop)) 0))) (list prop)) ((or (eq (car prop) 'foreground-color) (eq (car prop) 'background-color)) (list prop)) (t (apply #'nconc (mapcar #'htmlize-decode-face-prop prop))))) (defun htmlize-get-override-fstruct (face) (let* ((raw-def (plist-get htmlize-face-overrides face)) (def (cond ((stringp raw-def) (list :foreground raw-def)) ((listp raw-def) raw-def) (t (error "Face override must be %s, got %s" "an attribute list or string" raw-def))))) (and def (htmlize-attrlist-to-fstruct def (symbol-name face))))) (defun htmlize-make-face-map (faces) ;; Return a hash table mapping Emacs faces to htmlize's fstructs. ;; The keys are either face symbols or attrlists, so the test ;; function must be `equal'. (let ((face-map (make-hash-table :test 'equal)) css-names) (dolist (face faces) (unless (gethash face face-map) ;; Haven't seen FACE yet; convert it to an fstruct and cache ;; it. (let ((fstruct (htmlize-face-to-fstruct face))) (setf (gethash face face-map) fstruct) (let* ((css-name (htmlize-fstruct-css-name fstruct)) (new-name css-name) (i 0)) ;; Uniquify the face's css-name by using NAME-1, NAME-2, ;; etc. (while (member new-name css-names) (setq new-name (format "%s-%s" css-name (cl-incf i)))) (unless (equal new-name css-name) (setf (htmlize-fstruct-css-name fstruct) new-name)) (push new-name css-names))))) face-map)) (defun htmlize-unstringify-face (face) "If FACE is a string, return it interned, otherwise return it unchanged." (if (stringp face) (intern face) face)) (defun htmlize-faces-in-buffer () "Return a list of faces used in the current buffer. This is the set of faces specified by the `face' text property and by buffer overlays that specify `face'." (let (faces) ;; Faces used by text properties. (let ((pos (point-min)) face-prop next) (while (< pos (point-max)) (setq face-prop (get-text-property pos 'face) next (or (next-single-property-change pos 'face) (point-max))) (setq faces (cl-nunion (htmlize-decode-face-prop face-prop) faces :test 'equal)) (setq pos next))) ;; Faces used by overlays. (dolist (overlay (overlays-in (point-min) (point-max))) (let ((face-prop (overlay-get overlay 'face))) (setq faces (cl-nunion (htmlize-decode-face-prop face-prop) faces :test 'equal)))) faces)) ;; htmlize-faces-at-point returns the faces in use at point. The ;; faces are sorted by increasing priority, i.e. the last face takes ;; precedence. ;; ;; This returns all the faces in the `face' property and all the faces ;; in the overlays at point. (defun htmlize-faces-at-point () (let (all-faces) ;; Faces from text properties. (let ((face-prop (get-text-property (point) 'face))) ;; we need to reverse the `face' prop because we want ;; more specific faces to come later (setq all-faces (nreverse (htmlize-decode-face-prop face-prop)))) ;; Faces from overlays. (let ((overlays ;; Collect overlays at point that specify `face'. (cl-delete-if-not (lambda (o) (overlay-get o 'face)) (nreverse (overlays-at (point) t)))) list face-prop) (dolist (overlay overlays) (setq face-prop (overlay-get overlay 'face) list (nconc (htmlize-decode-face-prop face-prop) list))) ;; Under "Merging Faces" the manual explicitly states ;; that faces specified by overlays take precedence over ;; faces specified by text properties. (setq all-faces (nconc all-faces list))) all-faces)) ;; htmlize supports generating HTML in several flavors, some of which ;; use CSS, and others the element. We take an OO approach and ;; define "methods" that indirect to the functions that depend on ;; `htmlize-output-type'. The currently used methods are `doctype', ;; `insert-head', `body-tag', `pre-tag', and `text-markup'. Not all ;; output types define all methods. ;; ;; Methods are called either with (htmlize-method METHOD ARGS...) ;; special form, or by accessing the function with ;; (htmlize-method-function 'METHOD) and calling (funcall FUNCTION). ;; The latter form is useful in tight loops because `htmlize-method' ;; conses. (defmacro htmlize-method (method &rest args) ;; Expand to (htmlize-TYPE-METHOD ...ARGS...). TYPE is the value of ;; `htmlize-output-type' at run time. `(funcall (htmlize-method-function ',method) ,@args)) (defun htmlize-method-function (method) ;; Return METHOD's function definition for the current output type. ;; The returned object can be safely funcalled. (let ((sym (intern (format "htmlize-%s-%s" htmlize-output-type method)))) (indirect-function (if (fboundp sym) sym (let ((default (intern (format "htmlize-default-%s" method)))) (if (fboundp default) default 'ignore)))))) (defvar htmlize-memoization-table (make-hash-table :test 'equal)) (defmacro htmlize-memoize (key generator) "Return the value of GENERATOR, memoized as KEY. That means that GENERATOR will be evaluated and returned the first time it's called with the same value of KEY. All other times, the cached \(memoized) value will be returned." (let ((value (gensym))) `(let ((,value (gethash ,key htmlize-memoization-table))) (unless ,value (setq ,value ,generator) (setf (gethash ,key htmlize-memoization-table) ,value)) ,value))) ;;; Default methods. (defun htmlize-default-doctype () nil ; no doc-string ;; Note that the `font' output is technically invalid under this DTD ;; because the DTD doesn't allow embedding in
.
  "")

(defun htmlize-default-body-tag (face-map)
  nil                                   ; no doc-string
  face-map ; shut up the byte-compiler
  "")

(defun htmlize-default-pre-tag (face-map)
  nil                                   ; no doc-string
  face-map ; shut up the byte-compiler
  "
")


;;; CSS based output support.

;; Internal function; not a method.
(defun htmlize-css-specs (fstruct)
  (let (result)
    (when (htmlize-fstruct-foreground fstruct)
      (push (format "color: %s;" (htmlize-fstruct-foreground fstruct))
            result))
    (when (htmlize-fstruct-background fstruct)
      (push (format "background-color: %s;"
                    (htmlize-fstruct-background fstruct))
            result))
    (let ((size (htmlize-fstruct-size fstruct)))
      (when (and size (not (eq htmlize-ignore-face-size t)))
        (cond ((floatp size)
               (push (format "font-size: %d%%;" (* 100 size)) result))
              ((not (eq htmlize-ignore-face-size 'absolute))
               (push (format "font-size: %spt;" (/ size 10.0)) result)))))
    (when (htmlize-fstruct-boldp fstruct)
      (push "font-weight: bold;" result))
    (when (htmlize-fstruct-italicp fstruct)
      (push "font-style: italic;" result))
    (when (htmlize-fstruct-underlinep fstruct)
      (push "text-decoration: underline;" result))
    (when (htmlize-fstruct-overlinep fstruct)
      (push "text-decoration: overline;" result))
    (when (htmlize-fstruct-strikep fstruct)
      (push "text-decoration: line-through;" result))
    (nreverse result)))

(defun htmlize-css-insert-head (buffer-faces face-map)
  (insert "    \n"))

(defun htmlize-css-text-markup (fstruct-list buffer)
  ;; Open the markup needed to insert text colored with FACES into
  ;; BUFFER.  Return the function that closes the markup.

  ;; In CSS mode, this is easy: just nest the text in one  tag for each face in FSTRUCT-LIST.
  (dolist (fstruct fstruct-list)
    (princ "" buffer))
  (lambda ()
    (dolist (_fstruct fstruct-list)
      (princ "" buffer))))


;;; `inline-css' output support.

(defun htmlize-inline-css-body-tag (face-map)
  (format ""
          (mapconcat #'identity (htmlize-css-specs (gethash 'default face-map))
                     " ")))

(defun htmlize-inline-css-pre-tag (face-map)
  (if htmlize-pre-style
      (format "
"
              (mapconcat #'identity
                         (htmlize-css-specs (gethash 'default face-map))
                         " "))
    (format "
")))

(defun htmlize-inline-css-text-markup (fstruct-list buffer)
  (let* ((merged (htmlize-merge-faces fstruct-list))
         (style (htmlize-memoize
                 merged
                 (let ((specs (htmlize-css-specs merged)))
                   (and specs
                        (mapconcat #'identity
                                   (htmlize-css-specs merged)
                                   " "))))))
    (when style
      (princ "" buffer))
    (lambda ()
      (when style
        (princ "" buffer)))))


;;; `font' tag based output support.

(defun htmlize-font-body-tag (face-map)
  (let ((fstruct (gethash 'default face-map)))
    (format ""
            (htmlize-fstruct-foreground fstruct)
            (htmlize-fstruct-background fstruct))))

(defun htmlize-font-pre-tag (face-map)
  (if htmlize-pre-style
      (let ((fstruct (gethash 'default face-map)))
        (format "
"
                (htmlize-fstruct-foreground fstruct)
                (htmlize-fstruct-background fstruct)))
    (format "
")))

(defun htmlize-font-text-markup (fstruct-list buffer)
  ;; In `font' mode, we use the traditional HTML means of altering
  ;; presentation:  tag for colors,  for bold,  for
  ;; underline, and  for strike-through.
  (let* ((merged (htmlize-merge-faces fstruct-list))
         (markup (htmlize-memoize
                  merged
                  (cons (concat
                         (and (htmlize-fstruct-foreground merged)
                              (format ""
                                      (htmlize-fstruct-foreground merged)))
                         (and (htmlize-fstruct-boldp merged)      "")
                         (and (htmlize-fstruct-italicp merged)    "")
                         (and (htmlize-fstruct-underlinep merged) "")
                         (and (htmlize-fstruct-strikep merged)    ""))
                        (concat
                         (and (htmlize-fstruct-strikep merged)    "")
                         (and (htmlize-fstruct-underlinep merged) "")
                         (and (htmlize-fstruct-italicp merged)    "")
                         (and (htmlize-fstruct-boldp merged)      "")
                         (and (htmlize-fstruct-foreground merged) ""))))))
    (princ (car markup) buffer)
    (lambda ()
      (princ (cdr markup) buffer))))


;;; Utility functions.

(defun htmlize-buffer-1 ()
  ;; Internal function; don't call it from outside this file.  Htmlize
  ;; current buffer, writing the resulting HTML to a new buffer, and
  ;; return it.  Unlike htmlize-buffer, this doesn't change current
  ;; buffer or use switch-to-buffer.
  (save-excursion
    ;; Protect against the hook changing the current buffer.
    (save-excursion
      (run-hooks 'htmlize-before-hook))
    ;; Convince font-lock support modes to fontify the entire buffer
    ;; in advance.
    (message "Fontifing %s..." buffer-file-name)
    (font-lock-ensure)
    (message "Fontifing %s...done" buffer-file-name)
    (message "Htmlizing %s..." buffer-file-name)
    (clrhash htmlize-extended-character-cache)
    (clrhash htmlize-memoization-table)
    ;; It's important that the new buffer inherits default-directory
    ;; from the current buffer.
    (let ((htmlbuf (generate-new-buffer (if (buffer-file-name)
                                            (htmlize-make-file-name
                                             (file-name-nondirectory
                                              (buffer-file-name)))
                                          "*html*")))
          (completed nil))
      (unwind-protect
          (let* ((buffer-faces (htmlize-faces-in-buffer))
                 (face-map (htmlize-make-face-map
                            (cl-adjoin 'default buffer-faces)))
                 (places (gensym))
                 (title (if (buffer-file-name)
                            (file-name-nondirectory (buffer-file-name))
                          (buffer-name))))
            (when htmlize-generate-hyperlinks
              (htmlize-create-auto-links))
            (when htmlize-replace-form-feeds
              (htmlize-shadow-form-feeds))

            ;; Initialize HTMLBUF and insert the HTML prolog.
            (with-current-buffer htmlbuf
              (buffer-disable-undo)
              (insert (htmlize-method doctype) ?\n
                      (format "\n"
                              htmlize-version htmlize-output-type)
                      "\n  ")
              (put places 'head-start (point-marker))
              (insert "\n"
                      "    " (htmlize-protect-string title) "\n"
                      (if htmlize-html-charset
                          (format
                           (concat "    \n")
                           htmlize-html-charset)
                        "")
                      htmlize-head-tags)
              (htmlize-method insert-head buffer-faces face-map)
              (insert "  ")
              (put places 'head-end (point-marker))
              (insert "\n  ")
              (put places 'body-start (point-marker))
              (insert (htmlize-method body-tag face-map)
                      "\n    ")
              (put places 'content-start (point-marker))
              (insert (htmlize-method pre-tag face-map) "\n"))
            (let ((text-markup
                   ;; Get the inserter method, so we can funcall it inside
                   ;; the loop.  Not calling `htmlize-method' in the loop
                   ;; body yields a measurable speed increase.
                   (htmlize-method-function 'text-markup))
                  ;; Declare variables used in loop body outside the loop
                  ;; because it's faster to establish `let' bindings only
                  ;; once.
                  next-change text face-list trailing-ellipsis
                  fstruct-list last-fstruct-list
                  (close-markup (lambda ())))
              ;; This loop traverses and reads the source buffer, appending
              ;; the resulting HTML to HTMLBUF.  This method is fast
              ;; because: 1) it doesn't require examining the text
              ;; properties char by char (htmlize-next-face-change is used
              ;; to move between runs with the same face), and 2) it doesn't
              ;; require frequent buffer switches, which are slow because
              ;; they rebind all buffer-local vars.
              (goto-char (point-min))
              (while (not (eobp))
                (setq next-change (htmlize-next-face-change (point)))
                ;; Get faces in use between (point) and NEXT-CHANGE, and
                ;; convert them to fstructs.
                (setq face-list (htmlize-faces-at-point)
                      fstruct-list (delq nil (mapcar (lambda (f)
                                                       (gethash f face-map))
                                                     face-list)))
                (cl-multiple-value-setq (text trailing-ellipsis)
                  (htmlize-extract-text (point) next-change trailing-ellipsis))
                ;; Don't bother writing anything if there's no text (this
                ;; happens in invisible regions).
                (when (> (length text) 0)
                  ;; Open the new markup if necessary and insert the text.
                  (when (not (cl-equalp fstruct-list last-fstruct-list))
                    (funcall close-markup)
                    (setq last-fstruct-list fstruct-list)
                    (setq close-markup
                          (funcall text-markup fstruct-list htmlbuf)))
                  (princ text htmlbuf))
                (goto-char next-change))

              ;; We've gone through the buffer; close the markup from
              ;; the last run, if any.
              (funcall close-markup))

            ;; Insert the epilog and post-process the buffer.
            (with-current-buffer htmlbuf
              (insert "
") (put places 'content-end (point-marker)) (insert "\n ") (put places 'body-end (point-marker)) (insert "\n\n") (htmlize-defang-local-variables) (goto-char (point-min)) (when htmlize-html-major-mode ;; What sucks about this is that the minor modes, most notably ;; font-lock-mode, won't be initialized. Oh well. (funcall htmlize-html-major-mode)) (set (make-local-variable 'htmlize-buffer-places) (symbol-plist places)) (run-hooks 'htmlize-after-hook) (buffer-enable-undo)) (setq completed t) htmlbuf) (if completed (message "Htmlizing %s...done" buffer-file-name) (kill-buffer htmlbuf) (message "Htmlizing %s...failed" buffer-file-name)) (htmlize-delete-tmp-overlays))))) ;;;###autoload (defun htmlize-buffer (&optional buffer interactive) "Convert BUFFER to HTML, preserving colors and decorations. The generated HTML is available in a new buffer, which is returned. When invoked interactively (or if optional INTERACTIVE is non-nil), the new buffer is selected in the current window. The title of the generated document will be set to the buffer's file name or, if that is not available, to the buffer's name. Note that htmlize doesn't fontify your buffers, it only uses the decorations that are already present. If you don't set up font-lock or something else to fontify your buffers, the resulting HTML will be plain. Likewise, if you don't like the choice of colors, fix the mode that created them, or simply alter the faces it uses." (interactive "i\np") (let ((htmlbuf (with-current-buffer (or buffer (current-buffer)) (htmlize-buffer-1)))) (when interactive (switch-to-buffer htmlbuf)) htmlbuf)) ;;;###autoload (defun htmlize-region (beg end &optional interactive) "Convert the region to HTML, preserving colors and decorations. See `htmlize-buffer' for details." (interactive "r\np") ;; Don't let zmacs region highlighting end up in HTML. (when (fboundp 'zmacs-deactivate-region) (zmacs-deactivate-region)) (let ((htmlbuf (save-restriction (narrow-to-region beg end) (htmlize-buffer-1)))) (when interactive (switch-to-buffer htmlbuf)) htmlbuf)) (defun htmlize-region-for-paste (beg end) "Htmlize the region and return just the HTML as a string. This forces the `inline-css' style and only returns the HTML body, but without the BODY tag. This should make it useful for inserting the text to another HTML buffer." (let* ((htmlize-output-type 'inline-css) (htmlbuf (htmlize-region beg end))) (unwind-protect (with-current-buffer htmlbuf (buffer-substring (plist-get htmlize-buffer-places 'content-start) (plist-get htmlize-buffer-places 'content-end))) (kill-buffer htmlbuf)))) (defun htmlize-region-save-screenshot (beg end) "Save the htmlized (see `htmlize-region-for-paste') region in the kill ring. Uses `inline-css', with style information in `
' tags, so that the rendering of the marked up text
approximates the buffer as closely as possible."
  (interactive "r")
  (let ((htmlize-pre-style t))
    (kill-new (htmlize-region-for-paste beg end)))
  (deactivate-mark))

(defun htmlize-make-file-name (file)
  "Make an HTML file name from FILE.

In its default implementation, this simply appends `.html' to FILE.
This function is called by htmlize to create the buffer file name, and
by `htmlize-file' to create the target file name.

More elaborate transformations are conceivable, such as changing FILE's
extension to `.html' (\"file.c\" -> \"file.html\").  If you want them,
overload this function to do it and htmlize will comply."
  (concat file ".html"))

;;;###autoload
(defun htmlize-file (file &optional target)
  "Load FILE, fontify it, convert it to HTML, and save the result.

Contents of FILE are inserted into a temporary buffer, whose major mode
is set with `normal-mode' as appropriate for the file type.  The buffer
is subsequently fontified with `font-lock' and converted to HTML.  Note
that, unlike `htmlize-buffer', this function explicitly turns on
font-lock.  If a form of highlighting other than font-lock is desired,
please use `htmlize-buffer' directly on buffers so highlighted.

Buffers currently visiting FILE are unaffected by this function.  The
function does not change current buffer or move the point.

If TARGET is specified and names a directory, the resulting file will be
saved there instead of to FILE's directory.  If TARGET is specified and
does not name a directory, it will be used as output file name."
  (interactive (list (read-file-name
                      "HTML-ize file: "
                      nil nil nil (and (buffer-file-name)
                                       (file-name-nondirectory
                                        (buffer-file-name))))))
  (let ((output-file (if (and target (not (file-directory-p target)))
                         target
                       (expand-file-name
                        (htmlize-make-file-name (file-name-nondirectory file))
                        (or target (file-name-directory file))))))
    (with-temp-buffer
      ;; Insert FILE into the temporary buffer.
      (insert-file-contents file)
      ;; Set the file name so normal-mode and htmlize-buffer-1 pick it
      ;; up.  Restore it afterwards so with-temp-buffer's kill-buffer
      ;; doesn't complain about killing a modified buffer.
      (let ((buffer-file-name file))
        ;; Set the major mode for the sake of font-lock.
        (normal-mode)
        ;; htmlize the buffer and save the HTML.
        (with-current-buffer (htmlize-buffer-1)
          (unwind-protect
              (progn
                (run-hooks 'htmlize-file-hook)
                (write-region (point-min) (point-max) output-file))
            (kill-buffer (current-buffer)))))))
  ;; I haven't decided on a useful return value yet, so just return
  ;; nil.
  nil)

;;;###autoload
(defun htmlize-many-files (files &optional target-directory)
  "Convert FILES to HTML and save the corresponding HTML versions.

FILES should be a list of file names to convert.  This function calls
`htmlize-file' on each file; see that function for details.  When
invoked interactively, you are prompted for a list of files to convert,
terminated with RET.

If TARGET-DIRECTORY is specified, the HTML files will be saved to that
directory.  Normally, each HTML file is saved to the directory of the
corresponding source file."
  (interactive
   (list
    (let (list file)
      ;; Use empty string as DEFAULT because setting DEFAULT to nil
      ;; defaults to the directory name, which is not what we want.
      (while (not (equal (setq file (read-file-name
                                     "HTML-ize file (RET to finish): "
                                     (and list (file-name-directory
                                                (car list)))
                                     "" t))
                         ""))
        (push file list))
      (nreverse list))))
  ;; Verify that TARGET-DIRECTORY is indeed a directory.  If it's a
  ;; file, htmlize-file will use it as target, and that doesn't make
  ;; sense.
  (and target-directory
       (not (file-directory-p target-directory))
       (error "target-directory must name a directory: %s" target-directory))
  (dolist (file files)
    (htmlize-file file target-directory)))

(declare-function dired-get-marked-files "dired"
                  (&optional localp arg filter distinguish-one-marked error))

;;;###autoload
(defun htmlize-many-files-dired (arg &optional target-directory)
  "HTMLize dired-marked files."
  (interactive "P")
  (htmlize-many-files (dired-get-marked-files nil arg) target-directory))

(provide 'htmlize)

;; Local Variables:
;; indent-tabs-mode: nil
;; End:
;;; htmlize.el ends here