ikat 0.2.1

Weave Markdown into camera-ready LaTeX: mermaid-to-TikZ, pgfplots figures, publisher templates
Documentation
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
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
//! Document configuration: columns, margins, per-element spanning.
//!
//! An `ikat.toml` sits next to the manuscript:
//!
//! ```toml
//! [document]
//! class = "IEEEtran"
//! class_options = ["conference"]
//! columns = 2
//! margins = "0.75in"
//!
//! [spans]
//! diagram = "wide"    # figure* — TikZ flowcharts breathe at text width
//! plot    = "column"  # figure  — data graphics stay in-column
//! table   = "column"
//! default = "column"
//! ```
//!
//! A single element overrides its kind default from Markdown with a
//! trailing attribute comment on the fence info line, e.g.
//! ```` ```mermaid {span=column} ````.

use serde::{Deserialize, Serialize};

/// One/two-column placement of a floated element.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum Span {
    /// Single column: `figure` / one-column table.
    Column,
    /// Full text width: `figure*`.
    Wide,
}

impl Span {
    pub fn latex_env(&self) -> &'static str {
        match self {
            Span::Column => "figure",
            Span::Wide => "figure*",
        }
    }

    pub fn latex_width(&self) -> &'static str {
        match self {
            Span::Column => "\\columnwidth",
            Span::Wide => "\\textwidth",
        }
    }
}

/// `[document]` table.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Document {
    #[serde(default = "default_class")]
    pub class: String,
    #[serde(default)]
    pub class_options: Vec<String>,
    #[serde(default = "default_columns")]
    pub columns: u8,
    #[serde(default = "default_margins")]
    pub margins: String,
}

fn default_class() -> String {
    "IEEEtran".to_string()
}
fn default_columns() -> u8 {
    2
}
fn default_margins() -> String {
    "0.75in".to_string()
}

impl Default for Document {
    fn default() -> Self {
        Self {
            class: default_class(),
            class_options: vec!["conference".to_string()],
            columns: default_columns(),
            margins: default_margins(),
        }
    }
}

/// Float placement for one element: how close to its manuscript
/// position LaTeX may keep it. `figure*` wide floats only support
/// Top/Bottom/Page/Barrier (LaTeX bans `[h]`/`[H]` on `*` floats).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum Pos {
    /// `[t]`: top of column/page (default, journals-safe).
    Top,
    /// `[b]`: bottom (wide needs `dblfloatfix`, auto-added).
    Bottom,
    /// `[!tb]`: same column, top preferred, limits overridden.
    Both,
    /// `[p]`: dedicated float page.
    Page,
    /// `[h]`: here if it fits (polite request).
    Here,
    /// `[H]`: exactly here (needs `float` pkg, auto-added).
    Force,
    /// `\FloatBarrier` + `[t]`: never drift past this element.
    Barrier,
}

impl Pos {
    pub fn parse(s: &str) -> Result<Pos, String> {
        match s {
            "top" => Ok(Pos::Top),
            "bottom" => Ok(Pos::Bottom),
            "both" => Ok(Pos::Both),
            "page" => Ok(Pos::Page),
            "here" => Ok(Pos::Here),
            "force" => Ok(Pos::Force),
            "barrier" => Ok(Pos::Barrier),
            _ => Err(format!("pos must be top|bottom|both|page|here|force|barrier, got {s:?}")),
        }
    }

    /// LaTeX placement spec, or empty for Barrier (prefix instead).
    pub fn latex_spec(self) -> &'static str {
        match self {
            Pos::Top => "[t]",
            Pos::Bottom => "[b]",
            Pos::Both => "[!tb]",
            Pos::Page => "[p]",
            Pos::Here => "[h]",
            Pos::Force => "[H]",
            Pos::Barrier => "[t]",
        }
    }
}

/// Caption placement: figures conventionally below, tables above.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum CaptionPos {
    Top,
    Bottom,
}

impl CaptionPos {
    pub fn parse(s: &str) -> Result<CaptionPos, String> {
        match s {
            "top" => Ok(CaptionPos::Top),
            "bottom" => Ok(CaptionPos::Bottom),
            _ => Err(format!("captionpos must be top|bottom, got {s:?}")),
        }
    }
}

/// Package needs one float element can trigger, OR-combined across
/// the document. The preamble (or template validation) consumes this.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct FloatNeeds {
    pub float_h: bool,
    pub barrier: bool,
    pub dblfloat: bool,
    pub graphicx: bool,
}

impl FloatNeeds {
    pub fn none() -> Self {
        Self::default()
    }

    pub fn add(&mut self, o: FloatNeeds) {
        self.float_h |= o.float_h;
        self.barrier |= o.barrier;
        self.dblfloat |= o.dblfloat;
        self.graphicx |= o.graphicx;
    }

