summaryrefslogtreecommitdiff
path: root/src/main.rs
blob: 07eb673afa9de4c99ca86a1ca0e0438276081cfc (plain) (blame)
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
use std::fs;
use std::path::{Path, PathBuf};

use anyhow::{anyhow, bail, Context};
use fontdock::fs::FsIndex;

use typst::diag::{Feedback, Pass};
use typst::env::{Env, ResourceLoader};
use typst::eval::State;
use typst::export::pdf;
use typst::font::FsIndexExt;
use typst::library;
use typst::parse::LineMap;
use typst::typeset;

fn main() -> anyhow::Result<()> {
    let args: Vec<_> = std::env::args().collect();
    if args.len() < 2 || args.len() > 3 {
        println!("Usage: typst src.typ [out.pdf]");
        return Ok(());
    }

    let src_path = Path::new(&args[1]);
    let dest_path = if args.len() <= 2 {
        let name = src_path
            .file_name()
            .ok_or_else(|| anyhow!("Source path is not a file."))?;
        Path::new(name).with_extension("pdf")
    } else {
        PathBuf::from(&args[2])
    };

    if src_path == dest_path {
        bail!("Source and destination path are the same.");
    }

    let src = fs::read_to_string(src_path).context("Failed to read from source file.")?;

    let mut index = FsIndex::new();
    index.search_dir("fonts");
    index.search_system();

    let mut env = Env {
        fonts: index.into_dynamic_loader(),
        resources: ResourceLoader::new(),
    };

    let scope = library::new();
    let state = State::default();

    let Pass {
        output: frames,
        feedback: Feedback { mut diags, .. },
    } = typeset(&src, &mut env, &scope, state);

    if !diags.is_empty() {
        diags.sort();

        let map = LineMap::new(&src);
        for diag in diags {
            let span = diag.span;
            let start = map.location(span.start).unwrap();
            let end = map.location(span.end).unwrap();
            println!(
                "{}: {}:{}-{}: {}",
                diag.v.level,
                src_path.display(),
                start,
                end,
                diag.v.message,
            );
        }
    }

    let pdf_data = pdf::export(&frames, &env);
    fs::write(&dest_path, pdf_data).context("Failed to write PDF file.")?;

    Ok(())
}