marmite 0.3.1

Marmite is the easiest static site generator.
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
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
use crate::embedded::EMBEDDED_SHORTCODES;
use crate::highlight::MarmiteHighlighter;
use crate::re;
use log::{debug, warn};
use regex::Regex;
use serde::Serialize;
use std::collections::HashMap;
use std::fs;
use std::path::Path;
use tera::{Context, Tera};

#[derive(Debug, Clone, Serialize)]
pub struct Shortcode {
    pub name: String,
    pub content: String,
    pub is_html: bool,
    pub description: Option<String>,
}

pub struct ShortcodeProcessor {
    pub shortcodes: HashMap<String, Shortcode>,
    pub pattern: Regex,
}

impl ShortcodeProcessor {
    pub fn new(pattern: Option<&str>) -> Self {
        let pattern = Regex::new(pattern.unwrap_or(re::SHORTCODE_HTML_COMMENT))
            .expect("Invalid shortcode pattern");

        Self {
            shortcodes: HashMap::new(),
            pattern,
        }
    }

    /// Add shortcodes to Tera instance
    pub fn add_shortcodes_to_tera(&self, tera: &mut Tera) -> Result<(), String> {
        for (name, shortcode) in &self.shortcodes {
            if shortcode.is_html {
                tera.add_raw_template(&format!("shortcodes/{name}"), &shortcode.content)
                    .map_err(|e| format!("Failed to add shortcode template '{name}': {e}"))?;
            }
        }
        Ok(())
    }

    /// Collect shortcodes from the `input_dir/shortcodes` directory
    pub fn collect_shortcodes(&mut self, input_dir: &Path) -> Result<(), String> {
        let shortcodes_dir = input_dir.join("shortcodes");

        // Add builtin shortcodes first (always load them)
        self.add_builtin_shortcodes();

        if !shortcodes_dir.exists() {
            debug!(
                "No shortcodes directory found at {}",
                shortcodes_dir.display()
            );
            return Ok(());
        }

        // Then add user shortcodes (which can override builtins)
        let entries = fs::read_dir(&shortcodes_dir)
            .map_err(|e| format!("Failed to read shortcodes directory: {e}"))?;

        for entry in entries {
            let entry = entry.map_err(|e| format!("Failed to read directory entry: {e}"))?;
            let path = entry.path();

            if path.is_file() {
                if let Some(extension) = path.extension() {
                    if extension == "html" || extension == "md" {
                        self.load_shortcode(&path)?;
                    }
                }
            }
        }

        Ok(())
    }

    fn load_shortcode(&mut self, path: &Path) -> Result<(), String> {
        let content = fs::read_to_string(path)
            .map_err(|e| format!("Failed to read shortcode file {}: {e}", path.display()))?;

        let file_name = path
            .file_stem()
            .and_then(|s| s.to_str())
            .ok_or_else(|| format!("Invalid file name: {}", path.display()))?;

        let is_html = path
            .extension()
            .and_then(|s| s.to_str())
            .is_some_and(|ext| ext == "html");

        // Extract description from Tera comment on first line
        let description = self.extract_description(&content);

        if is_html {
            // For HTML files, validate that they contain macros
            if !content.contains("{% macro") {
                return Err(format!(
                    "HTML shortcode file {} must contain at least one macro",
                    path.display()
                ));
            }

            // Validate that the file contains a macro with the same name as the filename
            let macro_pattern =
                Regex::new(re::CAPTURE_TERA_MACRO_CALL).expect("Invalid macro pattern");
            let macro_names: Vec<String> = macro_pattern
                .captures_iter(&content)
                .map(|cap| cap[1].to_string())
                .collect();

            if !macro_names.contains(&file_name.to_string()) {
                return Err(format!(
                    "HTML shortcode file {} must contain a macro named '{}'. Found macros: {:?}",
                    path.display(),
                    file_name,
                    macro_names
                ));
            }
        }

        let shortcode = Shortcode {
            name: file_name.to_string(),
            content: content.clone(),
            is_html,
            description,
        };

        debug!("Loaded shortcode: {file_name}");
        self.shortcodes.insert(file_name.to_string(), shortcode);

        Ok(())
    }

