asciidown 0.1.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 +7 -0
- data/LICENSE.txt +21 -0
- data/README.md +111 -0
- data/bin/asciidoc2md +6 -0
- data/bin/asciidown +6 -0
- data/lib/asciidown/block_helpers.rb +82 -0
- data/lib/asciidown/cli.rb +77 -0
- data/lib/asciidown/constants.rb +76 -0
- data/lib/asciidown/converter.rb +387 -0
- data/lib/asciidown/document_state.rb +49 -0
- data/lib/asciidown/substitutors.rb +161 -0
- data/lib/asciidown/version.rb +5 -0
- data/lib/asciidown.rb +77 -0
- metadata +62 -0
checksums.yaml
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
---
|
|
2
|
+
SHA256:
|
|
3
|
+
metadata.gz: 425b4694d41e2ef9122fa15b08aefd1fc24b13c52107755b765baf0e69198936
|
|
4
|
+
data.tar.gz: 03a244945f538be210d9001c3cfa8e731e8f757942fcbefb382583dcc09951bd
|
|
5
|
+
SHA512:
|
|
6
|
+
metadata.gz: 78d0a226c07ede3e8ddd14372f1b6da643083f78e4aeb35f9e6c73faea40e173ba200f7a7205ca468b06a93958ecb3c8208f22c56a98457b7070450930404532
|
|
7
|
+
data.tar.gz: 9bb8f5ac415457271114e15ff6f1df744e8d15522fcc8aab99ec4363b6ba53b656acf0214f46cf8c6fe5f788b79046d6ac3457da3ad1ed3dbd2f2c8d6b12f2ce
|
data/LICENSE.txt
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Evgenii Zinner
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
data/README.md
ADDED
|
@@ -0,0 +1,111 @@
|
|
|
1
|
+
# asciidown
|
|
2
|
+
|
|
3
|
+
A fast, lightweight, pure Ruby converter from AsciiDoc to GitHub Flavored Markdown (GFM). Zero external dependencies.
|
|
4
|
+
|
|
5
|
+
[](https://github.com/Evgenii-Zinner/asciidown/actions/workflows/ci.yml)
|
|
6
|
+
[](https://codecov.io/gh/Evgenii-Zinner/asciidown)
|
|
7
|
+
[](https://badge.fury.io/rb/asciidown)
|
|
8
|
+
[](https://opensource.org/licenses/MIT)
|
|
9
|
+
|
|
10
|
+
## Features
|
|
11
|
+
|
|
12
|
+
- **Pure Ruby:** 100% dependency-free, runs in-memory with zero native or Node.js runtime requirements.
|
|
13
|
+
- **YAML Front Matter:** Automatically extracts document title and headers (`:author:`, `:tags:`, `:published: true`) into YAML Front Matter or ATX headings.
|
|
14
|
+
- **Liquid Tag Preservation:** Preserves `{% embed %}`, `{% youtube %}`, and `{{ var }}` without mangling (great for static site generators and blogging platforms).
|
|
15
|
+
- **Syntax Highlighting & Callouts:** Converts `[source,ruby]` listings with dynamic backtick fences (safely handles nested backticks) and translates callout numbers (`<1>`, `<2>`) into unicode circled numbers (`①`, `②`).
|
|
16
|
+
- **Tables:** Full AsciiDoc pipe table (`|===`) conversion to GFM pipe tables with column alignment (`cols="<,^,>"`), empty cell preservation, and escaped pipe support.
|
|
17
|
+
- **Blockquotes & Admonitions:** Formats single-line (`NOTE:`) and block admonitions (`[WARNING]` + `====`), as well as blockquotes (`____`) with optional author attributions (`— Author`).
|
|
18
|
+
- **Lists & Inlines:** Multi-level bulleted (`*`, `**`) and numbered (`.`, `..`) lists, headings (`==` to `======`), bold, italic, bold-italic, strikethrough, highlights (`<mark>`), cross-references (`<<anchor,Label>>`), images, and links.
|
|
19
|
+
- **CLI Executable:** Includes `asciidown` (and `asciidoc2md` alias) for command-line conversion and shell pipelines.
|
|
20
|
+
|
|
21
|
+
## Installation
|
|
22
|
+
|
|
23
|
+
Add this line to your application's `Gemfile`:
|
|
24
|
+
|
|
25
|
+
```ruby
|
|
26
|
+
gem "asciidown"
|
|
27
|
+
```
|
|
28
|
+
|
|
29
|
+
And then execute:
|
|
30
|
+
|
|
31
|
+
```bash
|
|
32
|
+
$ bundle install
|
|
33
|
+
```
|
|
34
|
+
|
|
35
|
+
Or install it yourself as:
|
|
36
|
+
|
|
37
|
+
```bash
|
|
38
|
+
$ gem install asciidown
|
|
39
|
+
```
|
|
40
|
+
|
|
41
|
+
## Usage
|
|
42
|
+
|
|
43
|
+
### Ruby API
|
|
44
|
+
|
|
45
|
+
```ruby
|
|
46
|
+
require "asciidown"
|
|
47
|
+
|
|
48
|
+
asciidoc = <<~ADOC
|
|
49
|
+
= Scaling Rails Applications
|
|
50
|
+
:author: Jane Developer
|
|
51
|
+
:tags: ruby, rails
|
|
52
|
+
|
|
53
|
+
== Introduction
|
|
54
|
+
Check out our guide at https://example.com[Documentation].
|
|
55
|
+
|
|
56
|
+
[source,ruby]
|
|
57
|
+
----
|
|
58
|
+
def hello
|
|
59
|
+
puts "world" <1>
|
|
60
|
+
end
|
|
61
|
+
----
|
|
62
|
+
ADOC
|
|
63
|
+
|
|
64
|
+
# Convert with YAML front matter
|
|
65
|
+
markdown = Asciidown.call(asciidoc)
|
|
66
|
+
puts markdown
|
|
67
|
+
|
|
68
|
+
# Convert with ATX H1 heading instead of front matter
|
|
69
|
+
markdown_plain = Asciidown.call(asciidoc, front_matter: false)
|
|
70
|
+
```
|
|
71
|
+
|
|
72
|
+
### Command Line Interface
|
|
73
|
+
|
|
74
|
+
```bash
|
|
75
|
+
# Convert a file to standard output
|
|
76
|
+
$ asciidown article.adoc
|
|
77
|
+
|
|
78
|
+
# Convert a file and save to output
|
|
79
|
+
$ asciidown article.adoc -o article.md
|
|
80
|
+
|
|
81
|
+
# Pipe through STDIN
|
|
82
|
+
$ cat article.adoc | asciidown > article.md
|
|
83
|
+
|
|
84
|
+
# Disable YAML front matter (produce standard ATX H1 heading)
|
|
85
|
+
$ asciidown --no-front-matter article.adoc
|
|
86
|
+
```
|
|
87
|
+
|
|
88
|
+
## Architecture
|
|
89
|
+
|
|
90
|
+
The gem is built around clean, modular subcomponents:
|
|
91
|
+
- `Asciidown::Converter`: Core parser state machine processing AsciiDoc line streams into GFM blocks.
|
|
92
|
+
- `Asciidown::Substitutors`: Inline text substitutions for quotes, attributes, macros, and callout numbers.
|
|
93
|
+
- `Asciidown::BlockHelpers`: Helper logic for heading detection, list markers, and block titles.
|
|
94
|
+
- `Asciidown::DocumentState`: Manages document attributes, section cross-references, and delimiter nesting.
|
|
95
|
+
- `Asciidown::CLI`: Standard command-line interface with option parsing and stream routing.
|
|
96
|
+
|
|
97
|
+
## Development
|
|
98
|
+
|
|
99
|
+
After checking out the repo, run `bundle install` to install dependencies. Then run the test suite and linter:
|
|
100
|
+
|
|
101
|
+
```bash
|
|
102
|
+
$ bundle exec rake
|
|
103
|
+
```
|
|
104
|
+
|
|
105
|
+
## Contributing
|
|
106
|
+
|
|
107
|
+
Bug reports and pull requests are welcome on GitHub at https://github.com/Evgenii-Zinner/asciidown.
|
|
108
|
+
|
|
109
|
+
## License
|
|
110
|
+
|
|
111
|
+
The gem is available as open source under the terms of the [MIT License](LICENSE.txt).
|
data/bin/asciidoc2md
ADDED
data/bin/asciidown
ADDED
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
require_relative "constants"
|
|
4
|
+
|
|
5
|
+
class Asciidown
|
|
6
|
+
# Helper functions for identifying and formatting AsciiDoc headings, list items,
|
|
7
|
+
# block titles, image macros, and element attribute lists.
|
|
8
|
+
module BlockHelpers
|
|
9
|
+
include Constants
|
|
10
|
+
|
|
11
|
+
module_function
|
|
12
|
+
|
|
13
|
+
def is_heading(str, accept_all, block_attrs)
|
|
14
|
+
space_idx = str.index(" ")
|
|
15
|
+
return nil unless space_idx&.positive? && space_idx <= 6
|
|
16
|
+
|
|
17
|
+
marker = ["=", "==", "===", "====", "=====", "======"][space_idx - 1]
|
|
18
|
+
return nil unless marker && str.start_with?(marker)
|
|
19
|
+
|
|
20
|
+
title = str[(space_idx + 1)..]
|
|
21
|
+
return nil if title.nil? || title.empty?
|
|
22
|
+
|
|
23
|
+
title = title.lstrip if title[0] == " "
|
|
24
|
+
return nil if title.empty?
|
|
25
|
+
|
|
26
|
+
[marker, title] if accept_all || (block_attrs && block_attrs[1] == "discrete")
|
|
27
|
+
end
|
|
28
|
+
|
|
29
|
+
def is_any_list_item(chr0, str)
|
|
30
|
+
if LIST_MARKERS[chr0] && (m = ListItemRx.match(str))
|
|
31
|
+
return [m[1], m[2], nil, nil]
|
|
32
|
+
end
|
|
33
|
+
|
|
34
|
+
if (str.end_with?("::") || str.include?(":: ")) && (m = DlistItemRx.match(str))
|
|
35
|
+
[m[1], m[3], m[3], m[2]]
|
|
36
|
+
end
|
|
37
|
+
end
|
|
38
|
+
|
|
39
|
+
def write_block_title(buffer, block_title, block_attrs, state)
|
|
40
|
+
id = block_attrs&.dig("id")
|
|
41
|
+
indent = block_title[:indent]
|
|
42
|
+
text = block_title[:text]
|
|
43
|
+
title = Substitutors.apply_subs(text, state, block_title[:subs])
|
|
44
|
+
if id
|
|
45
|
+
state.refs[id] = { title: title, reftext: block_attrs["reftext"] }
|
|
46
|
+
anchor = "<a name=\"#{id}\"></a>"
|
|
47
|
+
else
|
|
48
|
+
anchor = ""
|
|
49
|
+
end
|
|
50
|
+
buffer << "#{indent}#{anchor}**#{title}**"
|
|
51
|
+
buffer << ""
|
|
52
|
+
end
|
|
53
|
+
|
|
54
|
+
def handle_image(target, attrlist, state)
|
|
55
|
+
attrs = parse_attrlist(attrlist)
|
|
56
|
+
alt = attrs[1] || target
|
|
57
|
+
imagesdir = state["imagesdir"] ? "#{state['imagesdir']}/" : ""
|
|
58
|
+
""
|
|
59
|
+
end
|
|
60
|
+
|
|
61
|
+
def parse_attrlist(attrlist)
|
|
62
|
+
attrs = {}
|
|
63
|
+
return attrs if attrlist.nil? || attrlist.empty?
|
|
64
|
+
|
|
65
|
+
if attrlist.include?("=")
|
|
66
|
+
attrlist.scan(ElementAttributeRx) do |k, _, qv, uv|
|
|
67
|
+
attrs[k] = qv || uv
|
|
68
|
+
end
|
|
69
|
+
else
|
|
70
|
+
parts = attrlist.split(",").map(&:strip)
|
|
71
|
+
parts.each_with_index { |p, i| attrs[i + 1] = p }
|
|
72
|
+
if (shorthand = attrs[1])
|
|
73
|
+
shorthand.split(StyleShorthandMarkersRx).each_slice(2) do |val, marker|
|
|
74
|
+
attrs["id"] = val if marker == "#"
|
|
75
|
+
attrs["role"] = val if marker == "."
|
|
76
|
+
end
|
|
77
|
+
end
|
|
78
|
+
end
|
|
79
|
+
attrs
|
|
80
|
+
end
|
|
81
|
+
end
|
|
82
|
+
end
|
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
require "optparse"
|
|
4
|
+
|
|
5
|
+
class Asciidown
|
|
6
|
+
# Command line interface for converting AsciiDoc files or STDIN to Markdown.
|
|
7
|
+
class CLI
|
|
8
|
+
def self.run(argv = ARGV)
|
|
9
|
+
new(argv).run
|
|
10
|
+
end
|
|
11
|
+
|
|
12
|
+
def initialize(argv)
|
|
13
|
+
@argv = argv.dup
|
|
14
|
+
@options = { front_matter: true }
|
|
15
|
+
end
|
|
16
|
+
|
|
17
|
+
def run
|
|
18
|
+
parse_options!
|
|
19
|
+
|
|
20
|
+
opts = @options.dup
|
|
21
|
+
output_file = opts.delete(:output_file)
|
|
22
|
+
|
|
23
|
+
input_text = read_input
|
|
24
|
+
output_text = Asciidown.call(input_text, **opts)
|
|
25
|
+
write_output(output_text, output_file)
|
|
26
|
+
|
|
27
|
+
0
|
|
28
|
+
rescue StandardError => e
|
|
29
|
+
warn "asciidoc2md: #{e.message}"
|
|
30
|
+
1
|
|
31
|
+
end
|
|
32
|
+
|
|
33
|
+
private
|
|
34
|
+
|
|
35
|
+
def parse_options!
|
|
36
|
+
parser = OptionParser.new do |opts|
|
|
37
|
+
opts.banner = "Usage: asciidoc2md [options] [file]"
|
|
38
|
+
|
|
39
|
+
opts.on("-o", "--output FILE", "Write output to FILE instead of standard output") do |file|
|
|
40
|
+
@options[:output_file] = file
|
|
41
|
+
end
|
|
42
|
+
|
|
43
|
+
opts.on("--[no-]front-matter", "Extract document header as YAML front matter (default: true)") do |fm|
|
|
44
|
+
@options[:front_matter] = fm
|
|
45
|
+
end
|
|
46
|
+
|
|
47
|
+
opts.on("-v", "--version", "Show version") do
|
|
48
|
+
puts "asciidown #{VERSION}"
|
|
49
|
+
exit 0
|
|
50
|
+
end
|
|
51
|
+
|
|
52
|
+
opts.on("-h", "--help", "Show this help message") do
|
|
53
|
+
puts opts
|
|
54
|
+
exit 0
|
|
55
|
+
end
|
|
56
|
+
end
|
|
57
|
+
|
|
58
|
+
parser.parse!(@argv)
|
|
59
|
+
end
|
|
60
|
+
|
|
61
|
+
def read_input
|
|
62
|
+
if @argv.empty? || @argv.first == "-"
|
|
63
|
+
$stdin.read
|
|
64
|
+
else
|
|
65
|
+
File.read(@argv.first)
|
|
66
|
+
end
|
|
67
|
+
end
|
|
68
|
+
|
|
69
|
+
def write_output(text, output_file)
|
|
70
|
+
if output_file
|
|
71
|
+
File.write(output_file, text)
|
|
72
|
+
else
|
|
73
|
+
$stdout.print(text)
|
|
74
|
+
end
|
|
75
|
+
end
|
|
76
|
+
end
|
|
77
|
+
end
|
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
class Asciidown
|
|
4
|
+
module Constants
|
|
5
|
+
ADMONS = {
|
|
6
|
+
"CAUTION" => "🔥",
|
|
7
|
+
"IMPORTANT" => "❗",
|
|
8
|
+
"NOTE" => "📌",
|
|
9
|
+
"TIP" => "💡",
|
|
10
|
+
"WARNING" => "⚠️"
|
|
11
|
+
}.freeze
|
|
12
|
+
|
|
13
|
+
ATTRIBUTES = {
|
|
14
|
+
"empty" => "",
|
|
15
|
+
"idprefix" => "_",
|
|
16
|
+
"idseparator" => "_",
|
|
17
|
+
"markdown-line-break" => "\\",
|
|
18
|
+
"markdown-strikethrough" => "~~",
|
|
19
|
+
"nbsp" => " ",
|
|
20
|
+
"quotes" => "<q> </q>",
|
|
21
|
+
"sp" => " ",
|
|
22
|
+
"vbar" => "|",
|
|
23
|
+
"zwsp" => "​"
|
|
24
|
+
}.freeze
|
|
25
|
+
|
|
26
|
+
BREAKS = {
|
|
27
|
+
"'''" => "---",
|
|
28
|
+
"***" => "---",
|
|
29
|
+
"---" => "---",
|
|
30
|
+
"<<<" => nil,
|
|
31
|
+
"toc::[]" => nil
|
|
32
|
+
}.freeze
|
|
33
|
+
|
|
34
|
+
CONUMS = (1..19).to_h { |i| [i, [0x2460 + i - 1].pack("U*")] }.freeze
|
|
35
|
+
|
|
36
|
+
DELIMS = {
|
|
37
|
+
"----" => "v",
|
|
38
|
+
"...." => "v",
|
|
39
|
+
"====" => "c",
|
|
40
|
+
"|===" => "t",
|
|
41
|
+
"--" => "c",
|
|
42
|
+
"****" => "c",
|
|
43
|
+
"____" => "c",
|
|
44
|
+
"++++" => "p"
|
|
45
|
+
}.freeze
|
|
46
|
+
|
|
47
|
+
LIST_MARKERS = %w[1 2 3 4 5 6 7 8 9 * . < -].to_h { |c| [c, true] }.freeze
|
|
48
|
+
NORMAL_SUBS = %i[quotes attributes macros].freeze
|
|
49
|
+
TDIV = { "" => "| --- ", "<" => "| :-- ", "^" => "| :-: ", ">" => "| --: " }.freeze
|
|
50
|
+
|
|
51
|
+
AttributeEntryRx = /^:(!)?([^:-][^:]*):(?:$| (.+))/
|
|
52
|
+
AttributeRefRx = /(\\)?\{([\p{Ll}\d_][\p{Ll}\d_-]*)\}/u
|
|
53
|
+
AuthorInfoLineRx = /^(?:[\p{Alpha}\d_]+(?: +[\p{Alpha}\d_]+){0,2}(?: +<([^>]+)>)?(?:; |$))+$/u
|
|
54
|
+
BlockAnchorRx = /^\[([\p{L}_][\p{Alpha}\d_\-:.]*)(?:, ?(.+))?\]$/u
|
|
55
|
+
BlockImageMacroRx = /^image::([^\s\[]+)\[(.*?)\]$/
|
|
56
|
+
CellDelimiterRx = /(?<!\\)\| */
|
|
57
|
+
ConumRx = /(^| )<([.1-9]|1\d)>(?=(?: <(?:[.1-9]|1\d)>)*$)/
|
|
58
|
+
DlistItemRx = %r{^(?!//)(\S.*?)(:{2,4})(?: (.+))?($)}
|
|
59
|
+
ElementAttributeRx = /(?:^|, *)(?:(\w[\w-]*)=)?(?:("|')(.+?)\2|([^,]+|))/
|
|
60
|
+
EmphasisSpanMetaRx = /(?<![\p{L}\d_\\])\[[^\[\]]+\](?=_(?:\S|\S.*?\S)_(?![\p{L}\d_]))/u
|
|
61
|
+
InlineAnchorRx = /\[\[([\p{L}_][\p{Alpha}\d_\-:.]*)\]\]/u
|
|
62
|
+
InlineImageMacroRx = /image:([^\s\[]+)\[(.*?)\]/
|
|
63
|
+
InlineStemMacroRx = /stem:\[(.*?[^\\])\]/
|
|
64
|
+
LinkMacroRx = %r{(\\)?(?:(?:link:(?!:)|(?<![image:(\w])(https?://))([^\s\[\\]+)(\[(|.*?[^\\])\^?\])|(?<![image:(\w])(https?://)([^\s\[\])]+))}
|
|
65
|
+
ListItemRx = /^(\*+|\.+|<(?:[.1-9]|1\d)>|-|\d+\.) +(.+)/
|
|
66
|
+
MarkedSpanRx = /(?<![\p{L}\d_\\])(?:\[((\.line-through)|[^\[\]]+)\])?#(\S|\S.*?\S)#(?![\p{L}\d_])/u
|
|
67
|
+
PreprocessorDirectiveRx = /^\\?(?:(if)(n)?def|include)::([^\[]+)\[(.+)?\]$/
|
|
68
|
+
QuotedSpanRx = /("|')`(\S|\S.*?\S)`\1/
|
|
69
|
+
RevisionInfoLineRx = /^v(\d+(?:[-.]\w+)*)(?:, (\d+-\d+-\d+))?|(\d+-\d+-\d+)$/
|
|
70
|
+
RewriteInternalXrefRx = /\[([^\[\]]*?)\]\(#!([^)]+)\)/
|
|
71
|
+
StrongSpanRx = /(?<![\p{L}\d_\\])(?:\[[^\[\]]+\])?(\*(?:\S|\S.*?\S)\*)(?![\p{L}\d_])/u
|
|
72
|
+
StyleShorthandMarkersRx = /([.#%])/
|
|
73
|
+
XrefMacroRx = /(\\)?xref:(?![\s:`])(?:([^#\[\\]+)(#[^\s\[\\]*|\.adoc)|#([^\s\[\\]+)|([^#\[\\]+))\[(|.*?[^\\])\]/
|
|
74
|
+
XrefShorthandRx = /<<([^\s,>][^,>]*)(?:, ?([^>]+))?>>/
|
|
75
|
+
end
|
|
76
|
+
end
|
|
@@ -0,0 +1,387 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
require_relative "constants"
|
|
4
|
+
require_relative "document_state"
|
|
5
|
+
require_relative "substitutors"
|
|
6
|
+
require_relative "block_helpers"
|
|
7
|
+
|
|
8
|
+
class Asciidown
|
|
9
|
+
# Core state-machine conversion engine for parsing AsciiDoc lines into Markdown.
|
|
10
|
+
class Converter
|
|
11
|
+
include Constants
|
|
12
|
+
|
|
13
|
+
def self.convert(asciidoc, state)
|
|
14
|
+
new(asciidoc, state).convert
|
|
15
|
+
end
|
|
16
|
+
|
|
17
|
+
def initialize(asciidoc, state)
|
|
18
|
+
@asciidoc = asciidoc
|
|
19
|
+
@state = state
|
|
20
|
+
end
|
|
21
|
+
|
|
22
|
+
def convert
|
|
23
|
+
lines = @asciidoc.split("\n")
|
|
24
|
+
lines.pop if lines.last == ""
|
|
25
|
+
|
|
26
|
+
accum = []
|
|
27
|
+
in_container = false
|
|
28
|
+
in_header = @asciidoc[0] == "=" || @asciidoc.include?("\n= ")
|
|
29
|
+
in_para = false
|
|
30
|
+
in_list = false
|
|
31
|
+
in_table = nil
|
|
32
|
+
indent = ""
|
|
33
|
+
block_attrs = nil
|
|
34
|
+
block_title = nil
|
|
35
|
+
hardbreak_next = nil
|
|
36
|
+
list_stack = []
|
|
37
|
+
container_stack = []
|
|
38
|
+
skip_stack = []
|
|
39
|
+
verbatim = nil
|
|
40
|
+
subs = nil
|
|
41
|
+
next_line = nil
|
|
42
|
+
|
|
43
|
+
idx = 0
|
|
44
|
+
while idx < lines.length
|
|
45
|
+
line = lines[idx]
|
|
46
|
+
|
|
47
|
+
loop do
|
|
48
|
+
grab = match = next_line = style = subs = nil
|
|
49
|
+
|
|
50
|
+
if line.nil?
|
|
51
|
+
break
|
|
52
|
+
elsif skip_stack.any?
|
|
53
|
+
if line == skip_stack.last
|
|
54
|
+
skip_stack.pop
|
|
55
|
+
elsif skip_stack.last == "endif::[]" && line.start_with?("if") && line =~ /^ifn?def::.+\[\]$/
|
|
56
|
+
skip_stack.push("endif::[]")
|
|
57
|
+
end
|
|
58
|
+
line = nil
|
|
59
|
+
break
|
|
60
|
+
elsif line.empty? && (!in_container || !in_container[:verbatim])
|
|
61
|
+
if in_table
|
|
62
|
+
line = nil
|
|
63
|
+
break
|
|
64
|
+
end
|
|
65
|
+
in_header = false
|
|
66
|
+
in_para = false
|
|
67
|
+
|
|
68
|
+
if in_list
|
|
69
|
+
in_para = nil
|
|
70
|
+
list_stack = []
|
|
71
|
+
in_list = false
|
|
72
|
+
indent = (in_container && in_container[:child_indent]) || ""
|
|
73
|
+
else
|
|
74
|
+
line = indent = (in_container && in_container[:child_indent]) || ""
|
|
75
|
+
line = line.rstrip
|
|
76
|
+
end
|
|
77
|
+
block_attrs = block_title = verbatim &&= verbatim[:close]&.call
|
|
78
|
+
break
|
|
79
|
+
elsif ((grab = (line[0] == "\\")) || (line[0] == "i" && line[1] != "m")) &&
|
|
80
|
+
((grab && line == "\\endif::[]") || (line.end_with?("]") && line.include?("::") && (match = PreprocessorDirectiveRx.match(line)))) &&
|
|
81
|
+
!(line = grab ? line[1..] : nil)
|
|
82
|
+
if match[1]
|
|
83
|
+
negated = match[2]
|
|
84
|
+
name = match[3]
|
|
85
|
+
text = match[4]
|
|
86
|
+
drop = @state.key?(name) ? !negated.nil? : negated.nil?
|
|
87
|
+
if text
|
|
88
|
+
next if drop # redo
|
|
89
|
+
|
|
90
|
+
line = text
|
|
91
|
+
elsif !skip_stack.push(drop && "endif::[]")
|
|
92
|
+
next # redo
|
|
93
|
+
end
|
|
94
|
+
end
|
|
95
|
+
elsif in_container && in_container[:verbatim]
|
|
96
|
+
if line == in_container[:delimiter]
|
|
97
|
+
code_lines = in_container[:code_lines]
|
|
98
|
+
max_backticks = code_lines.flat_map { |l| l.scan(/`+/).map(&:length) }.max || 0
|
|
99
|
+
fence = "`" * [3, max_backticks + 1].max
|
|
100
|
+
accum[in_container[:fence_idx]] = "#{in_container[:indent]}#{fence}#{in_container[:style]}".strip
|
|
101
|
+
accum.concat(code_lines.map { |l| "#{in_container[:indent]}#{l}" })
|
|
102
|
+
line = "#{in_container[:indent]}#{fence}"
|
|
103
|
+
indent = in_container[:indent]
|
|
104
|
+
in_list = in_container[:in_list]
|
|
105
|
+
list_stack = in_container[:list_stack]
|
|
106
|
+
in_container = container_stack.any? ? container_stack.pop : false
|
|
107
|
+
elsif line.length.positive?
|
|
108
|
+
current_line = Substitutors.apply_callouts(line, @state)
|
|
109
|
+
in_container[:code_lines] << current_line
|
|
110
|
+
line = nil
|
|
111
|
+
end
|
|
112
|
+
break
|
|
113
|
+
elsif !in_header && DELIMS.key?(line)
|
|
114
|
+
if in_para != false
|
|
115
|
+
list_stack = []
|
|
116
|
+
in_list = false
|
|
117
|
+
indent = (in_container && in_container[:child_indent]) || ""
|
|
118
|
+
in_para = false
|
|
119
|
+
end
|
|
120
|
+
|
|
121
|
+
opening = in_container == false || (line != in_container[:delimiter] && container_stack.push(in_container))
|
|
122
|
+
if opening
|
|
123
|
+
in_container = { delimiter: line, indent: indent, child_indent: indent, in_list: in_list,
|
|
124
|
+
list_stack: list_stack }
|
|
125
|
+
end
|
|
126
|
+
|
|
127
|
+
if (grab = DELIMS[line]) == "v" && (in_container[:verbatim] = true)
|
|
128
|
+
in_container[:child_indent] = ""
|
|
129
|
+
in_container[:subs] = [:callouts]
|
|
130
|
+
in_container[:code_lines] = []
|
|
131
|
+
in_container[:fence_idx] = accum.length
|
|
132
|
+
@state.coseq = 1
|
|
133
|
+
if block_attrs
|
|
134
|
+
raw_style = block_attrs[1] || (line == "----" ? "source" : nil)
|
|
135
|
+
style = if raw_style =~ /^source(?:\s*,\s*([a-zA-Z0-9_+#.-]+))?/
|
|
136
|
+
Regexp.last_match(1) || block_attrs[2] || @state["source-language"]
|
|
137
|
+
elsif raw_style == "source"
|
|
138
|
+
block_attrs[2] || @state["source-language"]
|
|
139
|
+
else
|
|
140
|
+
raw_style
|
|
141
|
+
end
|
|
142
|
+
style = nil if %w[listing literal].include?(style)
|
|
143
|
+
BlockHelpers.write_block_title(accum, block_title, block_attrs, @state) if block_title
|
|
144
|
+
elsif line == "----"
|
|
145
|
+
style = @state["source-language"]
|
|
146
|
+
end
|
|
147
|
+
in_container[:style] = style
|
|
148
|
+
line = nil
|
|
149
|
+
elsif grab == "p" && (in_container[:verbatim] = true)
|
|
150
|
+
line = block_attrs && block_attrs[1] == "stem" ? "```math" : nil
|
|
151
|
+
in_container[:cap] = "```" if line
|
|
152
|
+
block_title = nil
|
|
153
|
+
elsif !opening
|
|
154
|
+
line = in_container[:cap]
|
|
155
|
+
indent = in_container[:indent]
|
|
156
|
+
in_list = in_container[:in_list]
|
|
157
|
+
list_stack = in_container[:list_stack]
|
|
158
|
+
in_table = block_title = nil
|
|
159
|
+
in_container = container_stack.any? ? container_stack.pop : false
|
|
160
|
+
elsif grab == "t"
|
|
161
|
+
in_table = { header: block_attrs&.key?("header-option") || (!block_attrs&.key?("noheader-option") && nil) }
|
|
162
|
+
if block_attrs && (grab = block_attrs["cols"])
|
|
163
|
+
cols = grab.split(/,|;/)
|
|
164
|
+
in_table[:div] = "| #{cols.map { |c| TDIV[c[/[<^>]/] || '']&.strip || '---' }.join(' | ')} |"
|
|
165
|
+
in_table[:cols] = cols.length
|
|
166
|
+
end
|
|
167
|
+
line = nil
|
|
168
|
+
elsif line == "____"
|
|
169
|
+
indent = (in_container[:child_indent] += "> ")
|
|
170
|
+
author_part = [block_attrs && block_attrs[2], block_attrs && block_attrs[3]].compact.map(&:strip).reject(&:empty?).join(", ")
|
|
171
|
+
author_part = block_attrs[1] if author_part.empty? && block_attrs && block_attrs[1] && block_attrs[1] != "quote"
|
|
172
|
+
in_container[:cap] = ">\n#{indent}— #{author_part}" if author_part && !author_part.empty?
|
|
173
|
+
line = block_title ? BlockHelpers.write_block_title(accum, block_title, block_attrs, @state) : nil
|
|
174
|
+
elsif line == "====" && block_attrs
|
|
175
|
+
style = block_attrs[1]
|
|
176
|
+
if ADMONS.key?(style) || %w[NOTE TIP IMPORTANT WARNING CAUTION].include?(style)
|
|
177
|
+
title_part = block_title ? ": #{block_title[:text]}" : ""
|
|
178
|
+
indent = (in_container[:child_indent] += "> ")
|
|
179
|
+
line = "> **#{style.capitalize}#{title_part}:**"
|
|
180
|
+
in_container[:cap] = nil
|
|
181
|
+
block_title = nil
|
|
182
|
+
elsif block_attrs.key?("collapsible-option")
|
|
183
|
+
summary = block_title ? block_title[:text] : "Details"
|
|
184
|
+
line = "<details>\n#{indent}<summary>#{summary}</summary>\n"
|
|
185
|
+
in_container[:cap] = "</details>"
|
|
186
|
+
block_title = nil
|
|
187
|
+
else
|
|
188
|
+
line = block_title ? BlockHelpers.write_block_title(accum, block_title, block_attrs, @state) : nil
|
|
189
|
+
end
|
|
190
|
+
else
|
|
191
|
+
line = block_title ? BlockHelpers.write_block_title(accum, block_title, block_attrs, @state) : nil
|
|
192
|
+
end
|
|
193
|
+
block_attrs = nil
|
|
194
|
+
list_stack = [] if opening
|
|
195
|
+
break
|
|
196
|
+
else
|
|
197
|
+
chr0 = line[0]
|
|
198
|
+
indented = (chr0 == " ")
|
|
199
|
+
_line = indented ? line.lstrip : line
|
|
200
|
+
_chr0 = _line[0]
|
|
201
|
+
|
|
202
|
+
if in_para.nil? && _chr0
|
|
203
|
+
in_para = false
|
|
204
|
+
if BlockHelpers.is_any_list_item(_chr0, _line) && in_list
|
|
205
|
+
accum.pop
|
|
206
|
+
elsif !indented
|
|
207
|
+
list_stack = []
|
|
208
|
+
in_list = false
|
|
209
|
+
indent = (in_container && in_container[:child_indent]) || ""
|
|
210
|
+
end
|
|
211
|
+
end
|
|
212
|
+
|
|
213
|
+
if chr0 == "/" && line[1] == "/"
|
|
214
|
+
if line == "////"
|
|
215
|
+
skip_stack.push(line)
|
|
216
|
+
in_para = false
|
|
217
|
+
end
|
|
218
|
+
line = nil
|
|
219
|
+
elsif !in_para && chr0 == "=" && (match = BlockHelpers.is_heading(line, in_container == false, block_attrs))
|
|
220
|
+
marker, title = match
|
|
221
|
+
if in_header
|
|
222
|
+
if marker.length > 1 || (block_attrs && block_attrs[1] == "discrete") || @state.key?("doctitle")
|
|
223
|
+
in_header = false
|
|
224
|
+
redo if accum.empty?
|
|
225
|
+
else
|
|
226
|
+
@state["doctitle"] = title
|
|
227
|
+
auto_id = Substitutors.generate_id(title).tr(" ", "-") if block_attrs&.key?("id")
|
|
228
|
+
end
|
|
229
|
+
else
|
|
230
|
+
title = Substitutors.apply_subs(title, @state, NORMAL_SUBS)
|
|
231
|
+
auto_id = Substitutors.generate_id(title).tr(" ", "-")
|
|
232
|
+
id = block_attrs&.dig("id") || (@state["idprefix"] + auto_id)
|
|
233
|
+
end
|
|
234
|
+
if id
|
|
235
|
+
ref_obj = { auto_id: auto_id, reftext: block_attrs&.dig("reftext"), title: title }
|
|
236
|
+
@state.refs[title] = ref_obj
|
|
237
|
+
@state.refs[id] = ref_obj
|
|
238
|
+
end
|
|
239
|
+
block_attrs = block_title = nil
|
|
240
|
+
line = "#{'#' * marker.length} #{title}"
|
|
241
|
+
elsif !in_para && chr0 == ":" && (match = AttributeEntryRx.match(line))
|
|
242
|
+
del = match[1]
|
|
243
|
+
name = match[2]
|
|
244
|
+
val = match[3] || ""
|
|
245
|
+
line = nil
|
|
246
|
+
if del
|
|
247
|
+
@state.delete(name)
|
|
248
|
+
else
|
|
249
|
+
@state[name] = val.include?("{") ? Substitutors.apply_attributes(val, @state) : val
|
|
250
|
+
end
|
|
251
|
+
elsif chr0 == "[" && line.end_with?("]")
|
|
252
|
+
block_attrs = BlockHelpers.parse_attrlist(line[1..-2])
|
|
253
|
+
line = nil
|
|
254
|
+
in_para = false
|
|
255
|
+
elsif in_header
|
|
256
|
+
if @state.key?("doctitle")
|
|
257
|
+
if !@state.key?("author") && AuthorInfoLineRx.match?(line)
|
|
258
|
+
authors = line.split("; ").map { |author| author.split(" <")[0] }
|
|
259
|
+
@state["author"] = authors[0]
|
|
260
|
+
@state["authors"] = authors.join(", ")
|
|
261
|
+
line = nil
|
|
262
|
+
elsif !@state.key?("revdate") && !@state.key?("revnumber") && (match = RevisionInfoLineRx.match?(line))
|
|
263
|
+
@state["revnumber"] = match[1] if match[1]
|
|
264
|
+
@state["revdate"] = match[2] || match[3] if match[2] || match[3]
|
|
265
|
+
line = nil
|
|
266
|
+
else
|
|
267
|
+
in_header = false
|
|
268
|
+
redo if accum.empty?
|
|
269
|
+
end
|
|
270
|
+
else
|
|
271
|
+
in_header = false
|
|
272
|
+
redo if accum.empty?
|
|
273
|
+
end
|
|
274
|
+
elsif in_table
|
|
275
|
+
cells = line.split(/(?<!\\)\|/, -1).map(&:strip)
|
|
276
|
+
cells.shift if cells.first.to_s.empty?
|
|
277
|
+
cells.pop if cells.last.to_s.empty?
|
|
278
|
+
if in_table[:row]
|
|
279
|
+
in_table[:row].concat(cells)
|
|
280
|
+
break if in_table[:row].length < in_table[:cols]
|
|
281
|
+
|
|
282
|
+
line = "| #{Substitutors.apply_subs(in_table[:row].shift(in_table[:cols]).join(' | '), @state, NORMAL_SUBS)} |"
|
|
283
|
+
else
|
|
284
|
+
in_table[:row] = []
|
|
285
|
+
in_table[:cols] ||= cells.length
|
|
286
|
+
cols = in_table[:cols]
|
|
287
|
+
div = in_table[:div] || "| #{Array.new(cols, '---').join(' | ')} |"
|
|
288
|
+
line = "| #{cells.join(' | ')} |\n#{indent}#{div}"
|
|
289
|
+
end
|
|
290
|
+
elsif line == "+" && in_list
|
|
291
|
+
line = in_list[:indent]
|
|
292
|
+
indent = in_list[:child_indent]
|
|
293
|
+
verbatim = in_para = false
|
|
294
|
+
accum << line.rstrip
|
|
295
|
+
break
|
|
296
|
+
elsif (!in_para || in_list) && (match = BlockHelpers.is_any_list_item(_chr0, _line))
|
|
297
|
+
marker, text, desc, dlist = match
|
|
298
|
+
if dlist
|
|
299
|
+
text = "*#{marker}*"
|
|
300
|
+
marker = "-"
|
|
301
|
+
hardbreak_next = "pending" unless desc
|
|
302
|
+
end
|
|
303
|
+
ordered = marker.start_with?(".", "1") || marker.end_with?(".")
|
|
304
|
+
if !in_list || in_list[:marker] != marker
|
|
305
|
+
if list_stack.any? && (m_idx = list_stack.find_index { |entry| entry[:marker] == marker })
|
|
306
|
+
in_list = list_stack[m_idx]
|
|
307
|
+
list_stack = list_stack[0...m_idx]
|
|
308
|
+
indent = in_list[:indent]
|
|
309
|
+
else
|
|
310
|
+
container_child = in_container ? in_container[:child_indent] : ""
|
|
311
|
+
indent = in_list ? (list_stack << in_list).last[:child_indent] : container_child
|
|
312
|
+
lindent = 2
|
|
313
|
+
in_list = { marker: marker, indent: indent, child_indent: indent + (" " * lindent),
|
|
314
|
+
numeral: ordered ? 0 : nil }
|
|
315
|
+
end
|
|
316
|
+
else
|
|
317
|
+
indent = in_list[:indent]
|
|
318
|
+
end
|
|
319
|
+
in_para = true
|
|
320
|
+
subs = NORMAL_SUBS
|
|
321
|
+
line = (ordered ? "#{in_list[:numeral] += 1}. " : "* ") + text
|
|
322
|
+
elsif in_para
|
|
323
|
+
subs = NORMAL_SUBS
|
|
324
|
+
accum[-1] += @state["markdown-line-break"] if (hardbreak_next || in_para == "hardbreaks") && accum.any?
|
|
325
|
+
elsif chr0 == "." && line.length > 1 && line[1] != "."
|
|
326
|
+
text = line.start_with?(".*") && line.end_with?("*") ? line[2..-2] : line[1..]
|
|
327
|
+
block_title = { indent: indent, text: text, subs: NORMAL_SUBS }
|
|
328
|
+
line = nil
|
|
329
|
+
elsif chr0 && (match = line.index(": ")) && match < 10 && ADMONS.key?(style = line[0...match])
|
|
330
|
+
body = line[(match + 2)..]
|
|
331
|
+
in_para = true
|
|
332
|
+
line = "> **#{style.capitalize}:** #{Substitutors.apply_subs(body, @state, NORMAL_SUBS)}"
|
|
333
|
+
elsif chr0 == "i" && line.start_with?("image::") && (match = BlockImageMacroRx.match(line))
|
|
334
|
+
line = BlockHelpers.handle_image(match[1], match[2], @state)
|
|
335
|
+
elsif BREAKS.key?(line)
|
|
336
|
+
line = BREAKS[line]
|
|
337
|
+
else
|
|
338
|
+
in_para = true
|
|
339
|
+
subs = NORMAL_SUBS
|
|
340
|
+
end
|
|
341
|
+
|
|
342
|
+
break
|
|
343
|
+
end
|
|
344
|
+
end
|
|
345
|
+
|
|
346
|
+
if line
|
|
347
|
+
BlockHelpers.write_block_title(accum, block_title, block_attrs, @state) if block_title
|
|
348
|
+
line = Substitutors.apply_subs(line, @state, subs) if subs
|
|
349
|
+
accum << (indent.empty? || line.empty? ? line : "#{indent}#{line}")
|
|
350
|
+
if next_line
|
|
351
|
+
next_line = Substitutors.apply_subs(next_line, @state, NORMAL_SUBS)
|
|
352
|
+
accum[-1] += @state["markdown-line-break"]
|
|
353
|
+
accum << (indent.empty? ? next_line : "#{indent}#{next_line}")
|
|
354
|
+
end
|
|
355
|
+
elsif line == ""
|
|
356
|
+
accum << (indent.empty? ? "" : indent.rstrip)
|
|
357
|
+
end
|
|
358
|
+
|
|
359
|
+
hardbreak_next = nil if hardbreak_next && hardbreak_next != "pending"
|
|
360
|
+
hardbreak_next = "active" if hardbreak_next == "pending"
|
|
361
|
+
idx += 1
|
|
362
|
+
end
|
|
363
|
+
|
|
364
|
+
if in_container && in_container[:verbatim]
|
|
365
|
+
code_lines = in_container[:code_lines]
|
|
366
|
+
max_backticks = code_lines.flat_map { |l| l.scan(/`+/).map(&:length) }.max || 0
|
|
367
|
+
fence = "`" * [3, max_backticks + 1].max
|
|
368
|
+
accum[in_container[:fence_idx]] = "#{in_container[:indent]}#{fence}#{in_container[:style]}".strip
|
|
369
|
+
accum.concat(code_lines.map { |l| "#{in_container[:indent]}#{l}" })
|
|
370
|
+
accum << "#{in_container[:indent]}#{fence}"
|
|
371
|
+
end
|
|
372
|
+
|
|
373
|
+
result = accum.join("\n").rstrip
|
|
374
|
+
# Final internal cross-references replacement
|
|
375
|
+
result.gsub(RewriteInternalXrefRx) do
|
|
376
|
+
text = Regexp.last_match(1)
|
|
377
|
+
id = Regexp.last_match(2)
|
|
378
|
+
target = @state.refs[id] || @state.nrefs[id] || {}
|
|
379
|
+
title = target[:title] || id
|
|
380
|
+
reftext = target[:reftext] || title
|
|
381
|
+
auto_id = target[:auto_id] || id.sub(/^#?_?/, "")
|
|
382
|
+
"[#{text.empty? ? reftext : text}](##{auto_id})"
|
|
383
|
+
end
|
|
384
|
+
end
|
|
385
|
+
# rubocop:enable Metrics/BlockLength, Metrics/PerceivedComplexity, Metrics/CyclomaticComplexity, Metrics/MethodLength, Metrics/AbcSize
|
|
386
|
+
end
|
|
387
|
+
end
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
require_relative "constants"
|
|
4
|
+
|
|
5
|
+
class Asciidown
|
|
6
|
+
# Encapsulates conversion state, registered attributes, and cross-reference targets.
|
|
7
|
+
class DocumentState
|
|
8
|
+
include Constants
|
|
9
|
+
|
|
10
|
+
attr_accessor :attrs, :pass, :coseq, :refs, :nrefs, :q, :s
|
|
11
|
+
|
|
12
|
+
def initialize(initial_attrs = {})
|
|
13
|
+
@attrs = ATTRIBUTES.merge(initial_attrs.transform_keys(&:to_s))
|
|
14
|
+
@pass = []
|
|
15
|
+
@coseq = 1
|
|
16
|
+
@refs = {}
|
|
17
|
+
@nrefs = {}
|
|
18
|
+
@q = nil
|
|
19
|
+
@s = nil
|
|
20
|
+
end
|
|
21
|
+
|
|
22
|
+
def [](key)
|
|
23
|
+
@attrs[key.to_s]
|
|
24
|
+
end
|
|
25
|
+
|
|
26
|
+
def []=(key, val)
|
|
27
|
+
@attrs[key.to_s] = val
|
|
28
|
+
end
|
|
29
|
+
|
|
30
|
+
def key?(key)
|
|
31
|
+
@attrs.key?(key.to_s)
|
|
32
|
+
end
|
|
33
|
+
|
|
34
|
+
def delete(key)
|
|
35
|
+
@attrs.delete(key.to_s)
|
|
36
|
+
end
|
|
37
|
+
|
|
38
|
+
def quotes_pair
|
|
39
|
+
@quotes_pair ||= (@attrs["quotes"] || "<q> </q>").split[0..1]
|
|
40
|
+
end
|
|
41
|
+
|
|
42
|
+
def strikethrough_pair
|
|
43
|
+
return @s if @s
|
|
44
|
+
|
|
45
|
+
pair = (@attrs["markdown-strikethrough"] || "~~").split
|
|
46
|
+
@s = pair.length > 1 ? pair[0..1] : [pair[0], pair[0]]
|
|
47
|
+
end
|
|
48
|
+
end
|
|
49
|
+
end
|
|
@@ -0,0 +1,161 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
require_relative "constants"
|
|
4
|
+
|
|
5
|
+
class Asciidown
|
|
6
|
+
# Handles inline text substitutions including quotes, attributes, macros, and callout numbers.
|
|
7
|
+
module Substitutors
|
|
8
|
+
include Constants
|
|
9
|
+
|
|
10
|
+
module_function
|
|
11
|
+
|
|
12
|
+
def apply_subs(str, state, subs = NORMAL_SUBS)
|
|
13
|
+
return str unless str && str =~ /[{\x60\x27*_:<\[#]/
|
|
14
|
+
|
|
15
|
+
subs.reduce(str) do |text, sub_type|
|
|
16
|
+
case sub_type
|
|
17
|
+
when :quotes then apply_quotes(text, state)
|
|
18
|
+
when :attributes then apply_attributes(text, state)
|
|
19
|
+
when :macros then apply_macros(text, state)
|
|
20
|
+
when :callouts then apply_callouts(text, state)
|
|
21
|
+
else text
|
|
22
|
+
end
|
|
23
|
+
end
|
|
24
|
+
end
|
|
25
|
+
|
|
26
|
+
def apply_quotes(str, state)
|
|
27
|
+
res = str.dup
|
|
28
|
+
if res.include?("<<")
|
|
29
|
+
res.gsub!(XrefShorthandRx) do
|
|
30
|
+
m = Regexp.last_match
|
|
31
|
+
anchor = m[1].sub(/^#?_?/, "")
|
|
32
|
+
label = m[2]
|
|
33
|
+
label = anchor if label && label.empty?
|
|
34
|
+
"[#{label || anchor}](##{anchor})"
|
|
35
|
+
end
|
|
36
|
+
end
|
|
37
|
+
|
|
38
|
+
# Strip metadata in front of emphasis
|
|
39
|
+
res.gsub!(EmphasisSpanMetaRx, "") if res.include?("]_")
|
|
40
|
+
|
|
41
|
+
# Bold: StrongSpanRx
|
|
42
|
+
res.gsub!(StrongSpanRx) { "**#{Regexp.last_match(1)[1..-2]}**" } if res.include?("*")
|
|
43
|
+
|
|
44
|
+
# Italic: _text_ -> *text*
|
|
45
|
+
res.gsub!(/(?<![\w\\])_(\S|\S.*?\S)_(?![\w\\])/, '*\1*') if res.include?("_")
|
|
46
|
+
|
|
47
|
+
# Bold-Italic: ***text***
|
|
48
|
+
res.gsub!(/\*\*_(.*?)_\*\*/, '***\1***') if res.include?("**_")
|
|
49
|
+
res.gsub!(/\*\*\*(.*?)\*\*\*/, '***\1***') if res.include?("***")
|
|
50
|
+
|
|
51
|
+
# Quoted spans: "`smart`"
|
|
52
|
+
if res.include?("`") && (res.include?('"`') || res.include?("'`"))
|
|
53
|
+
q = state.quotes_pair
|
|
54
|
+
res.gsub!(QuotedSpanRx, "#{q[0]}\\2#{q[1]}")
|
|
55
|
+
end
|
|
56
|
+
|
|
57
|
+
# Marked / Strikethrough
|
|
58
|
+
if res.include?("#")
|
|
59
|
+
res.gsub!(MarkedSpanRx) do
|
|
60
|
+
roles = Regexp.last_match(1)
|
|
61
|
+
is_line_through = Regexp.last_match(2)
|
|
62
|
+
content = Regexp.last_match(3)
|
|
63
|
+
if roles
|
|
64
|
+
s = state.strikethrough_pair
|
|
65
|
+
is_line_through ? "#{s[0]}#{content}#{s[1]}" : content
|
|
66
|
+
else
|
|
67
|
+
"<mark>#{content}</mark>"
|
|
68
|
+
end
|
|
69
|
+
end
|
|
70
|
+
end
|
|
71
|
+
|
|
72
|
+
res
|
|
73
|
+
end
|
|
74
|
+
|
|
75
|
+
def apply_attributes(str, state)
|
|
76
|
+
return str unless str.include?("{")
|
|
77
|
+
|
|
78
|
+
str.gsub(AttributeRefRx) do |match|
|
|
79
|
+
escaped = Regexp.last_match(1)
|
|
80
|
+
name = Regexp.last_match(2)
|
|
81
|
+
if escaped
|
|
82
|
+
match[1..]
|
|
83
|
+
else
|
|
84
|
+
state[name] || match
|
|
85
|
+
end
|
|
86
|
+
end
|
|
87
|
+
end
|
|
88
|
+
|
|
89
|
+
def apply_macros(str, state)
|
|
90
|
+
res = str.dup
|
|
91
|
+
return res unless res.include?(":") || res.include?("[[")
|
|
92
|
+
|
|
93
|
+
# Images: image:target[alt]
|
|
94
|
+
if res.include?("image:")
|
|
95
|
+
res.gsub!(InlineImageMacroRx) do
|
|
96
|
+
BlockHelpers.handle_image(Regexp.last_match(1), Regexp.last_match(2), state)
|
|
97
|
+
end
|
|
98
|
+
end
|
|
99
|
+
|
|
100
|
+
# Links: https://...[label] or link:...[label]
|
|
101
|
+
if res.include?(":/") || res.include?("link:")
|
|
102
|
+
res.gsub!(LinkMacroRx) do |m|
|
|
103
|
+
esc = Regexp.last_match(1)
|
|
104
|
+
scheme = Regexp.last_match(2) || ""
|
|
105
|
+
url = Regexp.last_match(3)
|
|
106
|
+
text = Regexp.last_match(5)
|
|
107
|
+
bare_url = Regexp.last_match(6)
|
|
108
|
+
|
|
109
|
+
if esc
|
|
110
|
+
m[1..]
|
|
111
|
+
elsif bare_url
|
|
112
|
+
bare_url
|
|
113
|
+
else
|
|
114
|
+
full_url = "#{scheme}#{url}"
|
|
115
|
+
label = text.nil? || text.empty? ? full_url : text
|
|
116
|
+
"[#{label}](#{full_url})"
|
|
117
|
+
end
|
|
118
|
+
end
|
|
119
|
+
end
|
|
120
|
+
|
|
121
|
+
# Anchors [[id]]
|
|
122
|
+
res.gsub!(InlineAnchorRx, '<a name="\1"></a>') if res.include?("[[")
|
|
123
|
+
|
|
124
|
+
# Cross-references: xref:path#id[text]
|
|
125
|
+
if res.include?("xref:")
|
|
126
|
+
res.gsub!(XrefMacroRx) do |m|
|
|
127
|
+
esc = Regexp.last_match(1)
|
|
128
|
+
p = Regexp.last_match(2)
|
|
129
|
+
ext = Regexp.last_match(3)
|
|
130
|
+
id = Regexp.last_match(4) || Regexp.last_match(5)
|
|
131
|
+
txt = Regexp.last_match(6)
|
|
132
|
+
|
|
133
|
+
if esc
|
|
134
|
+
m[1..]
|
|
135
|
+
elsif p && (ext == "#" || (p += ext))
|
|
136
|
+
"[#{txt || p}](#{p})"
|
|
137
|
+
else
|
|
138
|
+
"[#{txt || id}](#!#{id})"
|
|
139
|
+
end
|
|
140
|
+
end
|
|
141
|
+
end
|
|
142
|
+
|
|
143
|
+
res
|
|
144
|
+
end
|
|
145
|
+
|
|
146
|
+
def apply_callouts(str, state)
|
|
147
|
+
return str unless str.end_with?(">")
|
|
148
|
+
|
|
149
|
+
str.gsub(ConumRx) do
|
|
150
|
+
sp = Regexp.last_match(1)
|
|
151
|
+
chr = Regexp.last_match(2)
|
|
152
|
+
num = (chr == "." ? (state.coseq += 1) - 1 : chr.to_i)
|
|
153
|
+
"#{sp}#{CONUMS[num] || chr}"
|
|
154
|
+
end
|
|
155
|
+
end
|
|
156
|
+
|
|
157
|
+
def generate_id(string)
|
|
158
|
+
string.downcase.gsub(/[^\p{Ll}\d_ -]/u, "")
|
|
159
|
+
end
|
|
160
|
+
end
|
|
161
|
+
end
|
data/lib/asciidown.rb
ADDED
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
require "yaml"
|
|
4
|
+
require_relative "asciidown/version"
|
|
5
|
+
require_relative "asciidown/constants"
|
|
6
|
+
require_relative "asciidown/document_state"
|
|
7
|
+
require_relative "asciidown/substitutors"
|
|
8
|
+
require_relative "asciidown/block_helpers"
|
|
9
|
+
require_relative "asciidown/converter"
|
|
10
|
+
require_relative "asciidown/cli"
|
|
11
|
+
|
|
12
|
+
# Translates AsciiDoc text to GitHub Flavored Markdown.
|
|
13
|
+
class Asciidown
|
|
14
|
+
def self.call(asciidoc, **)
|
|
15
|
+
new(asciidoc, **).call
|
|
16
|
+
end
|
|
17
|
+
|
|
18
|
+
def self.perform(asciidoc, **)
|
|
19
|
+
call(asciidoc, **)
|
|
20
|
+
end
|
|
21
|
+
|
|
22
|
+
def initialize(asciidoc, attributes: {}, front_matter: true)
|
|
23
|
+
@raw = asciidoc.to_s
|
|
24
|
+
@initial_attrs = attributes
|
|
25
|
+
@front_matter = front_matter
|
|
26
|
+
end
|
|
27
|
+
|
|
28
|
+
def call
|
|
29
|
+
return "" if @raw.strip.empty?
|
|
30
|
+
|
|
31
|
+
# 1. Protect Liquid tags
|
|
32
|
+
protected_text, liquid_tags = protect_liquid_tags(@raw)
|
|
33
|
+
|
|
34
|
+
state = DocumentState.new(@initial_attrs)
|
|
35
|
+
result = Converter.convert(protected_text, state)
|
|
36
|
+
|
|
37
|
+
# 2. Restore Liquid tags
|
|
38
|
+
final_body = restore_liquid_tags(result, liquid_tags)
|
|
39
|
+
|
|
40
|
+
# 3. Format Front Matter if requested
|
|
41
|
+
if @front_matter && (state.key?("doctitle") || state.key?("tags") || state.key?("description"))
|
|
42
|
+
fm_hash = {}
|
|
43
|
+
fm_hash["title"] = state["doctitle"] if state.key?("doctitle")
|
|
44
|
+
state.attrs.each do |k, v|
|
|
45
|
+
next if %w[empty idprefix idseparator markdown-line-break markdown-strikethrough nbsp quotes sp vbar zwsp
|
|
46
|
+
doctitle].include?(k)
|
|
47
|
+
|
|
48
|
+
fm_hash[k] = v
|
|
49
|
+
end
|
|
50
|
+
front_matter_str = restore_liquid_tags(YAML.dump(fm_hash).strip, liquid_tags)
|
|
51
|
+
body_without_title = final_body.sub(/^#\s+[^\n]+\n+/, "")
|
|
52
|
+
"#{front_matter_str}\n---\n\n#{body_without_title.strip}\n"
|
|
53
|
+
else
|
|
54
|
+
"#{final_body.strip}\n"
|
|
55
|
+
end
|
|
56
|
+
end
|
|
57
|
+
|
|
58
|
+
private
|
|
59
|
+
|
|
60
|
+
def protect_liquid_tags(text)
|
|
61
|
+
tags = []
|
|
62
|
+
protected_content = text.gsub(/(?:\{%.*?%\}|\{\{.*?\}\})/m) do |match|
|
|
63
|
+
placeholder = "<!--LIQUID_TAG_PLACEHOLDER_#{tags.size}-->"
|
|
64
|
+
tags << match
|
|
65
|
+
placeholder
|
|
66
|
+
end
|
|
67
|
+
[protected_content, tags]
|
|
68
|
+
end
|
|
69
|
+
|
|
70
|
+
def restore_liquid_tags(text, tags)
|
|
71
|
+
tags.each_with_index.reduce(text) do |content, (tag, index)|
|
|
72
|
+
content.gsub("<!--LIQUID_TAG_PLACEHOLDER_#{index}-->", tag)
|
|
73
|
+
end
|
|
74
|
+
end
|
|
75
|
+
end
|
|
76
|
+
|
|
77
|
+
AsciidocToMarkdown = Asciidown
|
metadata
ADDED
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
--- !ruby/object:Gem::Specification
|
|
2
|
+
name: asciidown
|
|
3
|
+
version: !ruby/object:Gem::Version
|
|
4
|
+
version: 0.1.0
|
|
5
|
+
platform: ruby
|
|
6
|
+
authors:
|
|
7
|
+
- Evgenii Zinner
|
|
8
|
+
autorequire:
|
|
9
|
+
bindir: bin
|
|
10
|
+
cert_chain: []
|
|
11
|
+
date: 2026-10-30 00:00:00.000000000 Z
|
|
12
|
+
dependencies: []
|
|
13
|
+
description: A lightweight, dependency-free Ruby service and CLI tool to translate
|
|
14
|
+
AsciiDoc content into GitHub Flavored Markdown with support for YAML front matter,
|
|
15
|
+
pipe tables, callouts, and Liquid tags.
|
|
16
|
+
email:
|
|
17
|
+
- evgenii.zinner@gmail.com
|
|
18
|
+
executables:
|
|
19
|
+
- asciidown
|
|
20
|
+
- asciidoc2md
|
|
21
|
+
extensions: []
|
|
22
|
+
extra_rdoc_files: []
|
|
23
|
+
files:
|
|
24
|
+
- LICENSE.txt
|
|
25
|
+
- README.md
|
|
26
|
+
- bin/asciidoc2md
|
|
27
|
+
- bin/asciidown
|
|
28
|
+
- lib/asciidown.rb
|
|
29
|
+
- lib/asciidown/block_helpers.rb
|
|
30
|
+
- lib/asciidown/cli.rb
|
|
31
|
+
- lib/asciidown/constants.rb
|
|
32
|
+
- lib/asciidown/converter.rb
|
|
33
|
+
- lib/asciidown/document_state.rb
|
|
34
|
+
- lib/asciidown/substitutors.rb
|
|
35
|
+
- lib/asciidown/version.rb
|
|
36
|
+
homepage: https://github.com/Evgenii-Zinner/asciidown
|
|
37
|
+
licenses:
|
|
38
|
+
- MIT
|
|
39
|
+
metadata:
|
|
40
|
+
homepage_uri: https://github.com/Evgenii-Zinner/asciidown
|
|
41
|
+
source_code_uri: https://github.com/Evgenii-Zinner/asciidown
|
|
42
|
+
changelog_uri: https://github.com/Evgenii-Zinner/asciidown/blob/main/CHANGELOG.md
|
|
43
|
+
post_install_message:
|
|
44
|
+
rdoc_options: []
|
|
45
|
+
require_paths:
|
|
46
|
+
- lib
|
|
47
|
+
required_ruby_version: !ruby/object:Gem::Requirement
|
|
48
|
+
requirements:
|
|
49
|
+
- - ">="
|
|
50
|
+
- !ruby/object:Gem::Version
|
|
51
|
+
version: 3.2.0
|
|
52
|
+
required_rubygems_version: !ruby/object:Gem::Requirement
|
|
53
|
+
requirements:
|
|
54
|
+
- - ">="
|
|
55
|
+
- !ruby/object:Gem::Version
|
|
56
|
+
version: '0'
|
|
57
|
+
requirements: []
|
|
58
|
+
rubygems_version: 3.4.20
|
|
59
|
+
signing_key:
|
|
60
|
+
specification_version: 4
|
|
61
|
+
summary: Fast, pure Ruby converter from AsciiDoc to GitHub Flavored Markdown
|
|
62
|
+
test_files: []
|