1use std::collections::HashMap;
2use std::path::PathBuf;
3
4pub mod diagnostic;
5pub mod preprocessor;
6pub mod resolver;
7mod scanner;
8pub mod wikilink;
9
10pub use diagnostic::Diagnostic;
11
12use resolver::{ResolveContext, heading_id, relative_rendered_destination, resolve};
13use scanner::{Candidate, scan};
14use wikilink::{ParseError, WikiLink, parse};
15
16#[derive(Debug, Clone, Copy, PartialEq, Eq)]
17pub struct TransformOptions {
18 pub warn_on_missing: bool,
19 pub transform_embeds: bool,
20}
21
22#[derive(Debug, Clone, PartialEq, Eq)]
23pub struct ChapterLocation {
24 pub rendered_path: Option<PathBuf>,
25 pub source_path: Option<PathBuf>,
26}
27
28#[derive(Debug, Clone)]
29pub struct TransformContext {
30 pub source_root: PathBuf,
31 pub chapter_paths: HashMap<PathBuf, PathBuf>,
32 pub options: TransformOptions,
33}
34
35#[derive(Debug, Clone, PartialEq, Eq)]
36pub struct TransformOutput {
37 pub content: String,
38 pub diagnostics: Vec<Diagnostic>,
39}
40
41pub fn transform_chapter(
42 content: &str,
43 chapter: &ChapterLocation,
44 context: &TransformContext,
45) -> TransformOutput {
46 let scanned = scan(content);
47 let diagnostic_path = chapter
48 .source_path
49 .as_deref()
50 .or(chapter.rendered_path.as_deref());
51 let mut diagnostics: Vec<Diagnostic> = scanned
52 .issues
53 .into_iter()
54 .map(|issue| Diagnostic::at(content, diagnostic_path, issue.offset, issue.message))
55 .collect();
56 let mut replacements = Vec::new();
57
58 for candidate in scanned.candidates {
59 if candidate.embed && !context.options.transform_embeds {
60 continue;
61 }
62
63 let inner = &content[candidate.inner.clone()];
64 let parsed = match parse(inner, candidate.embed) {
65 Ok(parsed) => parsed,
66 Err(error) => {
67 if let Some(message) = parse_error_message(error) {
68 diagnostics.push(Diagnostic::at(
69 content,
70 diagnostic_path,
71 candidate.start,
72 message,
73 ));
74 }
75 continue;
76 }
77 };
78
79 if parsed.empty_alias {
80 diagnostics.push(Diagnostic::at(
81 content,
82 diagnostic_path,
83 candidate.start,
84 "empty alias; using the default label",
85 ));
86 }
87
88 if let Some(replacement) = render_candidate(
89 content,
90 chapter,
91 context,
92 diagnostic_path,
93 &candidate,
94 &parsed,
95 &mut diagnostics,
96 ) {
97 replacements.push((candidate.start, candidate.end, replacement));
98 }
99 }
100
101 if replacements.is_empty() {
102 return TransformOutput {
103 content: content.to_owned(),
104 diagnostics,
105 };
106 }
107
108 let mut transformed = String::with_capacity(content.len());
109 let mut cursor = 0;
110 for (start, end, replacement) in replacements {
111 transformed.push_str(&content[cursor..start]);
112 transformed.push_str(&replacement);
113 cursor = end;
114 }
115 transformed.push_str(&content[cursor..]);
116
117 TransformOutput {
118 content: transformed,
119 diagnostics,
120 }
121}
122
123fn render_candidate(
124 content: &str,
125 chapter: &ChapterLocation,
126 context: &TransformContext,
127 diagnostic_path: Option<&std::path::Path>,
128 candidate: &Candidate,
129 parsed: &WikiLink,
130 diagnostics: &mut Vec<Diagnostic>,
131) -> Option<String> {
132 if parsed.path.is_empty() {
133 return render_fragment_only(
134 content,
135 chapter,
136 diagnostic_path,
137 candidate,
138 parsed,
139 diagnostics,
140 );
141 }
142
143 let current_path = match chapter
144 .rendered_path
145 .as_deref()
146 .or(chapter.source_path.as_deref())
147 {
148 Some(path) => path,
149 None => {
150 diagnostics.push(Diagnostic::at(
151 content,
152 diagnostic_path,
153 candidate.start,
154 "cannot resolve a path-bearing link without a chapter path",
155 ));
156 return None;
157 }
158 };
159 let resolved = match resolve(
160 &parsed.path,
161 current_path,
162 &ResolveContext {
163 source_root: &context.source_root,
164 chapter_paths: &context.chapter_paths,
165 },
166 ) {
167 Ok(resolved) => resolved,
168 Err(error) => {
169 diagnostics.push(Diagnostic::at(
170 content,
171 diagnostic_path,
172 candidate.start,
173 format!("cannot convert target: {error}"),
174 ));
175 return None;
176 }
177 };
178
179 if context.options.warn_on_missing && !resolved.exists {
180 diagnostics.push(Diagnostic::at(
181 content,
182 diagnostic_path,
183 candidate.start,
184 format!(
185 "target does not exist: {}",
186 resolved.source_relative.display()
187 ),
188 ));
189 }
190
191 let is_block_reference = parsed
192 .fragment
193 .as_deref()
194 .is_some_and(|fragment| fragment.starts_with('^'));
195 let mut destination = resolved.destination.clone();
196 if let Some(fragment) = parsed.fragment.as_deref() {
197 if is_block_reference {
198 diagnostics.push(Diagnostic::at(
199 content,
200 diagnostic_path,
201 candidate.start,
202 "Obsidian block reference degraded to a file link",
203 ));
204 } else {
205 destination.push('#');
206 destination.push_str(&heading_id(fragment));
207 }
208 }
209
210 let alias_is_size =
211 parsed.embed && resolved.is_image && parsed.alias.as_deref().is_some_and(is_image_size);
212 if alias_is_size {
213 diagnostics.push(Diagnostic::at(
214 content,
215 diagnostic_path,
216 candidate.start,
217 "image size is not representable in standard Markdown and was discarded",
218 ));
219 }
220 let explicit_label = (!alias_is_size)
221 .then_some(parsed.alias.as_deref())
222 .flatten();
223 let default_label = default_label(parsed, &resolved);
224 let label = escape_label(explicit_label.unwrap_or(&default_label));
225
226 if parsed.embed && resolved.is_image {
227 Some(format!(""))
228 } else {
229 Some(format!("[{label}]({destination})"))
230 }
231}
232
233fn render_fragment_only(
234 content: &str,
235 chapter: &ChapterLocation,
236 diagnostic_path: Option<&std::path::Path>,
237 candidate: &Candidate,
238 parsed: &WikiLink,
239 diagnostics: &mut Vec<Diagnostic>,
240) -> Option<String> {
241 let fragment = parsed.fragment.as_deref()?;
242 let is_block_reference = fragment.starts_with('^');
243 let destination = if is_block_reference {
244 let current_path = match chapter
245 .rendered_path
246 .as_deref()
247 .or(chapter.source_path.as_deref())
248 {
249 Some(path) => path,
250 None => {
251 diagnostics.push(Diagnostic::at(
252 content,
253 diagnostic_path,
254 candidate.start,
255 "cannot degrade a block reference without a chapter path",
256 ));
257 return None;
258 }
259 };
260 diagnostics.push(Diagnostic::at(
261 content,
262 diagnostic_path,
263 candidate.start,
264 "Obsidian block reference degraded to a file link",
265 ));
266 match relative_rendered_destination(current_path, current_path) {
267 Ok(destination) => destination,
268 Err(error) => {
269 diagnostics.push(Diagnostic::at(
270 content,
271 diagnostic_path,
272 candidate.start,
273 format!("cannot convert target: {error}"),
274 ));
275 return None;
276 }
277 }
278 } else {
279 format!("#{}", heading_id(fragment))
280 };
281 let label = escape_label(parsed.alias.as_deref().unwrap_or(fragment));
282 Some(format!("[{label}]({destination})"))
283}
284
285fn default_label(parsed: &WikiLink, resolved: &resolver::ResolvedTarget) -> String {
286 if let Some(fragment) = parsed.fragment.as_deref() {
287 return fragment.to_owned();
288 }
289 if parsed.embed && resolved.is_image {
290 return PathBuf::from(&resolved.display_path)
291 .file_stem()
292 .and_then(|value| value.to_str())
293 .unwrap_or(&resolved.display_path)
294 .to_owned();
295 }
296 if parsed.embed && !resolved.is_note {
297 return resolved
298 .display_path
299 .rsplit('/')
300 .next()
301 .unwrap_or(&resolved.display_path)
302 .to_owned();
303 }
304 resolved.display_path.clone()
305}
306
307fn is_image_size(value: &str) -> bool {
308 let mut parts = value.split(['x', 'X']);
309 let width = parts.next().unwrap_or_default();
310 let height = parts.next();
311 !width.is_empty()
312 && width.bytes().all(|byte| byte.is_ascii_digit())
313 && height.is_none_or(|height| {
314 !height.is_empty() && height.bytes().all(|byte| byte.is_ascii_digit())
315 })
316 && parts.next().is_none()
317}
318
319fn escape_label(label: &str) -> String {
320 label
321 .replace('\\', "\\\\")
322 .replace('[', "\\[")
323 .replace(']', "\\]")
324 .replace(['\n', '\r'], " ")
325}
326
327fn parse_error_message(error: ParseError) -> Option<&'static str> {
328 match error {
329 ParseError::EmptyTarget => Some("empty target was left unchanged"),
330 ParseError::NestedLink => Some("nested wiki link was left unchanged"),
331 ParseError::Multiline => Some("multiline wiki link was left unchanged"),
332 }
333}