├── .gitignore ├── .gitattributes ├── NEWS ├── README.md ├── Makefile ├── LICENSE └── htmlize.el /.gitignore: -------------------------------------------------------------------------------- 1 | *.elc 2 | -------------------------------------------------------------------------------- /.gitattributes: -------------------------------------------------------------------------------- 1 | *.html linguist-generated 2 | -------------------------------------------------------------------------------- /NEWS: -------------------------------------------------------------------------------- 1 | htmlize NEWS -- history of user-visible changes. 2 | 3 | * Changes in htmlize 1.51 4 | 5 | ** `htmlize-face-overrides' can be used to override Emacs's face 6 | definitions. 7 | 8 | 9 | * Changes in htmlize 1.47 10 | 11 | ** GNU Emacs 21 is no longer supported. 12 | 13 | 14 | * Changes in htmlize 1.45 15 | 16 | ** Correctly handle :inherit specifying a list of faces. (This bug 17 | would cause an error in AUX TeX buffers.) 18 | 19 | 20 | * Changes in htmlize 1.44 21 | 22 | ** Faces specified in the `face' property are now prioritized the same 23 | way that Emacs redisplay does it: faces that appear earlier have 24 | precedence over those that appear later. 25 | 26 | 27 | * Changes in htmlize 1.41 28 | 29 | ** `before-string' and `after-string' overlay properties are now 30 | recognized by htmlize and inserted into the HTML. 31 | 32 | ** Images specified by `display' property are recognized and inserted 33 | into the HTML as . 34 | 35 | *** If the image data comes from a file, the image will be rendered as 36 | a relative URI that would resolve to that file. Images whose data 37 | comes from a string will be rendered inline as data: URIs. The flag 38 | `htmlize-force-inline-images' can be used to force inserting *all* 39 | images inline as data: URIs. 40 | 41 | ** The image's ALT text will be the text that the `display' property is 42 | replacing, if non-empty. 43 | 44 | ** Arbitrary links can now be added to the generated HTML. If htmlize 45 | encounters buffer text with `htmlize-link' property, it will wrap the 46 | text in .... If the property value is a string, it 47 | is interpreted as the URI. If it is a list, it should be a property 48 | list whose currently only defined key is :uri. 49 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Htmlize — Convert buffer text and decorations to HTML 2 | 3 | [![NonGNU ELPA](https://elpa.nongnu.org/nongnu/htmlize.svg)](https://elpa.nongnu.org/nongnu/htmlize.html) 4 | [![MELPA Stable](https://stable.melpa.org/packages/htmlize-badge.svg)](https://stable.melpa.org/#/htmlize) 5 | [![MELPA](https://melpa.org/packages/htmlize-badge.svg)](https://melpa.org/#/htmlize) 6 | 7 | This package converts the buffer text and the associated 8 | decorations to HTML. 9 | 10 | To use it, just switch to the buffer you want HTML-ized and type 11 | M-x htmlize-buffer. You will be switched to a new buffer 12 | that contains the resulting HTML code. You can edit and inspect this 13 | buffer, or you can just save it with C-x C-w. M-x 14 | htmlize-file will find a file, fontify it, and save the HTML 15 | version in `FILE.html`, without any additional intervention. M-x 16 | htmlize-many-files allows you to htmlize any number of files in 17 | the same manner. M-x htmlize-many-files-dired does the 18 | same for files marked in a dired buffer. 19 | 20 | Htmlize supports three types of HTML output, selected by setting 21 | `htmlize-output-type`: `css`, `inline-css` (optimized for code 22 | snippets), and `font` (simpler output, doesn't rely on CSS). See 23 | [`htmlize.el.html`][1] for an example of generated HTML. 24 | 25 | You can also use htmlize from your Emacs Lisp code. When called 26 | non-interactively, `htmlize-buffer` and `htmlize-region` will 27 | return the resulting HTML buffer, but will not change current 28 | buffer or move the point. Htmlize will do its best to work on 29 | non-windowing Emacs sessions but the result will be limited to 30 | colors supported by the terminal. 31 | 32 | [1]: http://htmlpreview.github.io/?https://github.com/emacsorphanage/htmlize/blob/master/htmlize.el.html 33 | -------------------------------------------------------------------------------- /Makefile: -------------------------------------------------------------------------------- 1 | -include .config.mk 2 | 3 | PKG = htmlize 4 | 5 | ELS = $(PKG).el 6 | ELCS = $(ELS:.el=.elc) 7 | HTML = $(ELS:.el=.el.html) 8 | 9 | DEPS = 10 | 11 | LOAD_PATH ?= $(addprefix -L ../,$(DEPS)) 12 | LOAD_PATH += -L . 13 | 14 | EMACS ?= emacs 15 | EMACS_ARGS ?= 16 | EMACS_Q_ARG ?= -Q 17 | EMACS_BATCH ?= $(EMACS) $(EMACS_Q_ARG) --batch $(EMACS_ARGS) $(LOAD_PATH) 18 | 19 | all: lisp 20 | 21 | help: 22 | $(info make all -- Build lisp) 23 | $(info make lisp -- Build lisp) 24 | $(info make redo -- Build lisp from scratch) 25 | $(info make htmlize -- Htmlize htmlize.el) 26 | $(info make clean -- Remove built files) 27 | @printf "\n" 28 | 29 | redo: clean lisp 30 | 31 | lisp: $(ELCS) autoloads check-declare 32 | 33 | autoloads: $(PKG)-autoloads.el 34 | 35 | %.elc: %.el 36 | @printf "Compiling $<\n" 37 | @$(EMACS_BATCH) --funcall batch-byte-compile $< 38 | 39 | check-declare: 40 | @printf " Checking function declarations\n" 41 | @$(EMACS_BATCH) --eval "(check-declare-directory default-directory)" 42 | 43 | %.el.html: %.el 44 | @$(EMACS) -Q $(EMACS_ARGS) $(LOAD_PATH) \ 45 | -l htmlize --eval "(progn (htmlize-file \"$<\") (kill-emacs))" 46 | 47 | htmlize: $(HTML) 48 | 49 | CLEAN = $(ELCS) $(PKG)-autoloads.el 50 | 51 | clean: 52 | @printf " Cleaning...\n" 53 | @rm -rf $(CLEAN) 54 | 55 | $(PKG)-autoloads.el: $(ELS) 56 | @printf " Creating $@\n" 57 | @$(EMACS_BATCH) --load autoload --eval "\ 58 | (let* ((file (expand-file-name \"$@\"))\ 59 | (generated-autoload-file file)\ 60 | (coding-system-for-write 'utf-8-emacs-unix)\ 61 | (backup-inhibited t)\ 62 | (version-control 'never)\ 63 | (inhibit-message t))\ 64 | (write-region (autoload-rubric file \"package\" t) nil file)\ 65 | (update-directory-autoloads default-directory))" \ 66 | 2>&1 | sed "/^Package autoload is deprecated$$/d" 67 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | -------------------------------------------------------------------------------- /htmlize.el: -------------------------------------------------------------------------------- 1 | ;;; htmlize.el --- Convert buffer text and decorations to HTML -*- lexical-binding: t -*- 2 | 3 | ;; Copyright (C) 1997-2003,2005,2006,2009,2011,2012,2014,2017,2018,2020 Hrvoje Niksic 4 | 5 | ;; Author: Hrvoje Niksic 6 | ;; Homepage: https://github.com/emacsorphanage/htmlize 7 | ;; Keywords: hypermedia, extensions 8 | ;; Package-Version: 1.59 9 | ;; Package-Requires: ((emacs "26.1")) 10 | 11 | ;; SPDX-License-Identifier: GPL-3.0-or-later 12 | 13 | ;; This file is free software: you can redistribute it and/or modify 14 | ;; it under the terms of the GNU General Public License as published 15 | ;; by the Free Software Foundation, either version 3 of the License, 16 | ;; or (at your option) any later version. 17 | ;; 18 | ;; This file is distributed in the hope that it will be useful, 19 | ;; but WITHOUT ANY WARRANTY; without even the implied warranty of 20 | ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 21 | ;; GNU General Public License for more details. 22 | ;; 23 | ;; You should have received a copy of the GNU General Public License 24 | ;; along with this file. If not, see . 25 | 26 | ;;; Commentary: 27 | 28 | ;; This package converts the buffer text and the associated 29 | ;; decorations to HTML. 30 | 31 | ;; To use it, just switch to the buffer you want HTML-ized and type 32 | ;; `M-x htmlize-buffer'. You will be switched to a new buffer that 33 | ;; contains the resulting HTML code. You can edit and inspect this 34 | ;; buffer, or you can just save it with C-x C-w. `M-x htmlize-file' 35 | ;; will find a file, fontify it, and save the HTML version in 36 | ;; FILE.html, without any additional intervention. `M-x 37 | ;; htmlize-many-files' allows you to htmlize any number of files in 38 | ;; the same manner. `M-x htmlize-many-files-dired' does the same for 39 | ;; files marked in a dired buffer. 40 | 41 | ;; Htmlize supports three types of HTML output, selected by setting 42 | ;; `htmlize-output-type': `css', `inline-css', and `font'. In `css' 43 | ;; mode, htmlize uses cascading style sheets to specify colors; it 44 | ;; generates classes that correspond to Emacs faces and uses ... to color parts of text. In this mode, the 46 | ;; produced HTML is valid under the 4.01 strict DTD, as confirmed by 47 | ;; the W3C validator. `inline-css' is like `css', except the CSS is 48 | ;; put directly in the STYLE attribute of the SPAN element, making it 49 | ;; possible to paste the generated HTML into existing HTML documents. 50 | ;; In `font' mode, htmlize uses ... to 51 | ;; colorize HTML, which is not standard-compliant, but works better in 52 | ;; older browsers. `css' mode is the default. 53 | 54 | ;; You can also use htmlize from your Emacs Lisp code. When called 55 | ;; non-interactively, `htmlize-buffer' and `htmlize-region' will 56 | ;; return the resulting HTML buffer, but will not change current 57 | ;; buffer or move the point. Htmlize will do its best to work on 58 | ;; non-windowing Emacs sessions but the result will be limited to 59 | ;; colors supported by the terminal. 60 | 61 | ;; The latest version is available at: 62 | ;; 63 | ;; 64 | 65 | ;; Thanks go to the many people who have sent reports and contributed 66 | ;; comments, suggestions, and fixes. They include Ron Gut, Bob 67 | ;; Weiner, Toni Drabik, Peter Breton, Ville Skytta, Thomas Vogels, 68 | ;; Juri Linkov, Maciek Pasternacki, and many others. 69 | 70 | ;; User quotes: "You sir, are a sick, sick, _sick_ person. :)" 71 | ;; -- Bill Perry, author of Emacs/W3 72 | 73 | 74 | ;;; Code: 75 | 76 | (require 'cl-lib) 77 | 78 | (defconst htmlize-version "1.59") 79 | 80 | (defgroup htmlize nil 81 | "Convert buffer text and faces to HTML." 82 | :group 'hypermedia) 83 | 84 | (defcustom htmlize-head-tags "" 85 | "Additional tags to insert within HEAD of the generated document." 86 | :type 'string 87 | :group 'htmlize) 88 | 89 | (defcustom htmlize-output-type 'css 90 | "Output type of generated HTML, one of `css', `inline-css', or `font'. 91 | When set to `css' (the default), htmlize will generate a style sheet 92 | with description of faces, and use it in the HTML document, specifying 93 | the faces in the actual text with . 94 | 95 | When set to `inline-css', the style will be generated as above, but 96 | placed directly in the STYLE attribute of the span ELEMENT: . This makes it easier to paste the resulting HTML to 98 | other documents. 99 | 100 | When set to `font', the properties will be set using layout tags 101 | , , , , and . 102 | 103 | `css' output is normally preferred, but `font' is still useful for 104 | supporting old, pre-CSS browsers, and both `inline-css' and `font' for 105 | easier embedding of colorized text in foreign HTML documents (no style 106 | sheet to carry around)." 107 | :type '(choice (const css) (const inline-css) (const font)) 108 | :group 'htmlize) 109 | 110 | (defcustom htmlize-use-images t 111 | "Whether htmlize generates `img' for images attached to buffer contents." 112 | :type 'boolean 113 | :group 'htmlize) 114 | 115 | (defcustom htmlize-force-inline-images nil 116 | "Non-nil means generate all images inline using data URLs. 117 | Normally htmlize converts image descriptors with :file properties to 118 | relative URIs, and those with :data properties to data URIs. With this 119 | flag set, the images specified as a file name are loaded into memory and 120 | embedded in the HTML as data URIs." 121 | :type 'boolean 122 | :group 'htmlize) 123 | 124 | (defcustom htmlize-max-alt-text 100 125 | "Maximum size of text to use as ALT text in images. 126 | 127 | Normally when htmlize encounters text covered by the `display' property 128 | that specifies an image, it generates an `alt' attribute containing the 129 | original text. If the text is larger than `htmlize-max-alt-text' characters, 130 | this will not be done." 131 | :type 'integer 132 | :group 'htmlize) 133 | 134 | (defcustom htmlize-transform-image 'htmlize-default-transform-image 135 | "Function called to modify the image descriptor. 136 | 137 | The function is called with the image descriptor found in the buffer and 138 | the text the image is supposed to replace. It should return a (possibly 139 | different) image descriptor property list or a replacement string to use 140 | instead of of the original buffer text. 141 | 142 | Returning nil is the same as returning the original text." 143 | :type 'boolean 144 | :group 'htmlize) 145 | 146 | (defcustom htmlize-generate-hyperlinks t 147 | "Non-nil means auto-generate the links from URLs and mail addresses in buffer. 148 | 149 | This is on by default; set it to nil if you don't want htmlize to 150 | autogenerate such links. Note that this option only turns off automatic 151 | search for contents that looks like URLs and converting them to links. 152 | It has no effect on whether htmlize respects the `htmlize-link' property." 153 | :type 'boolean 154 | :group 'htmlize) 155 | 156 | (defcustom htmlize-hyperlink-style " 157 | a { 158 | color: inherit; 159 | background-color: inherit; 160 | font: inherit; 161 | text-decoration: inherit; 162 | } 163 | a:hover { 164 | text-decoration: underline; 165 | } 166 | " 167 | "The CSS style used for hyperlinks when in CSS mode." 168 | :type 'string 169 | :group 'htmlize) 170 | 171 | (defcustom htmlize-replace-form-feeds t 172 | "Non-nil means replace form feeds in source code with HTML separators. 173 | Form feeds are the ^L characters at line beginnings that are sometimes 174 | used to separate sections of source code. If this variable is set to 175 | `t', form feed characters are replaced with the
separator. If this 176 | is a string, it specifies the replacement to use. Note that
 is
 177 | temporarily closed before the separator is inserted, so the default
 178 | replacement is effectively \"

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


--------------------------------------------------------------------------------