    #[allow(clippy::unused_self)]
    fn extract_description(&self, content: &str) -> Option<String> {
        // Check if the first line is a Tera comment {# ... #}
        let first_line = content.lines().next()?;
        let trimmed = first_line.trim();

        if trimmed.starts_with("{#") && trimmed.ends_with("#}") {
            // Extract content between {# and #}
            let desc = trimmed
                .strip_prefix("{#")?
                .strip_suffix("#}")?
                .trim()
                .to_string();

            if !desc.is_empty() {
                return Some(desc);
            }
        }

        None
    }

    fn add_builtin_shortcodes(&mut self) {
        // Load shortcodes from embedded files
        for (file_name, file_data) in EMBEDDED_SHORTCODES.iter() {
            let content = match std::str::from_utf8(file_data) {
                Ok(content) => content,
                Err(e) => {
                    warn!("Failed to read embedded shortcode '{file_name}': {e}");
                    continue;
                }
            };

            // Extract filename without extension
            let lowercase_name = file_name.to_lowercase();
            let shortcode_name = if let Some(name) = lowercase_name.strip_suffix(".html") {
                name
            } else if let Some(name) = lowercase_name.strip_suffix(".md") {
                name
            } else {
                warn!("Embedded shortcode '{file_name}' does not have .html or .md extension");
                continue;
            };

            // Determine if it's HTML or markdown
            let is_html = file_name.to_lowercase().ends_with(".html");

            // Extract description from content
            let description = self.extract_description(content);

            let shortcode = Shortcode {
                name: shortcode_name.to_string(),
                content: content.to_string(),
                is_html,
                description,
            };

            debug!("Loaded embedded shortcode: {shortcode_name}");
            self.shortcodes
                .insert(shortcode_name.to_string(), shortcode);
        }
    }

    /// Process shortcodes in HTML content
    pub fn process_shortcodes(
        &self,
        html: &str,
        context: &Context,
        tera: &Tera,
        highlighter: Option<&MarmiteHighlighter>,
    ) -> String {
        let mut result = html.to_string();

        let preview_end = {
            let mut end = html.len().min(1500);
            while end > 0 && !html.is_char_boundary(end) {
                end -= 1;
            }
            end
        };
        debug!(
            "Searching for shortcode pattern in HTML (first 1500 chars): {}",
            &html[..preview_end]
        );

        for captures in self.pattern.captures_iter(html) {
            let full_match = &captures[0];
            let shortcode_name = &captures[1];
            let params = captures.get(2).map_or("", |m| m.as_str().trim());

            log::info!(
                "Processing shortcode: name='{shortcode_name}', params='{params}', full_match='{full_match}'"
            );

            match self.render_shortcode(shortcode_name, params, context, tera, highlighter) {
                Ok(rendered) => {
                    debug!("Successfully rendered shortcode '{shortcode_name}': '{rendered}'");
                    result = result.replace(full_match, &rendered);
                }
                Err(e) => {
                    warn!("Shortcode '{shortcode_name}' failed to render: {e}");
                    // Render an error message in the HTML output
                    let escaped_error = e
                        .replace('&', "&amp;")
                        .replace('<', "&lt;")
                        .replace('>', "&gt;")
                        .replace('"', "&quot;")
                        .replace('\'', "&#39;");
                    let error_msg = format!(
                        r#"<div class="shortcode-error" style="border: 2px solid red; padding: 10px; margin: 10px 0; background-color: #ffeeee; color: #cc0000;">
                        <strong>Shortcode Error:</strong> {escaped_error}</div>"#
                    );
                    result = result.replace(full_match, &error_msg);
                }
            }
        }

        result
    }