    /// Preamble lines, in load order.
    pub fn packages(&self) -> Vec<String> {
        let mut out = Vec::new();
        if self.float_h {
            out.push("\\usepackage{float}".to_string());
        }
        if self.barrier {
            out.push("\\usepackage{placeins}".to_string());
        }
        if self.dblfloat {
            out.push("\\usepackage{dblfloatfix}".to_string());
        }
        out
    }

    /// LaTeX names template validation requires in the head.
    pub fn required_names(&self) -> Vec<&'static str> {
        let mut out = Vec::new();
        if self.float_h {
            out.push("float");
        }
        if self.barrier {
            out.push("placeins");
        }
        if self.dblfloat {
            out.push("dblfloatfix");
        }
        if self.graphicx {
            out.push("graphicx");
        }
        out
    }
}

/// `[spans]` table: default float span per element kind.
/// `picture` (precompiled graphics) falls back to `diagram` when
/// unset, so existing documents keep their wide figures.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Spans {
    #[serde(default = "span_wide")]
    pub diagram: Span,
    #[serde(default = "span_column")]
    pub plot: Span,
    #[serde(default = "span_column")]
    pub table: Span,
    #[serde(default)]
    pub picture: Option<Span>,
    #[serde(default = "span_column")]
    pub default: Span,
}

fn span_wide() -> Span {
    Span::Wide
}
fn span_column() -> Span {
    Span::Column
}

impl Default for Spans {
    fn default() -> Self {
        Self {
            diagram: Span::Wide,
            plot: Span::Column,
            table: Span::Column,
            picture: None,
            default: Span::Column,
        }
    }
}

impl Spans {
    pub fn for_kind(&self, kind: &str) -> Span {
        match kind {
            "diagram" => self.diagram,
            "plot" => self.plot,
            "table" => self.table,
            "picture" => self.picture.unwrap_or(self.diagram),
            _ => self.default,
        }
    }
}

/// `[template]` table: user-supplied preamble pieces.
///
/// ```toml
/// [template]
/// preamble_file = "journal-head.tex"  # replaces the generated head
/// preamble_append = ["\\usepackage{natbib}"]  # extra lines before \\begin{document}
/// ```
///
/// `preamble_file` is resolved by Python relative to the toml file;
/// Rust only ever sees file *content* (via `BuildSpec`).
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct Template {
    #[serde(default)]
    pub preamble_file: String,
    #[serde(default)]
    pub preamble_append: Vec<String>,
    /// Top-matter classes (ACM, Elsevier, APS) set the abstract in
    /// `\maketitle`: hoist the body's abstract env before it.
    #[serde(default)]
    pub abstract_before_maketitle: bool,
    /// Whole-document skeleton file (level 3 escape hatch);
    /// mutually exclusive with `preamble_file` (checked at build).
    #[serde(default)]
    pub skeleton: String,
}

/// `[floats]` table: document-wide float tuning. Fraction/counter
/// lines are emitted into the preamble ONLY when they differ from
/// the LaTeX defaults, so default documents weave byte-identically.
///
/// ```toml
/// [floats]
/// pos_default = "top"
/// topfraction = 0.9
/// bottomfraction = 0.8
/// textfraction = 0.1
/// floatpagefraction = 0.6
/// topnumber = 2
/// bottomnumber = 2
/// barrier_sections = false
/// ```
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Floats {
    #[serde(default = "pos_top")]
    pub pos_default: Pos,
    #[serde(default = "frac_top")]
    pub topfraction: f64,
    #[serde(default = "frac_bottom")]
    pub bottomfraction: f64,
    #[serde(default = "frac_text")]
    pub textfraction: f64,
    #[serde(default = "frac_floatpage")]
    pub floatpagefraction: f64,
    #[serde(default = "num_top")]
    pub topnumber: i64,
    #[serde(default = "num_bottom")]
    pub bottomnumber: i64,
    #[serde(default)]
    pub barrier_sections: bool,
}

fn pos_top() -> Pos {
    Pos::Top
}
fn frac_top() -> f64 {
    0.7
}
fn frac_bottom() -> f64 {
    0.3
}
fn frac_text() -> f64 {
    0.2
}
fn frac_floatpage() -> f64 {
    0.5
}
fn num_top() -> i64 {
    2
}
fn num_bottom() -> i64 {
    1
}

impl Default for Floats {
    fn default() -> Self {
        Self {
            pos_default: Pos::Top,
            topfraction: 0.7,
            bottomfraction: 0.3,
            textfraction: 0.2,
            floatpagefraction: 0.5,
            topnumber: 2,
            bottomnumber: 1,
            barrier_sections: false,
        }
    }
}

