1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
/*!
# HTML Minifier
This 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.
HTML is minified by the following rules:
* ASCII control characters (0x00-0x08, 0x0B, 0x0E-0x1F, 0x7F) are always removed.
* Comments can be optionally removed. (removed by default)
Empty comments are kept when needed to keep text from forming a different character reference or tag.
* Unnecessary whitespace is removed.
* HTML whitespace (spaces, tabs, line feeds, carriage returns and form feeds) is collapsed to a single space or line feed where applicable.
* Empty attribute values are collapsed. (e.g `<input readonly="">` => `<input readonly>` )
* The inner HTML of all elements is minified except for the following elements:
* `<pre>` and `<listing>`
* `<textarea>`
* `<title>` (only whitespace is collapsed)
* `<xmp>`, `<iframe>`, `<noembed>` and `<noframes>`
* `<svg>` and `<math>` (including their start tags and HTML children)
* `<plaintext>` (all content after its start tag is preserved until the end of input)
* `<code>` (optionally, minified by default)
* `<style>` (preserved if CSS minification is disabled or its `type` is unsupported)
* `<script>` (preserved if JavaScript minification is disabled or its `type` is unsupported)
* Embedded JavaScript and CSS are minified by removing comments and whitespace.
The 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.
`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.
`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.
Foreign 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.
## Examples
```rust
use html_minifier::HTMLMinifier;
let mut html_minifier = HTMLMinifier::new();
html_minifier.digest("<!DOCTYPE html> <html ").unwrap();
html_minifier.digest("lang= en >").unwrap();
html_minifier.digest("
<head>
<meta name=viewport>
</head>
").unwrap();
html_minifier.digest("
<body class=' container bg-light '>
<input type='text' value='123 456' readonly='' />
123456
<b>big</b> 789
ab
c
中文
字
</body>
").unwrap();
html_minifier.digest("</html >").unwrap();
html_minifier.finish().unwrap();
assert_eq!("<!DOCTYPE html> <html lang=en>
<head>
<meta name=viewport>
</head>
<body class='container bg-light'>
<input type='text' value='123 456' readonly/>
123456
<b>big</b> 789
ab
c
中文
字
</body>
</html>".as_bytes(), html_minifier.get_html());
```
```rust
use html_minifier::HTMLMinifier;
let mut html_minifier = HTMLMinifier::new();
html_minifier.digest("<pre > Hello world! </pre >").unwrap();
html_minifier.finish().unwrap();
assert_eq!(b"<pre> Hello world! </pre>", html_minifier.get_html());
```
```rust
use html_minifier::HTMLMinifier;
let mut html_minifier = HTMLMinifier::new();
html_minifier.digest("<script type=' application/javascript '> alert('Hello!') ; </script>").unwrap();
html_minifier.finish().unwrap();
assert_eq!("<script type=' application/javascript '>alert('Hello!');</script>".as_bytes(), html_minifier.get_html());
```
## Options and Embedded Code
| Setter | Default | Effect |
| --- | --- | --- |
| `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. |
| `set_minify_code` | `true` | Minify HTML inside `<code>` elements. |
| `set_minify_js` | `true` | Minify supported JavaScript content. |
| `set_minify_css` | `true` | Minify supported CSS content. |
Each 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.
JavaScript and CSS can be disabled independently:
```rust
use html_minifier::HTMLMinifier;
let mut html_minifier = HTMLMinifier::new();
html_minifier.set_minify_js(false);
html_minifier.digest("<style> p { color: red; } </style><script> a(); </script>").unwrap();
let html = html_minifier.into_html().unwrap();
assert_eq!(b"<style>p{color:red;}</style><script> a(); </script>", html.as_slice());
```
JavaScript minification supports an absent or empty `type`, `application/javascript`, `text/javascript`, and `module`.
Leading and trailing ASCII whitespace is allowed only around the two JavaScript MIME types.
CSS minification supports an absent or empty `type` and `text/css` without added whitespace.
Type matching ignores ASCII case and decodes character references.
The original attribute value is preserved.
Other types keep their content unchanged.
Removing a comment or `</>` must not join text into a different character reference or tag.
For example, `&co<!-- note -->py;` becomes `&co<!---->py;` so its text stays `©` instead of becoming `©`.
Likewise, `a<<!-- note -->b` becomes `a<<!---->b` so `<b` does not start a tag.
JavaScript 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.
## Errors
`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.
`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.
## Write HTML to a Writer
Use `HTMLMinifierHelper` to supply an output writer. Wrap a file in `BufWriter` to combine small writes.
```rust,no_run
use html_minifier::HTMLMinifierHelper;
use std::fs::File;
use std::io::{BufWriter, Read, Write};
let mut input_file = File::open("tests/data/w3schools.com_tryhow_css_example_website.htm").unwrap();
let output_file = File::create("index.min.html").unwrap();
let mut output = BufWriter::new(output_file);
let mut buffer = [0u8; 256];
let mut html_minifier_helper = HTMLMinifierHelper::new();
loop {
let c = input_file.read(&mut buffer).unwrap();
if c == 0 {
break;
}
html_minifier_helper.digest(&buffer[..c], &mut output).unwrap();
}
html_minifier_helper.finish(&mut output).unwrap();
output.flush().unwrap();
```
*/
use Educe;
pub use *;
pub use *;
pub use *;
use crate*;
/// This struct helps you generate and minify your HTML code in the same time. The output destination is inside this struct.
/// Minify HTML with the default options, which also minify embedded JavaScript and CSS.