    fn render_shortcode(
        &self,
        name: &str,
        params: &str,
        context: &Context,
        tera: &Tera,
        highlighter: Option<&MarmiteHighlighter>,
    ) -> Result<String, String> {
        let shortcode = self
            .shortcodes
            .get(name)
            .ok_or_else(|| format!("Shortcode '{name}' not found"))?;

        if shortcode.is_html {
            // Parse parameters into macro arguments
            let macro_args = if params.is_empty() {
                String::new()
            } else {
                // Parse key=value pairs with proper quote handling
                let mut args = Vec::new();
                let parsed_params = Self::parse_parameters(params);
                for (key, value) in parsed_params {
                    // Ensure value is properly quoted for Tera
                    let quoted_value = if value.starts_with('"') && value.ends_with('"') {
                        value
                    } else if value.starts_with('\'') && value.ends_with('\'') {
                        // Convert single quotes to double quotes for Tera
                        format!("\"{}\"", &value[1..value.len() - 1])
                    } else {
                        format!("\"{value}\"")
                    };
                    args.push(format!("{key}={quoted_value}"));
                }
                args.join(", ")
            };

            // Render HTML shortcode using Tera macro
            let shortcode_template = format!(
                "{{% import \"shortcodes/{name}\" as sc -%}}\n{{{{ sc::{name}({macro_args}) }}}}"
            );

            debug!("Rendering shortcode '{name}' with template: {shortcode_template}");
            debug!("Shortcode params: '{params}' -> macro_args: '{macro_args}'");

            let mut tera_clone = tera.clone();
            tera_clone
                .render_str(&shortcode_template, context)
                .map_err(|e| format!("Failed to render shortcode '{name}': {e}"))
        } else {
            // Render markdown shortcode
            let mut tera_clone = tera.clone();
            let rendered = tera_clone
                .render_str(&shortcode.content, context)
                .map_err(|e| format!("Failed to render markdown shortcode '{name}': {e}"))?;

            // Convert markdown to HTML
            let default_parser_options = crate::config::ParserOptions::default();
            Ok(crate::parser::get_html_with_options(
                &rendered,
                &default_parser_options,
                highlighter,
            ))
        }
    }

    /// Get list of available shortcodes with descriptions
    pub fn list_shortcodes_with_descriptions(&self) -> Vec<(&str, Option<&str>)> {
        let mut shortcodes: Vec<(&str, Option<&str>)> = self
            .shortcodes
            .iter()
            .map(|(name, sc)| (name.as_str(), sc.description.as_deref()))
            .collect();
        shortcodes.sort_by_key(|(name, _)| *name);
        shortcodes
    }

    /// Parse parameters from a string, handling quoted values correctly
    fn parse_parameters(params: &str) -> Vec<(String, String)> {
        let mut result = Vec::new();
        let mut chars = params.chars().peekable();

        while let Some(ch) = chars.next() {
            if ch.is_whitespace() {
                continue;
            }

            // Parse key
            let mut key = String::new();
            let mut current_char = ch;

            loop {
                if current_char == '=' {
                    break;
                } else if current_char.is_whitespace() {
                    // Skip whitespace before =
                    while let Some(&next_ch) = chars.peek() {
                        if next_ch.is_whitespace() {
                            chars.next();
                        } else {
                            break;
                        }
                    }
                    if let Some(&'=') = chars.peek() {
                        chars.next(); // consume the =
                        break;
                    }
                    // No = found, this is not a valid key=value pair
                    break;
                }
                key.push(current_char);

                if let Some(next_ch) = chars.next() {
                    current_char = next_ch;
                } else {
                    break;
                }
            }

            if key.is_empty() {
                continue;
            }

            // Skip whitespace after =
            while let Some(&next_ch) = chars.peek() {
                if next_ch.is_whitespace() {
                    chars.next();
                } else {
                    break;
                }
            }

            // Parse value
            let mut value = String::new();

            if let Some(&quote_char) = chars.peek() {
                if quote_char == '"' || quote_char == '\'' {
                    // Handle quoted value
                    chars.next(); // consume opening quote
                    value.push(quote_char);

                    for ch in chars.by_ref() {
                        value.push(ch);
                        if ch == quote_char {
                            // Check if it's escaped
                            let mut backslash_count = 0;
                            let temp_chars: Vec<char> = value.chars().rev().skip(1).collect();
                            for &c in &temp_chars {
                                if c == '\\' {
                                    backslash_count += 1;
                                } else {
                                    break;
                                }
                            }

                            // If even number of backslashes (including 0), quote is not escaped
                            if backslash_count % 2 == 0 {
                                break;
                            }
                        }
                    }
                } else {
                    // Handle unquoted value
                    while let Some(&next_ch) = chars.peek() {
                        if next_ch.is_whitespace() {
                            break;
                        }
                        if let Some(ch) = chars.next() {
                            value.push(ch);
                        } else {
                            // This should not happen since we peeked successfully, but be safe
                            break;
                        }
                    }
                }
            }

            if !value.is_empty() {
                result.push((key, value));
            }
        }

        result
    }
}

#[cfg(test)]
#[path = "tests/shortcodes.rs"]
mod tests;