html2text 0.5.0 → 0.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: 1a1e6fcee8973815b391ca28bd156a878e36594e0bfbece01f7ff8c67f6cad6f
4
- data.tar.gz: f515c6edb112deeae87f59b717aa4a2aed5d37b4b42db151fc49359f2b98d0b9
3
+ metadata.gz: 5d0ee5830d24c19672d267ad5c943d00d308569c87ee0eaa89c4abecd7475c72
4
+ data.tar.gz: efb5873799bc3f0a75e0faecf69709af256a25256b0ce0bc074d8acc99dde2ab
5
5
  SHA512:
6
- metadata.gz: 3972abc5f287146a5f43969fe3a37b83333559618b198ccc6ca3b105178c7cb37a03c9b44317428c8323c9b86e7e7a22a78276d9ddb7cccaab1819105e469a18
7
- data.tar.gz: dcc2f39ebc4d772b47762cacb5de22ab16f386fbc4952c7fcf72ae66938fffcacad1fad7062714fdebc21a6b74c802224d02b796c099d2a00d1b3d13729f5d6d
6
+ metadata.gz: fc5635a8c1e2aca406b8266532d0d05eb60a33221e96ec3c9886d18f8dea9d651e2b8d46308b90e27c47e553a53cd963d8f9d86f764f65b8fe572acf90a433df
7
+ data.tar.gz: 7469aa62d9ccc0f1eb7a90c8940b347bde7e89e914b937b9f3512a4b6ce745b85ea367ffac18a203be880f8079d5b4b2d21eca63585bc363d3d8ac2b74c53b3e
data/CHANGELOG.md CHANGED
@@ -1,60 +1,72 @@
1
- # Changelog
2
- All notable changes to this project will be documented in this file.
3
-
4
- The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
5
- and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
6
-
7
- ## [Unreleased](https://github.com/soundasleep/html2text_ruby/compare/v0.5.0...master)
8
-
9
- ## [0.5.0](https://github.com/soundasleep/html2text_ruby/compare/v0.4.0...v0.5.0) - 2026-07-08
10
- ### Added
11
- - Add a `wrap_links:` option to `Html2Text.convert` and `Html2Text.new` (default `true`); when `false`, hyperlinks render as `text: href` instead of markdown-style `[text](href)`. Only affects `<a href>` links — images and named anchors keep their `[bracketed]` format ([#40](https://github.com/soundasleep/html2text_ruby/pull/40))
12
- - Specs covering subclass overrides of `prefix_whitespace`, `suffix_whitespace`, `iterate_over`, `wrap_link` and `image_text`, plus unit specs for `fix_newlines` and `replace_entities` ([#41](https://github.com/soundasleep/html2text_ruby/pull/41))
13
-
14
- ### Changed
15
- - Require Ruby 3.3+, since all earlier Rubies are EOL; CI now tests Ruby 3.3, 3.4 and 4.0 ([#42](https://github.com/soundasleep/html2text_ruby/pull/42))
16
- - Reduce object allocations in `iterate_over` for ~1.6x faster conversion of large documents ([#41](https://github.com/soundasleep/html2text_ruby/pull/41))
17
- - Update development dependencies (rubocop 1.88, nokogiri 1.19 in the lockfile), removing the transitive `rexml` dependency ([#42](https://github.com/soundasleep/html2text_ruby/pull/42))
18
-
19
- ## [0.4.0](https://github.com/soundasleep/html2text_ruby/compare/0.3.1...v0.4.0) - 2024-06-08
20
- ### Added
21
- - Switch from Travis to Github Actions for Build and Test
22
- - Add rubocop for linting and cleanup existing violations ([#36](https://github.com/soundasleep/html2text_ruby/pull/36))
23
-
24
- ### Changed
25
- - Add support for Ruby 3.x, removed support for Ruby < 3.0 since it is EOL
26
- - Allow subclassing of `Html2Text` to override the default behaviour ([#30](https://github.com/soundasleep/html2text_ruby/pull/30))
27
-
28
- ### Fixed
29
- - Loosen nokogiri dependency to allow for nokogiri < 2.0 ([#17](https://github.com/soundasleep/html2text_ruby/pull/17))
30
- - Fix `NoMethodError` when parsing nodes with no name ([#15](https://github.com/soundasleep/html2text_ruby/pull/15))
31
-
32
- ## [0.3.1] - 2019-06-12
33
- ### Security
34
- - Bumped nokogiri requirement to ~> 1.10.3, resolving [CVE-2019-11068](https://nvd.nist.gov/vuln/detail/CVE-2019-11068)
35
- ([#8](https://github.com/soundasleep/html2text_ruby/issues/8))
36
-
37
- ## [0.3.0] - 2019-02-15
38
- ### Added
39
- - Zero-width non-joiners are now stripped ([#5](https://github.com/soundasleep/html2text_ruby/pull/5))
40
- - Support both UTF-8 and Windows-1252 encoded files
41
- - Support converting `<pre>` blocks, including whitespace within these blocks
42
- - MS Office (MsoNormal) documents are now rendered closer to actual render output
43
- - Note this assumes that the input MS Office document has standard `MsoNormal` CSS.
44
- This component is _not_ designed to try and interpret CSS within an HTML document.
45
-
46
- ### Changed
47
- - Behaviour with multiple and nested `<p>`, `<div>` tags has been improved to be more in line with
48
- actual browser render behaviour (see test suite)
49
-
50
- ### Fixed
51
- - Update nokogiri dependency to 1.8.5
52
-
53
- ## [0.2.1] - 2017-09-27
54
- ### Fixed
55
- - Convert non-string input into strings ([#3](https://github.com/soundasleep/html2text_ruby/pull/3))
56
-
57
- [Unreleased]: https://github.com/soundasleep/html2text_ruby/compare/0.3.1...HEAD
58
- [0.3.1]: https://github.com/soundasleep/html2text_ruby/compare/0.3.0...0.3.1
59
- [0.3.0]: https://github.com/soundasleep/html2text_ruby/compare/0.2.1...0.3.0
60
- [0.2.1]: https://github.com/soundasleep/html2text_ruby/compare/0.2.1...0.2.1
1
+ # Changelog
2
+ All notable changes to this project will be documented in this file.
3
+
4
+ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
5
+ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
6
+
7
+ ## [Unreleased](https://github.com/soundasleep/html2text_ruby/compare/v0.6.0...master)
8
+
9
+ ## [0.6.0](https://github.com/soundasleep/html2text_ruby/compare/v0.5.0...v0.6.0) - 2026-11-24
10
+ ### Added
11
+ - Enforce 100% line and branch coverage with SimpleCov; `rake` now runs RuboCop as well as the specs ([#47](https://github.com/soundasleep/html2text_ruby/pull/47))
12
+
13
+ ### Changed
14
+ - Convert documents with many sibling `<div>`s in linear instead of quadratic time: the stripped text lengths of a nested div and its parent are compared first, so the parent's text is no longer computed for every div (e.g. 625 KB of sibling divs: 13 s → 0.2 s) ([#45](https://github.com/soundasleep/html2text_ruby/pull/45))
15
+ - Re-enable RuboCop's complexity cops, with limits ratcheted to the current worst case ([#48](https://github.com/soundasleep/html2text_ruby/pull/48))
16
+ - Update development dependencies: bundler 4.1.0, bundler-audit 0.9.3, `actions/checkout` v7, and nokogiri 1.19.5 and json 2.21.2 in the lockfile ([#43](https://github.com/soundasleep/html2text_ruby/pull/43), [#44](https://github.com/soundasleep/html2text_ruby/pull/44), [#46](https://github.com/soundasleep/html2text_ruby/pull/46), [#47](https://github.com/soundasleep/html2text_ruby/pull/47))
17
+
18
+ ### Removed
19
+ - Unused private helpers `previous_node_name` and `previous_node_is_text?`; subclasses calling them should copy them ([#47](https://github.com/soundasleep/html2text_ruby/pull/47))
20
+
21
+ ## [0.5.0](https://github.com/soundasleep/html2text_ruby/compare/v0.4.0...v0.5.0) - 2026-07-08
22
+ ### Added
23
+ - Add a `wrap_links:` option to `Html2Text.convert` and `Html2Text.new` (default `true`); when `false`, hyperlinks render as `text: href` instead of markdown-style `[text](href)`. Only affects `<a href>` links — images and named anchors keep their `[bracketed]` format ([#40](https://github.com/soundasleep/html2text_ruby/pull/40))
24
+ - Specs covering subclass overrides of `prefix_whitespace`, `suffix_whitespace`, `iterate_over`, `wrap_link` and `image_text`, plus unit specs for `fix_newlines` and `replace_entities` ([#41](https://github.com/soundasleep/html2text_ruby/pull/41))
25
+
26
+ ### Changed
27
+ - Require Ruby 3.3+, since all earlier Rubies are EOL; CI now tests Ruby 3.3, 3.4 and 4.0 ([#42](https://github.com/soundasleep/html2text_ruby/pull/42))
28
+ - Reduce object allocations in `iterate_over` for ~1.6x faster conversion of large documents ([#41](https://github.com/soundasleep/html2text_ruby/pull/41))
29
+ - Update development dependencies (rubocop 1.88, nokogiri 1.19 in the lockfile), removing the transitive `rexml` dependency ([#42](https://github.com/soundasleep/html2text_ruby/pull/42))
30
+
31
+ ## [0.4.0](https://github.com/soundasleep/html2text_ruby/compare/0.3.1...v0.4.0) - 2024-06-08
32
+ ### Added
33
+ - Switch from Travis to Github Actions for Build and Test
34
+ - Add rubocop for linting and cleanup existing violations ([#36](https://github.com/soundasleep/html2text_ruby/pull/36))
35
+
36
+ ### Changed
37
+ - Add support for Ruby 3.x, removed support for Ruby < 3.0 since it is EOL
38
+ - Allow subclassing of `Html2Text` to override the default behaviour ([#30](https://github.com/soundasleep/html2text_ruby/pull/30))
39
+
40
+ ### Fixed
41
+ - Loosen nokogiri dependency to allow for nokogiri < 2.0 ([#17](https://github.com/soundasleep/html2text_ruby/pull/17))
42
+ - Fix `NoMethodError` when parsing nodes with no name ([#15](https://github.com/soundasleep/html2text_ruby/pull/15))
43
+
44
+ ## [0.3.1] - 2019-06-12
45
+ ### Security
46
+ - Bumped nokogiri requirement to ~> 1.10.3, resolving [CVE-2019-11068](https://nvd.nist.gov/vuln/detail/CVE-2019-11068)
47
+ ([#8](https://github.com/soundasleep/html2text_ruby/issues/8))
48
+
49
+ ## [0.3.0] - 2019-02-15
50
+ ### Added
51
+ - Zero-width non-joiners are now stripped ([#5](https://github.com/soundasleep/html2text_ruby/pull/5))
52
+ - Support both UTF-8 and Windows-1252 encoded files
53
+ - Support converting `<pre>` blocks, including whitespace within these blocks
54
+ - MS Office (MsoNormal) documents are now rendered closer to actual render output
55
+ - Note this assumes that the input MS Office document has standard `MsoNormal` CSS.
56
+ This component is _not_ designed to try and interpret CSS within an HTML document.
57
+
58
+ ### Changed
59
+ - Behaviour with multiple and nested `<p>`, `<div>` tags has been improved to be more in line with
60
+ actual browser render behaviour (see test suite)
61
+
62
+ ### Fixed
63
+ - Update nokogiri dependency to 1.8.5
64
+
65
+ ## [0.2.1] - 2017-09-27
66
+ ### Fixed
67
+ - Convert non-string input into strings ([#3](https://github.com/soundasleep/html2text_ruby/pull/3))
68
+
69
+ [Unreleased]: https://github.com/soundasleep/html2text_ruby/compare/0.3.1...HEAD
70
+ [0.3.1]: https://github.com/soundasleep/html2text_ruby/compare/0.3.0...0.3.1
71
+ [0.3.0]: https://github.com/soundasleep/html2text_ruby/compare/0.2.1...0.3.0
72
+ [0.2.1]: https://github.com/soundasleep/html2text_ruby/compare/0.2.1...0.2.1
data/LICENSE.md CHANGED
@@ -1,20 +1,20 @@
1
- Copyright 2015 Jevon Wright
2
-
3
- Permission is hereby granted, free of charge, to any person obtaining
4
- a copy of this software and associated documentation files (the
5
- "Software"), to deal in the Software without restriction, including
6
- without limitation the rights to use, copy, modify, merge, publish,
7
- distribute, sublicense, and/or sell copies of the Software, and to
8
- permit persons to whom the Software is furnished to do so, subject to
9
- the following conditions:
10
-
11
- The above copyright notice and this permission notice shall be
12
- included in all copies or substantial portions of the Software.
13
-
14
- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
15
- EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
16
- MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
17
- NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
18
- LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
19
- OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
20
- WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
1
+ Copyright 2015 Jevon Wright
2
+
3
+ Permission is hereby granted, free of charge, to any person obtaining
4
+ a copy of this software and associated documentation files (the
5
+ "Software"), to deal in the Software without restriction, including
6
+ without limitation the rights to use, copy, modify, merge, publish,
7
+ distribute, sublicense, and/or sell copies of the Software, and to
8
+ permit persons to whom the Software is furnished to do so, subject to
9
+ the following conditions:
10
+
11
+ The above copyright notice and this permission notice shall be
12
+ included in all copies or substantial portions of the Software.
13
+
14
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
15
+ EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
16
+ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
17
+ NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
18
+ LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
19
+ OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
20
+ WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
data/README.md CHANGED
@@ -1,75 +1,75 @@
1
- html2text ![Build](https://github.com/soundasleep/html2text_ruby/actions/workflows/build.yml/badge.svg) [![Gem Version](https://badge.fury.io/rb/html2text.svg)](https://badge.fury.io/rb/html2text)
2
- ---
3
-
4
- `html2text` is a very simple gem that uses DOM methods to convert HTML into a format similar to what would be
5
- rendered by a browser - perfect for places where you need a quick text representation. For example:
6
-
7
- ```html
8
- <html>
9
- <title>Ignored Title</title>
10
- <body>
11
- <h1>Hello, World!</h1>
12
-
13
- <p>This is some e-mail content.
14
- Even though it has whitespace and newlines, the e-mail converter
15
- will handle it correctly.
16
-
17
- <p>Even mismatched tags.</p>
18
-
19
- <div>A div</div>
20
- <div>Another div</div>
21
- <div>A div<div>within a div</div></div>
22
-
23
- <a href="https://foo.com">A link</a>
24
-
25
- </body>
26
- </html>
27
- ```
28
-
29
- Will be converted into:
30
-
31
- ```text
32
- Hello, World!
33
-
34
- This is some e-mail content. Even though it has whitespace and newlines, the e-mail converter will handle it correctly.
35
-
36
- Even mismatched tags.
37
-
38
- A div
39
- Another div
40
- A div
41
- within a div
42
-
43
- [A link](https://foo.com)
44
- ```
45
-
46
- See the [original blog post](http://journals.jevon.org/users/jevon-phd/entry/19818) or the related [StackOverflow answer](http://stackoverflow.com/a/2564472/39531).
47
-
48
- ## Installing
49
-
50
- Add [the gem](https://rubygems.org/gems/html2text) into your Gemfile and run `bundle install`:
51
-
52
- ```ruby
53
- gem 'html2text'
54
- ```
55
-
56
- Then you can:
57
-
58
- ```ruby
59
- require 'html2text'
60
-
61
- text = Html2Text.convert(html)
62
- ```
63
-
64
- ## Tests
65
-
66
- See all of the test cases defined in [spec/examples/](spec/examples/). These can be run with `bundle exec rake`.
67
-
68
- ## License
69
-
70
- `html2text` is [licensed under MIT](LICENSE.md).
71
-
72
- ## Other versions
73
-
74
- 1. [html2text](https://github.com/soundasleep/html2text), the original PHP implementation.
75
- 2. [actionmailer-html2text](https://github.com/soundasleep/actionmailer-html2text), automatically generate text parts for HTML emails sent with ActionMailer.
1
+ html2text ![Build](https://github.com/soundasleep/html2text_ruby/actions/workflows/build.yml/badge.svg) [![Gem Version](https://badge.fury.io/rb/html2text.svg)](https://badge.fury.io/rb/html2text) ![Coverage](https://img.shields.io/badge/coverage-100%25-brightgreen)
2
+ ---
3
+
4
+ `html2text` is a very simple gem that uses DOM methods to convert HTML into a format similar to what would be
5
+ rendered by a browser - perfect for places where you need a quick text representation. For example:
6
+
7
+ ```html
8
+ <html>
9
+ <title>Ignored Title</title>
10
+ <body>
11
+ <h1>Hello, World!</h1>
12
+
13
+ <p>This is some e-mail content.
14
+ Even though it has whitespace and newlines, the e-mail converter
15
+ will handle it correctly.
16
+
17
+ <p>Even mismatched tags.</p>
18
+
19
+ <div>A div</div>
20
+ <div>Another div</div>
21
+ <div>A div<div>within a div</div></div>
22
+
23
+ <a href="https://foo.com">A link</a>
24
+
25
+ </body>
26
+ </html>
27
+ ```
28
+
29
+ Will be converted into:
30
+
31
+ ```text
32
+ Hello, World!
33
+
34
+ This is some e-mail content. Even though it has whitespace and newlines, the e-mail converter will handle it correctly.
35
+
36
+ Even mismatched tags.
37
+
38
+ A div
39
+ Another div
40
+ A div
41
+ within a div
42
+
43
+ [A link](https://foo.com)
44
+ ```
45
+
46
+ See the [original blog post](http://journals.jevon.org/users/jevon-phd/entry/19818) or the related [StackOverflow answer](http://stackoverflow.com/a/2564472/39531).
47
+
48
+ ## Installing
49
+
50
+ Add [the gem](https://rubygems.org/gems/html2text) into your Gemfile and run `bundle install`:
51
+
52
+ ```ruby
53
+ gem 'html2text'
54
+ ```
55
+
56
+ Then you can:
57
+
58
+ ```ruby
59
+ require 'html2text'
60
+
61
+ text = Html2Text.convert(html)
62
+ ```
63
+
64
+ ## Tests
65
+
66
+ See all of the test cases defined in [spec/examples/](spec/examples/). These can be run with `bundle exec rake`.
67
+
68
+ ## License
69
+
70
+ `html2text` is [licensed under MIT](LICENSE.md).
71
+
72
+ ## Other versions
73
+
74
+ 1. [html2text](https://github.com/soundasleep/html2text), the original PHP implementation.
75
+ 2. [actionmailer-html2text](https://github.com/soundasleep/actionmailer-html2text), automatically generate text parts for HTML emails sent with ActionMailer.
@@ -1,5 +1,5 @@
1
- # frozen_string_literal: true
2
-
3
- class Html2Text
4
- VERSION = '0.5.0'
5
- end
1
+ # frozen_string_literal: true
2
+
3
+ class Html2Text
4
+ VERSION = '0.6.0'
5
+ end
data/lib/html2text.rb CHANGED
@@ -1,256 +1,252 @@
1
- # frozen_string_literal: true
2
-
3
- require 'nokogiri'
4
-
5
- class Html2Text
6
- attr_reader :doc
7
-
8
- def initialize(doc, wrap_links: true)
9
- @doc = doc
10
- @wrap_links = wrap_links
11
- end
12
-
13
- def self.convert(html, wrap_links: true)
14
- html = html.to_s
15
-
16
- if office_document?(html)
17
- # Emulate the CSS rendering of Office documents
18
- html = html.gsub('<p class=MsoNormal>', '<br>')
19
- .gsub('<o:p>&nbsp;</o:p>', '<br>')
20
- .gsub('<o:p></o:p>', '')
21
- end
22
-
23
- unless html.include?('<html')
24
- # Stop Nokogiri from inserting in <p> tags
25
- html = "<div>#{html}</div>"
26
- end
27
-
28
- html = fix_newlines(replace_entities(html))
29
- doc = Nokogiri::HTML(html)
30
-
31
- new(doc, wrap_links: wrap_links).convert
32
- end
33
-
34
- def self.fix_newlines(text)
35
- # rubocop:disable Performance/StringReplacement
36
- text.gsub("\r\n", "\n").gsub("\r", "\n")
37
- # rubocop:enable Performance/StringReplacement
38
- end
39
-
40
- def self.replace_entities(text)
41
- # rubocop:disable Performance/StringReplacement
42
- text.gsub('&nbsp;', ' ').gsub("\u00a0", ' ').gsub('&zwnj;', '')
43
- # rubocop:enable Performance/StringReplacement
44
- end
45
-
46
- def convert
47
- output = iterate_over(doc)
48
- output = remove_leading_and_trailing_whitespace(output)
49
- output = remove_unnecessary_empty_lines(output)
50
- output.strip
51
- end
52
-
53
- DO_NOT_TOUCH_WHITESPACE = '<do-not-touch-whitespace>'
54
- IGNORED_TAGS = Set.new(%w[style head title meta script]).freeze
55
-
56
- def remove_leading_and_trailing_whitespace(text)
57
- # ignore any <pre> blocks, which we don't want to interact with
58
- pre_blocks = text.split(DO_NOT_TOUCH_WHITESPACE)
59
-
60
- output = []
61
- pre_blocks.each.with_index do |block, index|
62
- output << if index.even?
63
- block.gsub(/[ \t]*\n[ \t]*/im, "\n").gsub(/ *\t */im, "\t")
64
- else
65
- block
66
- end
67
- end
68
-
69
- output.join
70
- end
71
-
72
- private_class_method def self.office_document?(text)
73
- text.include?('urn:schemas-microsoft-com:office')
74
- end
75
-
76
- private
77
-
78
- def remove_unnecessary_empty_lines(text)
79
- text.gsub(/\n{3,}/, "\n\n")
80
- end
81
-
82
- def trimmed_whitespace(text)
83
- # Replace whitespace characters with a space (equivalent to \s)
84
- # and force any text encoding into UTF-8
85
- if text.valid_encoding?
86
- text.gsub(/[\t\n\f\r ]+/, ' ')
87
- else
88
- text.force_encoding('WINDOWS-1252')
89
- trimmed_whitespace(text.encode('UTF-16be', invalid: :replace, replace: '?').encode('UTF-8'))
90
- end
91
- end
92
-
93
- def iterate_over(node)
94
- return trimmed_whitespace(node.text) if node.text?
95
-
96
- name = node.name&.downcase
97
-
98
- return '' if name.nil? || IGNORED_TAGS.include?(name)
99
-
100
- return "\n" if name == 'br' && next_node_is_text?(node)
101
-
102
- return "\n#{DO_NOT_TOUCH_WHITESPACE}#{node.text}#{DO_NOT_TOUCH_WHITESPACE}" if name == 'pre'
103
-
104
- return image_text(node) if name == 'img'
105
-
106
- output = +''
107
- output << (prefix_whitespace(node) || '')
108
- node.children.each do |child|
109
- output << iterate_over(child)
110
- end
111
- output << (suffix_whitespace(node) || '')
112
-
113
- output = wrap_link(node, output) if name == 'a'
114
-
115
- output
116
- end
117
-
118
- def prefix_whitespace(node)
119
- case node.name.downcase
120
- when 'hr'
121
- "\n---------------------------------------------------------------\n"
122
-
123
- when 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'ol', 'ul', 'p'
124
- "\n\n"
125
-
126
- when 'tr'
127
- "\n"
128
-
129
- when 'div'
130
- if node.parent.name == 'div' && (node.parent.text.strip == node.text.strip)
131
- ''
132
- else
133
- "\n"
134
- end
135
-
136
- when 'td', 'th'
137
- "\t"
138
-
139
- when 'li'
140
- '- '
141
- end
142
- end
143
-
144
- def suffix_whitespace(node)
145
- case node.name.downcase
146
- when 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'p'
147
- "\n\n"
148
-
149
- when 'br'
150
- next_name = next_node_name(node)
151
- "\n" if !next_name.nil? && next_name != 'div'
152
-
153
- when 'li'
154
- "\n"
155
-
156
- when 'div'
157
- if next_node_is_text?(node)
158
- "\n"
159
- else
160
- next_name = next_node_name(node)
161
- "\n" if !next_name.nil? && next_name != 'div'
162
- end
163
- end
164
- end
165
-
166
- # links are returned in [text](link) format, or "text: link" with wrap_links: false
167
- def wrap_link(node, output)
168
- href = node.attribute('href')
169
- name = node.attribute('name')
170
-
171
- output = output.strip
172
-
173
- # remove double [[ ]]s from linking images
174
- if output[0] == '[' && output[-1] == ']'
175
- output = output[1, output.length - 2]
176
-
177
- # for linking images, the title of the <a> overrides the title of the <img>
178
- output = node.attribute('title').to_s if node.attribute('title')
179
- end
180
-
181
- # if there is no link text, but a title attr
182
- output = node.attribute('title').to_s if output.empty? && node.attribute('title')
183
-
184
- if href.nil?
185
- output = "[#{output}]" unless name.nil?
186
- else
187
- href = href.to_s
188
-
189
- if href != output && href != "mailto:#{output}" &&
190
- href != "http://#{output}" && href != "https://#{output}"
191
- output = if output.empty?
192
- href
193
- elsif !@wrap_links
194
- "#{output}: #{href}"
195
- else
196
- "[#{output}](#{href})"
197
- end
198
- end
199
- end
200
-
201
- case next_node_name(node)
202
- when 'h1', 'h2', 'h3', 'h4', 'h5', 'h6'
203
- output += "\n"
204
- end
205
-
206
- output
207
- end
208
-
209
- def image_text(node)
210
- if node.attribute('title')
211
- "[#{node.attribute('title')}]"
212
- elsif node.attribute('alt')
213
- "[#{node.attribute('alt')}]"
214
- else
215
- ''
216
- end
217
- end
218
-
219
- def next_node_name(node)
220
- next_node = node.next_sibling
221
- until next_node.nil?
222
- break if next_node.element?
223
-
224
- next_node = next_node.next_sibling
225
- end
226
-
227
- return unless next_node&.element?
228
-
229
- next_node.name.downcase
230
- end
231
-
232
- def next_node_is_text?(node)
233
- !node.next_sibling.nil? && node.next_sibling.text? && !node.next_sibling.text.strip.empty?
234
- end
235
-
236
- def previous_node_name(node)
237
- previous_node = node.previous_sibling
238
- until previous_node.nil?
239
- break if previous_node.element?
240
-
241
- previous_node = previous_node.previous_sibling
242
- end
243
-
244
- return unless previous_node&.element?
245
-
246
- previous_node.name.downcase
247
- end
248
-
249
- def previous_node_is_text?(node)
250
- !node.previous_sibling.nil? && node.previous_sibling.text? && !node.previous_sibling.text.strip.empty?
251
- end
252
-
253
- # def previous_node_is_not_text?(node)
254
- # return node.previous_sibling.nil? || !node.previous_sibling.text? || node.previous_sibling.text.strip.empty?
255
- # end
256
- end
1
+ # frozen_string_literal: true
2
+
3
+ require 'nokogiri'
4
+
5
+ # Converts HTML into plain text, approximating how a browser would render it.
6
+ class Html2Text
7
+ attr_reader :doc
8
+
9
+ def initialize(doc, wrap_links: true)
10
+ @doc = doc
11
+ @wrap_links = wrap_links
12
+ end
13
+
14
+ def self.convert(html, wrap_links: true)
15
+ html = html.to_s
16
+
17
+ if office_document?(html)
18
+ # Emulate the CSS rendering of Office documents
19
+ html = html.gsub('<p class=MsoNormal>', '<br>')
20
+ .gsub('<o:p>&nbsp;</o:p>', '<br>')
21
+ .gsub('<o:p></o:p>', '')
22
+ end
23
+
24
+ unless html.include?('<html')
25
+ # Stop Nokogiri from inserting in <p> tags
26
+ html = "<div>#{html}</div>"
27
+ end
28
+
29
+ html = fix_newlines(replace_entities(html))
30
+ doc = Nokogiri::HTML(html)
31
+
32
+ new(doc, wrap_links: wrap_links).convert
33
+ end
34
+
35
+ def self.fix_newlines(text)
36
+ # rubocop:disable Performance/StringReplacement
37
+ text.gsub("\r\n", "\n").gsub("\r", "\n")
38
+ # rubocop:enable Performance/StringReplacement
39
+ end
40
+
41
+ def self.replace_entities(text)
42
+ # rubocop:disable Performance/StringReplacement
43
+ text.gsub('&nbsp;', ' ').gsub("\u00a0", ' ').gsub('&zwnj;', '')
44
+ # rubocop:enable Performance/StringReplacement
45
+ end
46
+
47
+ def convert
48
+ output = iterate_over(doc)
49
+ output = remove_leading_and_trailing_whitespace(output)
50
+ output = remove_unnecessary_empty_lines(output)
51
+ output.strip
52
+ end
53
+
54
+ DO_NOT_TOUCH_WHITESPACE = '<do-not-touch-whitespace>'
55
+ IGNORED_TAGS = Set.new(%w[style head title meta script]).freeze
56
+
57
+ def remove_leading_and_trailing_whitespace(text)
58
+ # ignore any <pre> blocks, which we don't want to interact with
59
+ pre_blocks = text.split(DO_NOT_TOUCH_WHITESPACE)
60
+
61
+ output = []
62
+ pre_blocks.each.with_index do |block, index|
63
+ output << if index.even?
64
+ block.gsub(/[ \t]*\n[ \t]*/im, "\n").gsub(/ *\t */im, "\t")
65
+ else
66
+ block
67
+ end
68
+ end
69
+
70
+ output.join
71
+ end
72
+
73
+ private_class_method def self.office_document?(text)
74
+ text.include?('urn:schemas-microsoft-com:office')
75
+ end
76
+
77
+ private
78
+
79
+ def remove_unnecessary_empty_lines(text)
80
+ text.gsub(/\n{3,}/, "\n\n")
81
+ end
82
+
83
+ def trimmed_whitespace(text)
84
+ # Replace whitespace characters with a space (equivalent to \s)
85
+ # and force any text encoding into UTF-8
86
+ if text.valid_encoding?
87
+ text.gsub(/[\t\n\f\r ]+/, ' ')
88
+ else
89
+ text.force_encoding('WINDOWS-1252')
90
+ trimmed_whitespace(text.encode('UTF-16be', invalid: :replace, replace: '?').encode('UTF-8'))
91
+ end
92
+ end
93
+
94
+ def iterate_over(node)
95
+ return trimmed_whitespace(node.text) if node.text?
96
+
97
+ name = node.name&.downcase
98
+
99
+ return '' if name.nil? || IGNORED_TAGS.include?(name)
100
+
101
+ return "\n" if name == 'br' && next_node_is_text?(node)
102
+
103
+ return "\n#{DO_NOT_TOUCH_WHITESPACE}#{node.text}#{DO_NOT_TOUCH_WHITESPACE}" if name == 'pre'
104
+
105
+ return image_text(node) if name == 'img'
106
+
107
+ output = +''
108
+ output << (prefix_whitespace(node) || '')
109
+ node.children.each do |child|
110
+ output << iterate_over(child)
111
+ end
112
+ output << (suffix_whitespace(node) || '')
113
+
114
+ output = wrap_link(node, output) if name == 'a'
115
+
116
+ output
117
+ end
118
+
119
+ def prefix_whitespace(node)
120
+ case node.name.downcase
121
+ when 'hr'
122
+ "\n---------------------------------------------------------------\n"
123
+
124
+ when 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'ol', 'ul', 'p'
125
+ "\n\n"
126
+
127
+ when 'tr'
128
+ "\n"
129
+
130
+ when 'div'
131
+ if node.parent.name == 'div' && same_text_as_parent?(node)
132
+ ''
133
+ else
134
+ "\n"
135
+ end
136
+
137
+ when 'td', 'th'
138
+ "\t"
139
+
140
+ when 'li'
141
+ '- '
142
+ end
143
+ end
144
+
145
+ def suffix_whitespace(node)
146
+ case node.name.downcase
147
+ when 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'p'
148
+ "\n\n"
149
+
150
+ when 'br'
151
+ next_name = next_node_name(node)
152
+ "\n" if !next_name.nil? && next_name != 'div'
153
+
154
+ when 'li'
155
+ "\n"
156
+
157
+ when 'div'
158
+ if next_node_is_text?(node)
159
+ "\n"
160
+ else
161
+ next_name = next_node_name(node)
162
+ "\n" if !next_name.nil? && next_name != 'div'
163
+ end
164
+ end
165
+ end
166
+
167
+ # links are returned in [text](link) format, or "text: link" with wrap_links: false
168
+ def wrap_link(node, output)
169
+ href = node.attribute('href')
170
+ name = node.attribute('name')
171
+
172
+ output = output.strip
173
+
174
+ # remove double [[ ]]s from linking images
175
+ if output[0] == '[' && output[-1] == ']'
176
+ output = output[1, output.length - 2]
177
+
178
+ # for linking images, the title of the <a> overrides the title of the <img>
179
+ output = node.attribute('title').to_s if node.attribute('title')
180
+ end
181
+
182
+ # if there is no link text, but a title attr
183
+ output = node.attribute('title').to_s if output.empty? && node.attribute('title')
184
+
185
+ if href.nil?
186
+ output = "[#{output}]" unless name.nil?
187
+ else
188
+ href = href.to_s
189
+
190
+ if href != output && href != "mailto:#{output}" &&
191
+ href != "http://#{output}" && href != "https://#{output}"
192
+ output = if output.empty?
193
+ href
194
+ elsif !@wrap_links
195
+ "#{output}: #{href}"
196
+ else
197
+ "[#{output}](#{href})"
198
+ end
199
+ end
200
+ end
201
+
202
+ case next_node_name(node)
203
+ when 'h1', 'h2', 'h3', 'h4', 'h5', 'h6'
204
+ output += "\n"
205
+ end
206
+
207
+ output
208
+ end
209
+
210
+ def image_text(node)
211
+ if node.attribute('title')
212
+ "[#{node.attribute('title')}]"
213
+ elsif node.attribute('alt')
214
+ "[#{node.attribute('alt')}]"
215
+ else
216
+ ''
217
+ end
218
+ end
219
+
220
+ # Comparing the lengths first avoids computing the parent's text for every
221
+ # child div, which made converting many sibling divs quadratic. If a
222
+ # sibling has text, the parent's text is longer than the div's, so the texts
223
+ # are only compared for at most one child per parent (and not at all when
224
+ # both are empty).
225
+ def same_text_as_parent?(node)
226
+ text = node.text.strip
227
+ length = stripped_text_length(node.parent)
228
+ text.length == length && (length.zero? || node.parent.text.strip == text)
229
+ end
230
+
231
+ def stripped_text_length(node)
232
+ @stripped_text_lengths ||= {}.compare_by_identity
233
+ @stripped_text_lengths[node] ||= node.text.strip.length
234
+ end
235
+
236
+ def next_node_name(node)
237
+ next_node = node.next_sibling
238
+ until next_node.nil?
239
+ break if next_node.element?
240
+
241
+ next_node = next_node.next_sibling
242
+ end
243
+
244
+ return unless next_node&.element?
245
+
246
+ next_node.name.downcase
247
+ end
248
+
249
+ def next_node_is_text?(node)
250
+ !node.next_sibling.nil? && node.next_sibling.text? && !node.next_sibling.text.strip.empty?
251
+ end
252
+ end
metadata CHANGED
@@ -1,7 +1,7 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: html2text
3
3
  version: !ruby/object:Gem::Version
4
- version: 0.5.0
4
+ version: 0.6.0
5
5
  platform: ruby
6
6
  authors:
7
7
  - Jevon Wright
@@ -141,6 +141,20 @@ dependencies:
141
141
  - - ">="
142
142
  - !ruby/object:Gem::Version
143
143
  version: '0'
144
+ - !ruby/object:Gem::Dependency
145
+ name: simplecov
146
+ requirement: !ruby/object:Gem::Requirement
147
+ requirements:
148
+ - - ">="
149
+ - !ruby/object:Gem::Version
150
+ version: '0'
151
+ type: :development
152
+ prerelease: false
153
+ version_requirements: !ruby/object:Gem::Requirement
154
+ requirements:
155
+ - - ">="
156
+ - !ruby/object:Gem::Version
157
+ version: '0'
144
158
  description: A Ruby component to convert HTML into a plain text format.
145
159
  email:
146
160
  - jevon@jevon.org
@@ -172,7 +186,7 @@ required_rubygems_version: !ruby/object:Gem::Requirement
172
186
  - !ruby/object:Gem::Version
173
187
  version: '0'
174
188
  requirements: []
175
- rubygems_version: 4.0.10
189
+ rubygems_version: 4.0.20
176
190
  specification_version: 4
177
191
  summary: Convert HTML into plain text.
178
192
  test_files: []