Syntax-Highlight-WithEmacs
view release on metacpan or search on metacpan
(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)
(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)
(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)
;;; Some cross-Emacs compatibility.
;; I try to conditionalize on features rather than Emacs version, but
;; in some cases checking against the version *is* necessary.
(defconst htmlize-running-xemacs (string-match "XEmacs" emacs-version))
;; 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.
(cond
(htmlize-running-xemacs
(defun htmlize-next-change (pos prop &optional limit)
(if prop
(next-single-char-property-change pos prop nil (or limit (point-max)))
(next-property-change pos nil (or limit (point-max)))))
(defun htmlize-next-face-change (pos &optional limit)
(htmlize-next-change pos 'face limit)))
(t
(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)))
(t
(error "htmlize requires next-single-property-change or \
next-single-char-property-change")))
(defmacro htmlize-lexlet (&rest letforms)
(declare (indent 1) (debug let))
(if (and (boundp 'lexical-binding)
lexical-binding)
`(let ,@letforms)
;; cl extensions have a macro implementing lexical let
`(lexical-let ,@letforms)))
;; Simple overlay emulation for XEmacs
(cond
(htmlize-running-xemacs
(defalias 'htmlize-make-overlay 'make-extent)
(defalias 'htmlize-overlay-put 'set-extent-property)
(defalias 'htmlize-overlay-get 'extent-property)
(defun htmlize-overlays-in (beg end) (extent-list nil beg end))
(defalias 'htmlize-delete-overlay 'detach-extent))
(t
(defalias 'htmlize-make-overlay 'make-overlay)
(defalias 'htmlize-overlay-put 'overlay-put)
(defalias 'htmlize-overlay-get 'overlay-get)
(defalias 'htmlize-overlays-in 'overlays-in)
(defalias 'htmlize-delete-overlay 'delete-overlay)))
;;; 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 "&#<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)
: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)
(format "<img src=\"data:image/%s;base64,%s\"%s />"
(or (plist-get imgprops :type) "")
(base64-encode-string (plist-get imgprops :data))
alt-attr)))))
(defconst htmlize-ellipsis "...")
(put-text-property 0 (length htmlize-ellipsis) 'htmlize-ellipsis t htmlize-ellipsis)
(defun htmlize-match-inv-spec (inv)
(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)
(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 (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)
(unless htmlize-running-xemacs
(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 ?\ ), except it doesn't cons.
(let ((v (make-vector 32 nil)))
(dotimes (i (length v))
(setf (aref v i) (make-string i ?\ )))
v))
(defun htmlize-untabify (text start-column)
(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.)
(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
(put-text-property 0 tab-size 'display display expanded-tab))
(push expanded-tab chunks))
(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)))
(setq text (htmlize-untabify text (current-column)))
(setq text (htmlize-string-to-html text))
(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 (htmlize-make-overlay beg end)))
(htmlize-overlay-put overlay 'htmlize-tmp-overlay t)
(while props
(htmlize-overlay-put overlay (pop props) (pop props)))
overlay))
(defun htmlize-delete-tmp-overlays ()
(dolist (overlay (htmlize-overlays-in (point-min) (point-max)))
(when (htmlize-overlay-get overlay 'htmlize-tmp-overlay)
(htmlize-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 "\n<hr />"))
(put-text-property 0 (length s) 'htmlize-literal t s)
(let ((disp `(display ,s)))
(while (re-search-forward "\n\^L" nil t)
(htmlize-make-tmp-overlay (match-beginning 0) (match-end 0) 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.
)
(setf (htmlize-fstruct-italicp fstruct) t))
(setf (htmlize-fstruct-strikep fstruct)
(face-strikethru-p face))
(setf (htmlize-fstruct-underlinep fstruct)
(face-underline-p 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))
(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
(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
(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)
;; 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) "ATTRLIST")
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-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 (if (symbolp face)
(htmlize-face-to-fstruct face)
(htmlize-attrlist-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 (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.
Under XEmacs, this returns the set of faces specified by the extents
with the `face' property. (This covers text properties as well.) Under
GNU Emacs, it returns the set of faces specified by the `face' text
property and by buffer overlays that specify `face'."
(let (faces)
;; Testing for (fboundp 'map-extents) doesn't work because W3
;; defines `map-extents' under FSF.
(if htmlize-running-xemacs
(let (face-prop)
(map-extents (lambda (extent ignored)
(setq face-prop (extent-face extent)
;; FACE-PROP can be a face or a list of
;; faces.
faces (if (listp face-prop)
(union face-prop faces)
(adjoin face-prop faces)))
nil)
nil
;; Specify endpoints explicitly to respect
;; narrowing.
(point-min) (point-max) nil nil 'face))
;; FSF Emacs code.
;; 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 (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 (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.
;;
;; Under XEmacs, this returns all the faces in all the extents at
;; point. Under GNU Emacs, this returns all the faces in the `face'
;; property and all the faces in the overlays at point.
(cond (htmlize-running-xemacs
(defun htmlize-faces-at-point ()
(let (extent extent-list face-list face-prop)
(while (setq extent (extent-at (point) nil 'face extent))
(push extent extent-list))
;; extent-list is in reverse display order, meaning that
;; smallest ones come last. That is the order we want,
;; except it can be overridden by the `priority' property.
(setq extent-list (stable-sort extent-list #'<
:key #'extent-priority))
(dolist (extent extent-list)
(setq face-prop (extent-face extent))
;; extent's face-list is in reverse order from what we
;; want, but the `nreverse' below will take care of it.
(setq face-list (if (listp face-prop)
(append face-prop face-list)
(cons face-prop face-list))))
(nreverse face-list))))
(t
(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'.
(delete-if-not (lambda (o)
(overlay-get o 'face))
(overlays-at (point))))
list face-prop)
;; Sort the overlays so the smaller (more specific) ones
;; come later. The number of overlays at each one
;; position should be very small, so the sort shouldn't
;; slow things down.
(setq overlays (sort* overlays
;; Sort by ascending...
#'<
;; ...overlay size.
:key (lambda (o)
(- (overlay-end o)
(overlay-start o)))))
;; Overlay priorities, if present, override the above
;; established order. Larger overlay priority takes
;; precedence and therefore comes later in the list.
(setq overlays (stable-sort
overlays
;; Reorder (stably) by acending...
#'<
;; ...overlay priority.
:key (lambda (o)
(or (overlay-get o 'priority) 0))))
(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', 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
;; 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)))
(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 (equalp fstruct-list last-fstruct-list))
(funcall close-markup)
(setq last-fstruct-list fstruct-list
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)
(when (not completed)
(kill-buffer htmlbuf))
(htmlize-delete-tmp-overlays)))))
;; Utility functions.
(defmacro htmlize-with-fontify-message (&rest body)
;; When forcing fontification of large buffers in
;; htmlize-ensure-fontified, inform the user that he is waiting for
;; font-lock, not for htmlize to finish.
`(progn
(if (> (buffer-size) 65536)
(message "Forcing fontification of %s..."
(buffer-name (current-buffer))))
,@body
(if (> (buffer-size) 65536)
(message "Forcing fontification of %s...done"
(buffer-name (current-buffer))))))
(defun htmlize-ensure-fontified ()
;; If font-lock is being used, ensure that the "support" modes
;; actually fontify the buffer. If font-lock is not in use, we
;; don't care because, except in htmlize-file, we don't force
;; font-lock on the user.
(when (and (boundp 'font-lock-mode)
font-lock-mode)
;; In part taken from ps-print-ensure-fontified in GNU Emacs 21.
(cond
((and (boundp 'jit-lock-mode)
(symbol-value 'jit-lock-mode))
(htmlize-with-fontify-message
(jit-lock-fontify-now (point-min) (point-max))))
((and (boundp 'lazy-lock-mode)
(symbol-value 'lazy-lock-mode))
(htmlize-with-fontify-message
(lazy-lock-fontify-region (point-min) (point-max))))
((and (boundp 'lazy-shot-mode)
(symbol-value 'lazy-shot-mode))
(htmlize-with-fontify-message
;; lazy-shot is amazing in that it must *refontify* the region,
;; even if the whole buffer has already been fontified. <sigh>
(lazy-shot-fontify-region (point-min) (point-max))))
;; There's also fast-lock, but we don't need to handle specially,
;; I think. fast-lock doesn't really defer fontification, it
;; just saves it to an external cache so it's not done twice.
)))
;;;###autoload
(defun htmlize-buffer (&optional buffer)
"Convert BUFFER to HTML, preserving colors and decorations.
The generated HTML is available in a new buffer, which is returned.
When invoked interactively, 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's 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)
( run in 2.676 seconds using v1.01-cache-2.11-cpan-2398b32b56e )