Skip to main content

html_minifier/
lib.rs

1/*!
2# HTML Minifier
3
4This library minifies HTML as you generate or read it. It preserves the content of `<pre>` and `<textarea>` elements and can also preserve `<code>` content. Embedded JavaScript and CSS are also minified by removing comments and whitespace.
5
6HTML is minified by the following rules:
7
8* ASCII control characters (0x00-0x08, 0x0B, 0x0E-0x1F, 0x7F) are always removed.
9* Comments can be optionally removed. (removed by default)
10  Empty comments are kept when needed to keep text from forming a different character reference or tag.
11* Unnecessary whitespace is removed.
12* HTML whitespace (spaces, tabs, line feeds, carriage returns and form feeds) is collapsed to a single space or line feed where applicable.
13* Empty attribute values are collapsed. (e.g `<input readonly="">` => `<input readonly>` )
14* The inner HTML of all elements is minified except for the following elements:
15  * `<pre>` and `<listing>`
16  * `<textarea>`
17  * `<title>` (only whitespace is collapsed)
18  * `<xmp>`, `<iframe>`, `<noembed>` and `<noframes>`
19  * `<svg>` and `<math>` (including their start tags and HTML children)
20  * `<plaintext>` (all content after its start tag is preserved until the end of input)
21  * `<code>` (optionally, minified by default)
22  * `<style>` (preserved if CSS minification is disabled or its `type` is unsupported)
23  * `<script>` (preserved if JavaScript minification is disabled or its `type` is unsupported)
24* Embedded JavaScript and CSS are minified by removing comments and whitespace.
25
26The original (non-minified) HTML doesn't need to be completely generated before using this library because this library doesn't do any deserialization to create DOMs.
27
28`digest` accepts byte slices, including chunks that split a UTF-8 character. Call `finish` after the last chunk. `get_html` returns the current output snapshot and may omit pending content until `finish` succeeds. `into_html` calls `finish` and returns the owned output buffer without copying it. The `minify` convenience function finishes the input automatically.
29
30`finish` reports incomplete tags, comments and special elements. It preserves a trailing literal `<` or `</`. It does not validate the whole document or require every ordinary element to have a closing tag.
31
32Foreign SVG and MathML content is preserved as one region, including comments and embedded code. HTML minification resumes after the region ends. Like browsers, an HTML tag that cannot be in foreign content, such as `<p>` directly in `<svg>`, ends the region. A `plaintext` element consumes all remaining input, including text that looks like an end tag. Preserved content still follows the control-character and line-break rules.
33
34## Examples
35
36```rust
37use html_minifier::HTMLMinifier;
38
39let mut html_minifier = HTMLMinifier::new();
40
41html_minifier.digest("<!DOCTYPE html>   <html  ").unwrap();
42html_minifier.digest("lang=  en >").unwrap();
43html_minifier.digest("
44<head>
45    <meta name=viewport>
46</head>
47").unwrap();
48html_minifier.digest("
49<body class=' container   bg-light '>
50    <input type='text' value='123   456' readonly=''  />
51
52    123456
53    <b>big</b> 789
54    ab
55    c
56    中文
57    字
58</body>
59").unwrap();
60html_minifier.digest("</html  >").unwrap();
61html_minifier.finish().unwrap();
62
63assert_eq!("<!DOCTYPE html> <html lang=en>
64<head>
65<meta name=viewport>
66</head>
67<body class='container bg-light'>
68<input type='text' value='123   456' readonly/>
69123456
70<b>big</b> 789
71ab
72c
73中文
74字
75</body>
76</html>".as_bytes(), html_minifier.get_html());
77```
78
79```rust
80use html_minifier::HTMLMinifier;
81
82let mut html_minifier = HTMLMinifier::new();
83
84html_minifier.digest("<pre  >   Hello  world!   </pre  >").unwrap();
85html_minifier.finish().unwrap();
86
87assert_eq!(b"<pre>   Hello  world!   </pre>", html_minifier.get_html());
88```
89
90```rust
91use html_minifier::HTMLMinifier;
92
93let mut html_minifier = HTMLMinifier::new();
94
95html_minifier.digest("<script type='  application/javascript '>   alert('Hello!')    ;   </script>").unwrap();
96html_minifier.finish().unwrap();
97
98assert_eq!("<script type='  application/javascript '>alert('Hello!');</script>".as_bytes(), html_minifier.get_html());
99```
100
101## Options and Embedded Code
102
103| Setter | Default | Effect |
104| --- | --- | --- |
105| `set_remove_comments` | `true` | Remove HTML comments outside preserved content, except empty comments needed to keep text from forming a different character reference or tag. |
106| `set_minify_code` | `true` | Minify HTML inside `<code>` elements. |
107| `set_minify_js` | `true` | Minify supported JavaScript content. |
108| `set_minify_css` | `true` | Minify supported CSS content. |
109
110Each option has a corresponding `get_` method. `HTMLMinifierHelper` exposes the same options as public fields. Set options before digesting the document. `reset` clears parsing state and output while keeping options and allocated capacity; the helper leaves its external writer unchanged.
111
112JavaScript and CSS can be disabled independently:
113
114```rust
115use html_minifier::HTMLMinifier;
116
117let mut html_minifier = HTMLMinifier::new();
118html_minifier.set_minify_js(false);
119html_minifier.digest("<style> p { color: red; } </style><script> a(); </script>").unwrap();
120
121let html = html_minifier.into_html().unwrap();
122assert_eq!(b"<style>p{color:red;}</style><script> a(); </script>", html.as_slice());
123```
124
125JavaScript minification supports an absent or empty `type`, `application/javascript`, `text/javascript`, and `module`.
126Leading and trailing ASCII whitespace is allowed only around the two JavaScript MIME types.
127CSS minification supports an absent or empty `type` and `text/css` without added whitespace.
128Type matching ignores ASCII case and decodes character references.
129The original attribute value is preserved.
130Other types keep their content unchanged.
131
132Removing a comment or `</>` must not join text into a different character reference or tag.
133For example, `&co<!-- note -->py;` becomes `&co<!---->py;` so its text stays `&copy;` instead of becoming `©`.
134Likewise, `a<<!-- note -->b` becomes `a<<!---->b` so `<b` does not start a tag.
135
136JavaScript and CSS minification only removes comments and whitespace, so the code keeps its meaning. JavaScript line breaks that automatic semicolon insertion (ASI) needs are kept. When the meaning of a slash is unclear, the rest of that script is preserved. Block comments whose text starts with `!` or contains `@lic` (such as `@license`) or `@preserve` are kept. Preserved content still follows the control-character removal rule above.
137
138## Errors
139
140`HTMLMinifierError` is non-exhaustive and includes `IncompleteInput` and `IOError`. Byte input is preserved without requiring each chunk to be valid UTF-8. Debug formatting also supports incomplete or invalid UTF-8.
141
142`IOError` shows the message of the underlying I/O error, and `source()` returns the source of that error. An error can leave partial output; reset the parser and use a fresh output destination before retrying a document.
143
144## Write HTML to a Writer
145
146Use `HTMLMinifierHelper` to supply an output writer. Wrap a file in `BufWriter` to combine small writes.
147
148```rust,no_run
149use html_minifier::HTMLMinifierHelper;
150
151use std::fs::File;
152use std::io::{BufWriter, Read, Write};
153
154let mut input_file = File::open("tests/data/w3schools.com_tryhow_css_example_website.htm").unwrap();
155let output_file = File::create("index.min.html").unwrap();
156let mut output = BufWriter::new(output_file);
157
158let mut buffer = [0u8; 256];
159
160let mut html_minifier_helper = HTMLMinifierHelper::new();
161
162loop {
163    let c = input_file.read(&mut buffer).unwrap();
164
165    if c == 0 {
166        break;
167    }
168
169    html_minifier_helper.digest(&buffer[..c], &mut output).unwrap();
170}
171
172html_minifier_helper.finish(&mut output).unwrap();
173output.flush().unwrap();
174```
175*/
176mod comment;
177mod css_minifier;
178mod errors;
179mod foreign_content;
180mod functions;
181mod html_minifier_helper;
182mod html_writer;
183mod js_minifier;
184mod script_data;
185
186use educe::Educe;
187pub use errors::*;
188pub use html_minifier_helper::*;
189pub use html_writer::*;
190
191use crate::functions::*;
192
193/// This struct helps you generate and minify your HTML code in the same time. The output destination is inside this struct.
194#[derive(Educe, Clone)]
195#[educe(Debug, Default(new))]
196pub struct HTMLMinifier {
197    helper: HTMLMinifierHelper,
198    #[educe(Debug(method = "str_bytes_fmt"))]
199    out:    Vec<u8>,
200}
201
202impl HTMLMinifier {
203    /// Set whether to remove HTML comments.
204    /// Empty comments are kept when needed to keep text from forming a different character reference or tag.
205    #[inline]
206    pub fn set_remove_comments(&mut self, remove_comments: bool) {
207        self.helper.remove_comments = remove_comments;
208    }
209
210    /// Set whether to minify the content in the `code` element.
211    #[inline]
212    pub fn set_minify_code(&mut self, minify_code: bool) {
213        self.helper.minify_code = minify_code;
214    }
215
216    /// Set whether to minify JavaScript in supported script elements.
217    #[inline]
218    pub fn set_minify_js(&mut self, minify_js: bool) {
219        self.helper.minify_js = minify_js;
220    }
221
222    /// Set whether to minify CSS in supported style elements.
223    #[inline]
224    pub fn set_minify_css(&mut self, minify_css: bool) {
225        self.helper.minify_css = minify_css;
226    }
227
228    /// Get whether to remove HTML comments.
229    #[inline]
230    pub const fn get_remove_comments(&self) -> bool {
231        self.helper.remove_comments
232    }
233
234    /// Get whether to minify the content in the `code` element.
235    #[inline]
236    pub const fn get_minify_code(&self) -> bool {
237        self.helper.minify_code
238    }
239
240    /// Get whether to minify JavaScript in supported script elements.
241    #[inline]
242    pub const fn get_minify_js(&self) -> bool {
243        self.helper.minify_js
244    }
245
246    /// Get whether to minify CSS in supported style elements.
247    #[inline]
248    pub const fn get_minify_css(&self) -> bool {
249        self.helper.minify_css
250    }
251}
252
253impl HTMLMinifier {
254    /// Reset this HTML minifier while keeping its options and allocated memory.
255    #[inline]
256    pub fn reset(&mut self) {
257        self.helper.reset();
258        self.out.clear();
259    }
260}
261
262impl HTMLMinifier {
263    /// Input some text to generate HTML code. It is not necessary to input a full HTML text at once.
264    #[inline]
265    pub fn digest<S: AsRef<[u8]>>(&mut self, text: S) -> Result<(), HTMLMinifierError> {
266        let text = text.as_ref();
267
268        self.out.reserve(text.len());
269
270        self.helper.digest(text, &mut self.out)
271    }
272
273    /// Finish the current input and report any incomplete tag or special element.
274    #[inline]
275    pub fn finish(&mut self) -> Result<(), HTMLMinifierError> {
276        self.helper.finish(&mut self.out)
277    }
278
279    /// Directly input some text to generate HTML code. The text will just be appended to the output buffer instead of being through the helper.
280    ///
281    /// # When to Use This?
282    ///
283    /// If the text has been minified, you can consider to use this method to get a better performance.
284    #[allow(clippy::missing_safety_doc)]
285    #[inline]
286    pub unsafe fn indigest<S: AsRef<[u8]>>(&mut self, text: S) {
287        self.out.extend_from_slice(text.as_ref());
288    }
289}
290
291impl HTMLMinifier {
292    /// Get the current output bytes, which may be incomplete until `finish` succeeds.
293    #[inline]
294    pub fn get_html(&self) -> &[u8] {
295        self.out.as_slice()
296    }
297
298    /// Finish the input and return its output buffer without copying it.
299    #[inline]
300    pub fn into_html(mut self) -> Result<Vec<u8>, HTMLMinifierError> {
301        self.finish()?;
302        Ok(self.out)
303    }
304}
305
306/// Minify HTML with the default options, which also minify embedded JavaScript and CSS.
307#[inline]
308pub fn minify<S: AsRef<str>>(html: S) -> Result<String, HTMLMinifierError> {
309    let mut minifier = HTMLMinifierHelper::new();
310
311    let html = html.as_ref();
312
313    let mut minified_html = String::with_capacity(html.len());
314
315    // The input is UTF-8, and the helper only removes ASCII bytes or whole comments and only adds ASCII bytes between characters.
316    let out = unsafe { minified_html.as_mut_vec() };
317    minifier.digest(html, out)?;
318    minifier.finish(out)?;
319
320    Ok(minified_html)
321}