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
322
323
324
325
326
327
//! AsciiDoc backend.
//!
//! A line-oriented port of docling's `AsciiDocBackend._parse`: titles (`= `),
//! section headers (`== `…), bullet/numbered lists, bare and `|===`-delimited
//! tables (with cell-format-specifier stripping), images and captions, and
//! multi-line paragraphs.
use docling_core::{DoclingDocument, Node, Table};
use crate::backend::markdown::escape_text;
use crate::backend::DeclarativeBackend;
use crate::error::ConversionError;
use crate::source::SourceDocument;
/// AsciiDoc cell specifier, e.g. `2*`, `^`, `.^`, `h` — the run that can be
/// glued before a `|` in a table line. Mirrors docling's `_CELL_SPEC`.
const CELL_SPEC: &str = r"(?:\d+(?:\.\d+)?[*+])*[<^>]?(?:\.[<^>])?[adehlms]?";
pub struct AsciiDocBackend;
impl DeclarativeBackend for AsciiDocBackend {
fn convert(&self, source: &SourceDocument) -> Result<DoclingDocument, ConversionError> {
let text = source.text()?;
let mut doc = DoclingDocument::new(&source.name);
let mut p = Parser::default();
// Iterate raw lines, preserving them as docling does (it never strips the
// trailing newline-only state machine differently from `str::lines`).
for line in text.lines() {
p.feed(line, &mut doc);
}
p.finish(&mut doc);
Ok(doc)
}
}
#[derive(Default)]
struct Parser {
text_data: Vec<String>,
caption_data: Vec<String>,
table_data: Vec<Vec<String>>,
in_list: bool,
in_table: bool,
/// Indents of the currently-open list levels (index = markdown nesting level).
list_indents: Vec<usize>,
/// Per-level running number for ordered lists.
list_counts: Vec<u64>,
/// Whether the next emitted item starts a fresh list (for the serializer).
fresh_list: bool,
/// Which heading levels (docling 0-based) currently have an active ancestor.
active: Vec<bool>,
/// Images and orphan (level-skipping) headings: docling attaches these to the
/// body root with no parent, so they render after the whole title subtree.
deferred: Vec<Node>,
}
impl Parser {
fn feed(&mut self, line: &str, doc: &mut DoclingDocument) {
// Title: `= ` — the root of the section tree.
if let Some(rest) = is_title(line) {
doc.push(Node::Heading {
level: 1,
text: escape_text(rest.trim()),
});
self.set_active(0);
return;
}
// Section header: `==+ `
if let Some((n, text)) = section_header(line) {
let node = Node::Heading {
level: n.min(6),
text: escape_text(text.trim()),
};
// A heading whose immediate parent level is absent (e.g. `====`
// under `==`) is orphaned to the body root and deferred.
let docling_level = (n - 1) as usize;
if docling_level >= 1 && !self.is_active(docling_level - 1) {
self.deferred.push(node);
} else {
doc.push(node);
self.set_active(docling_level);
}
return;
}
// List item
if let Some((indent, ordered, text)) = list_item(line) {
self.push_list_item(indent, ordered, &text, doc);
return;
}
if self.in_list {
// A non-list line ends the current list and is itself swallowed —
// docling's `elif in_list and not is_list_item` branch consumes it.
self.end_list();
return;
}
// Table start delimiter `|===`
if line.trim() == "|===" && !self.in_table {
self.in_table = true;
return;
}
// A table row
if is_table_line(line) {
self.in_table = true;
self.table_data.push(parse_table_line(line));
return;
}
// End of a table (any non-row line, including the closing `|===`)
if self.in_table {
self.flush_table(doc);
// fall through: the line may still be text/caption/etc., except `|===`.
if line.trim() == "|===" {
return;
}
}
// Picture — added with no parent, so deferred to the document end.
if let Some(caption) = is_picture(line) {
let cap = self.take_caption(doc);
let _ = caption; // alt text is not rendered by docling's markdown export
self.deferred.push(Node::Picture {
caption: cap,
image: None,
classification: None,
});
return;
}
// Caption: a line beginning with `.` (only when none is pending)
if let Some(rest) = is_caption(line) {
if self.caption_data.is_empty() {
self.caption_data.push(rest.to_string());
return;
}
}
// Continuation of a multi-line caption
if !line.trim().is_empty() && !self.caption_data.is_empty() {
self.caption_data.push(line.trim().to_string());
return;
}
// Plain text: blank line flushes the accumulated paragraph
if line.trim().is_empty() {
self.flush_text(doc);
} else {
self.text_data.push(line.trim().to_string());
}
}
fn push_list_item(
&mut self,
indent: usize,
ordered: bool,
text: &str,
doc: &mut DoclingDocument,
) {
if !self.in_list {
self.in_list = true;
self.list_indents = vec![indent];
self.list_counts = vec![0];
self.fresh_list = true;
} else if indent > *self.list_indents.last().unwrap() {
self.list_indents.push(indent);
self.list_counts.push(0);
} else {
while self.list_indents.len() > 1 && indent < *self.list_indents.last().unwrap() {
self.list_indents.pop();
self.list_counts.pop();
}
}
let level = (self.list_indents.len() - 1) as u8;
let count = self.list_counts.last_mut().unwrap();
*count += 1;
let number = *count;
// docling's AsciiDoc backend adds every item to a plain `LIST` group and
// ignores the numbered/bullet distinction, so all items render as `-`.
let _ = ordered;
doc.push(Node::ListItem {
ordered: false,
number,
first_in_list: self.fresh_list,
text: escape_text(text.trim()),
level,
marker: None,
location: None,
dclx: None,
href: None,
layer: None,
});
self.fresh_list = false;
}
fn end_list(&mut self) {
self.in_list = false;
self.list_indents.clear();
self.list_counts.clear();
}
fn take_caption(&mut self, doc: &mut DoclingDocument) -> Option<String> {
if self.caption_data.is_empty() {
return None;
}
let cap = self.caption_data.join(" ");
self.caption_data.clear();
let _ = doc;
Some(escape_text(&cap))
}
fn flush_text(&mut self, doc: &mut DoclingDocument) {
if !self.text_data.is_empty() {
let text = self.text_data.join(" ");
self.text_data.clear();
doc.push(Node::Paragraph {
text: escape_text(&text),
});
}
}
fn flush_table(&mut self, doc: &mut DoclingDocument) {
if !self.table_data.is_empty() {
// A pending caption is attached to this table and renders before it.
if let Some(cap) = self.take_caption(doc) {
doc.push(Node::Paragraph { text: cap });
}
let num_cols = self.table_data.iter().map(Vec::len).max().unwrap_or(0);
let rows: Vec<Vec<String>> = self
.table_data
.drain(..)
.map(|mut r| {
r.resize(num_cols, String::new());
r
})
.collect();
doc.push(Node::Table(Table {
rows,
location: None,
structure: None,
cell_blocks: None,
}));
}
self.in_table = false;
self.table_data.clear();
}
fn finish(&mut self, doc: &mut DoclingDocument) {
self.flush_text(doc);
if self.in_table {
self.flush_table(doc);
}
// Root-attached items (images, orphan headings) render last.
doc.nodes.append(&mut self.deferred);
}
fn is_active(&self, level: usize) -> bool {
self.active.get(level).copied().unwrap_or(false)
}
/// Mark `level` active and clear all deeper levels (a heading resets its
/// descendants), mirroring docling's `parents` bookkeeping.
fn set_active(&mut self, level: usize) {
if self.active.len() <= level {
self.active.resize(level + 1, false);
}
self.active[level] = true;
self.active.truncate(level + 1);
}
}
fn is_title(line: &str) -> Option<&str> {
line.strip_prefix("= ")
}
/// `== Section` → (number-of-`=`, text). A bare `=` (title) is excluded.
fn section_header(line: &str) -> Option<(u8, String)> {
if !line.starts_with("==") {
return None;
}
let caps = cached_regex!(r"^(=+)\s+(.*)").captures(line)?;
let level = caps.get(1)?.as_str().len() as u8;
Some((level, caps.get(2)?.as_str().to_string()))
}
/// A list item → (indent width, ordered, text).
fn list_item(line: &str) -> Option<(usize, bool, String)> {
let caps = cached_regex!(r"^(\s*)(\*|-|\d+\.)\s+(.*)").captures(line)?;
let indent = caps.get(1)?.as_str().len();
let marker = caps.get(2)?.as_str();
let text = caps.get(3)?.as_str().to_string();
let ordered = !(marker == "*" || marker == "-");
Some((indent, ordered, text))
}
fn is_table_line(line: &str) -> bool {
cached_regex!(&format!(r"^{CELL_SPEC}\|.*\|")).is_match(line)
}
/// Strip cell specifiers glued before a `|`, split on `|`, drop the leading
/// empty field, and trim — exactly as docling's `_parse_table_line`.
fn parse_table_line(line: &str) -> Vec<String> {
let cleaned = cached_regex!(&format!(r"(^|\s){CELL_SPEC}(\|)")).replace_all(line, "$1$2");
cleaned
.split('|')
.skip(1)
.map(|c| c.trim().to_string())
.collect()
}
fn is_picture(line: &str) -> Option<String> {
if !line.starts_with("image::") {
return None;
}
Some(
cached_regex!(r"^image::(.+)\[(.*)\]$")
.captures(line)
.and_then(|c| c.get(1).map(|m| m.as_str().trim().to_string()))
.unwrap_or_else(|| line.to_string()),
)
}
fn is_caption(line: &str) -> Option<&str> {
// `.text` but not `..` and not a list/other marker.
let rest = line.strip_prefix('.')?;
(!rest.is_empty()).then_some(rest)
}