impl Floats {
    /// Preamble lines for knobs that differ from LaTeX defaults.
    /// Empty for a default `[floats]` (golden parity).
    pub fn setup_lines(&self) -> Vec<String> {
        let mut lines = Vec::new();
        let mut frac = |name: &str, val: f64, dflt: f64| {
            if (val - dflt).abs() > 1e-9 {
                lines.push(format!("\\renewcommand{{\\{name}}}{{{val}}}"));
            }
        };
        frac("topfraction", self.topfraction, 0.7);
        frac("bottomfraction", self.bottomfraction, 0.3);
        frac("textfraction", self.textfraction, 0.2);
        frac("floatpagefraction", self.floatpagefraction, 0.5);
        if self.topnumber != 2 {
            lines.push(format!("\\setcounter{{topnumber}}{{{}}}", self.topnumber));
        }
        if self.bottomnumber != 1 {
            lines.push(format!("\\setcounter{{bottomnumber}}{{{}}}", self.bottomnumber));
        }
        lines
    }
}

/// Whole-file configuration.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct Config {
    #[serde(default)]
    pub document: Document,
    #[serde(default)]
    pub spans: Spans,
    #[serde(default)]
    pub floats: Floats,
    #[serde(default)]
    pub template: Template,
}

impl Config {
    pub fn from_toml(src: &str) -> Result<Self, String> {
        toml::from_str(src).map_err(|e| format!("ikat.toml: {e}"))
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn defaults_favour_readable_diagrams() {
        let cfg = Config::from_toml("").unwrap();
        assert_eq!(cfg.document.class, "IEEEtran");
        assert_eq!(cfg.document.columns, 2);
        assert_eq!(cfg.spans.diagram, Span::Wide);
        assert_eq!(cfg.spans.plot, Span::Column);
    }

    #[test]
    fn spans_parse_and_envs_map() {
        let cfg = Config::from_toml(
            "[spans]\ndiagram = \"column\"\nplot = \"wide\"\n",
        )
        .unwrap();
        assert_eq!(cfg.spans.for_kind("diagram").latex_env(), "figure");
        assert_eq!(cfg.spans.for_kind("plot").latex_env(), "figure*");
        assert_eq!(cfg.spans.for_kind("table").latex_env(), "figure");
        assert_eq!(cfg.spans.for_kind("diagram").latex_width(), "\\columnwidth");
    }

    #[test]
    fn template_table_parses() {
        let cfg = Config::from_toml(
            "[template]\npreamble_file = \"head.tex\"\npreamble_append = [\"\\\\usepackage{natbib}\"]\n",
        )
        .unwrap();
        assert_eq!(cfg.template.preamble_file, "head.tex");
        assert_eq!(cfg.template.preamble_append, vec!["\\usepackage{natbib}"]);
        assert!(Config::from_toml("").unwrap().template.preamble_append.is_empty());
    }

    #[test]
    fn template_flag_parses() {
        let cfg = Config::from_toml("[template]\nabstract_before_maketitle = true\n").unwrap();
        assert!(cfg.template.abstract_before_maketitle);
        assert!(!Config::from_toml("").unwrap().template.abstract_before_maketitle);
    }

    #[test]
    fn picture_falls_back_to_diagram() {
        let cfg = Config::from_toml("").unwrap();
        assert_eq!(cfg.spans.for_kind("picture"), Span::Wide);
        let cfg = Config::from_toml("[spans]\npicture = \"column\"\n").unwrap();
        assert_eq!(cfg.spans.for_kind("picture"), Span::Column);
        assert_eq!(cfg.spans.for_kind("diagram"), Span::Wide);
    }

    #[test]
    fn pos_parses_strictly() {
        assert_eq!(Pos::parse("both"), Ok(Pos::Both));
        assert_eq!(Pos::Both.latex_spec(), "[!tb]");
        assert_eq!(Pos::Barrier.latex_spec(), "[t]");
        assert!(Pos::parse("center").is_err());
    }

    #[test]
    fn float_setup_lines_only_nondefaults() {
        assert!(Config::from_toml("").unwrap().floats.setup_lines().is_empty());
        let cfg = Config::from_toml("[floats]\ntopfraction = 0.9\nbottomnumber = 2\n").unwrap();
        let lines = cfg.floats.setup_lines();
        assert!(lines.contains(&"\\renewcommand{\\topfraction}{0.9}".to_string()));
        assert!(lines.contains(&"\\setcounter{bottomnumber}{2}".to_string()));
        assert_eq!(lines.len(), 2);
        assert!(cfg.floats.barrier_sections == false);
    }

    #[test]
    fn bad_toml_is_an_error_string() {
        assert!(Config::from_toml("[spans\ndiagram = 42\n").is_err());
    }
}