typ2anki 1.0.12

Compile Typst flashcards into Anki decks
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
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
use std::{
    collections::HashSet,
    path::PathBuf,
    sync::{Arc, LazyLock},
};

use regex::Regex;

use crate::{
    card_wrapper::{CardInfo, TypFileStats},
    cards_cache::CardsCacheManager,
    config,
    output::{OutputManager, OutputMessage},
    utils,
};

const DEFAULT_ANKICONF: &str = "#let conf(
  doc,
) = {
  doc
}";

pub fn check_ankiconf_exists() {
    let cfg = config::get();
    let ankiconf_path = cfg.path.join("ankiconf.typ");
    if !ankiconf_path.exists() {
        std::fs::write(&ankiconf_path, DEFAULT_ANKICONF).expect("Failed to create ankiconf.typ");
    }
}

pub static QUESTION_EMPTY_RE: LazyLock<Regex> =
    LazyLock::new(|| Regex::new(r#"q:\s*(\[\s*\]|"\s*")"#).unwrap());
pub static ANSWER_EMPTY_RE: LazyLock<Regex> =
    LazyLock::new(|| Regex::new(r#"a:\s*(\[\s*\]|"\s*")"#).unwrap());

pub static ID_RE: LazyLock<Regex> = LazyLock::new(|| Regex::new(r#"id:\s*"([^"]*)""#).unwrap());
pub static DECK_RE: LazyLock<Regex> =
    LazyLock::new(|| Regex::new(r#"target-deck:\s*"([^"]+)""#).unwrap());
pub static QUESTION_RE: LazyLock<Regex> =
    LazyLock::new(|| Regex::new(r#"q:\s*(\[(?:.|\n)*\]|"(?:.|\n)*")"#).unwrap());
pub static ANSWER_RE: LazyLock<Regex> =
    LazyLock::new(|| Regex::new(r#"a:\s*(\[(?:.|\n)*\]|"(?:.|\n)*")"#).unwrap());

pub fn is_card_empty(card_str: &str) -> bool {
    QUESTION_EMPTY_RE.is_match(card_str) && ANSWER_EMPTY_RE.is_match(card_str)
}

pub fn get_ankiconf_hash() -> String {
    let cfg = config::get();
    let ankiconf_path = cfg.path.join("ankiconf.typ");
    if !ankiconf_path.exists() {
        return String::new();
    }
    let mut content = std::fs::read_to_string(ankiconf_path).unwrap_or_default();
    let imports = utils::get_all_typst_imports(content.as_str());

    for import in imports {
        if let Ok(import_content) = std::fs::read_to_string(&import) {
            content.push('\n');
            content.push_str(&import_content);
        }
    }

    utils::hash_string(&content)
}

#[cfg(feature = "tree-sitter")]
mod parse_card_tree_sitter {
    use super::*;
    use crate::card_wrapper::BarebonesCardInfo;

    use std::sync::Mutex;

    use once_cell::sync::OnceCell;
    use tree_sitter::{Node, Parser};

    static TS_PARSER: OnceCell<Mutex<Parser>> = OnceCell::new();
    static VALUE_TRIM_CHARS: &[char] = &['"', ' ', '\n', '\t', '\r', '[', ']', ':'];

    fn get_tagged_argument_value(source: &[u8], node: &Node, arg_name: &str) -> Option<String> {
        let mut cursor = node.walk();

        let arguments_node = node
            .child_by_field_name("arguments")
            .or_else(|| node.child_by_field_name("group"))
            .or_else(|| node.named_child(1));

        let arguments_node = arguments_node?;

        for child in arguments_node.named_children(&mut cursor) {
            if child.kind() == "tagged" {
                if let Some(field_node) = child.child_by_field_name("field") {
                    let field_name = field_node.utf8_text(source).ok()?;
                    if field_name == arg_name {
                        if let Some(value_node) = child.child(2).or_else(|| child.child(1)) {
                            return value_node.utf8_text(source).ok().map(|s| s.to_string());
                        }
                    }
                }
            }
        }

        None
    }

    fn get_function_from_call_node<'a>(
        source: &[u8],
        node: Node<'a>,
        function_name: &str,
    ) -> Option<Node<'a>> {
        if let Some(item) = node.child_by_field_name("item") {
            if item.kind() == "identifier" || item.kind() == "ident" {
                let name = item.utf8_text(source).unwrap();
                if name == function_name {
                    return Some(node);
                }
            }
        }
        None
    }

    pub fn parse_cards_string(
        content: &str,
        output: &Arc<impl OutputManager + 'static>,
        _no_prelude: bool,
    ) -> Vec<String> {
        let cfg = config::get();
        const CARD_FUNCTION_NAME: &str = "custom-card";

        let mut ts_parser = TS_PARSER
            .get_or_init(|| {
                let mut parser = Parser::new();
                parser
                    .set_language(tree_sitter_typst::language())
                    .expect("Error loading typst grammar");
                Mutex::new(parser)
            })
            .lock()
            .unwrap();

        let tree = match ts_parser.parse(content, None) {
            Some(t) => t,
            None => return vec![],
        };
        let source = content.as_bytes();
        let mut cursor = tree.root_node().walk();
        let mut cards = Vec::new();

        let handle_card_node =
            |func_call: Node, parent: &Node| -> Result<BarebonesCardInfo, &str> {
                macro_rules! ga {
                    ($tag:expr) => {
                        get_tagged_argument_value(source, parent, $tag)
                            .map(|s| s.trim_matches(VALUE_TRIM_CHARS).to_string())
                            .filter(|s| s != "")
                    };
                }

                let id = ga!("id").ok_or("Couldn't parse id")?;
                let target_deck = ga!("target-deck").ok_or("Couldn't parse target-deck")?;

                Ok(BarebonesCardInfo {
                    card_id: id,
                    deck_name: target_deck,
                    question: ga!("q").unwrap_or(String::new()),
                    answer: ga!("a").unwrap_or(String::new()),
                    byte_range: (func_call.start_byte(), func_call.end_byte()),
                    prelude_range: None,
                })
            };

        // Checks that the call_node isn't being defined in a let statement
        let check_isnt_let = |call_node: &Node| {
            if let Some(parent) = call_node.parent() {
                if parent.kind() == "let" {
                    return false;
                }
            }
            true
        };

        let mut push_hashtag = false;
        let mut prelude = String::new();
        let mut previous_was_card = false;
        for call_node in tree.root_node().children(&mut cursor) {
            if call_node.kind() == "call" {
                if !check_isnt_let(&call_node) {
                    continue;
                }
                if let Some(item) =
                    get_function_from_call_node(source, call_node, CARD_FUNCTION_NAME)
                {
                    push_hashtag = false;
                    previous_was_card = true;
                    match handle_card_node(item, &call_node) {
                        Err(e) => {
                            let id = get_tagged_argument_value(source, &call_node, "id")
                                .map(|s| s.trim_matches(VALUE_TRIM_CHARS).to_string())
                                .unwrap_or("unknown_id".to_string());
                            output.send(OutputMessage::ParsingError(if !cfg.dry_run {
                                format!(
                                    "Warning: Failed to parse {CARD_FUNCTION_NAME} (id: {id}): {}",
                                    e
                                )
                            } else {
                                format!(
                                    "Failed to parse {CARD_FUNCTION_NAME} (id: {id}): {e}\n{}",
                                    call_node.utf8_text(source).unwrap_or("unknown_content")
                                )
                            }));
                        }
                        Ok(mut c) => {
                            c.prelude_range = Some(0..prelude.len());
                            cards.push(c);
                            // println!("Card: {:?}", c);
                        }
                    }
                }
            } else {
                if call_node.kind() == "let" {
                    if let Some(func_name) = call_node
                        .children(&mut call_node.walk())
                        .find(|s| s.kind() == "call")
                        .map(|n| n.child_by_field_name("item"))
                        .flatten()
                        .filter(|n| n.kind() == "identifier" || n.kind() == "ident")
                        .map(|n| n.utf8_text(source).ok())
                        .flatten()
                    {
                        if func_name == CARD_FUNCTION_NAME {
                            push_hashtag = false;
                            continue;
                        }
                    }
                } else if call_node.kind() == "import" {
                    if let Some(p) = call_node
                        .child_by_field_name("import")
                        .map(|n| n.utf8_text(source).ok())
                        .flatten()
                        .map(|s| s.trim_matches(VALUE_TRIM_CHARS).to_string())
                    {
                        if p.ends_with("ankiconf.typ") {
                            push_hashtag = false;
                            continue;
                        }
                    }
                } else if call_node.kind() == "show" {
                    if let Some(p) = call_node
                        .child_by_field_name("value")
                        .map(|n| n.utf8_text(source).ok())
                        .flatten()
                        .map(|s| s.trim_matches(VALUE_TRIM_CHARS).to_string())
                    {
                        if p.contains("conf(doc)") {
                            push_hashtag = false;
                            continue;
                        }
                    }
                }

                if push_hashtag {
                    prelude.push_str("#");
                    push_hashtag = false;
                }

                match call_node.kind() {
                    "#" => {
                        push_hashtag = true;
                    }
                    "parbreak" => {
                        if !previous_was_card {
                            prelude.push_str("\n");
                        }
                    }
                    "end" => {
                        if !previous_was_card {
                            prelude.push_str("\n");
                        }
                    }
                    "comment" => {
                        previous_was_card = false;
                    }
                    _ => {
                        if let Some(s) = call_node.utf8_text(source).ok() {
                            prelude.push_str(s);
                        }
                        previous_was_card = false;
                    }
                }
            }
        }

        // println!("Function calls found: {:?}", calls);

        // if !calls.is_empty() {
        //     let first_call = calls[0];
        //     println!(
        //         "First call from {} to {}: {}",
        //         first_call.0,
        //         first_call.1,
        //         &content[first_call.0..first_call.1]
        //     );
        // }

        cards
            .into_iter()
            .map(|c| {
                let mut card_str = String::new();
                if let Some(prelude_range) = &c.prelude_range {
                    card_str.push_str(&prelude[prelude_range.start..prelude_range.end]);
                    card_str.push_str("\n");
                }
                card_str.push_str(&content[c.byte_range.0..c.byte_range.1]);
                card_str
            })
            .collect()
    }
}

#[cfg(not(feature = "tree-sitter"))]
mod parse_card_fallback {
    use std::ops::Range;

    use super::*;

    const CARD_TYPES: [&str; 2] = ["#card(", "#custom-card("];
    const PRELUDE_STARTS: [&str; 2] = ["START", "start"];

    /// Checks if the `content string has a line or block comment starting at byte index `i`
    /// If it does, this returns a range indicating the inside of the comment, and the byte index
    /// of the first character after the end of the comment (after the linefeed for line comments)
    fn parse_comment(content: &str, i: usize) -> Option<(Range<usize>, usize)> {
        let len = content.len();
        if content[i..].starts_with("//") {
            // Line comment
            // Get the index of the character after the comment's end
            let end = content[i..].find('\n').map(|end| end + i).unwrap_or(len);
            let next = content.ceil_char_boundary(end + 1); // `ceil_char_boundary` returns `len` if its argument overflows `len`

            Some((i + 2..end, next))
        } else if content[i..].starts_with("/*") {
            // Block comment
            let end = content[i + 2..]
                .find("*/")
                .map(|end| end + i + 2)
                .unwrap_or(len);
            let next = content.ceil_char_boundary(end + 2); // skip */
            Some(((i + 2..end), next))
        } else {
            None
        }
    }

    pub fn parse_cards_string(
        content: &str,
        _: &Arc<impl OutputManager + 'static>,
        no_prelude: bool,
    ) -> Vec<String> {
        let mut results: Vec<String> = Vec::new();

        let mut inside_card = false;
        let mut balance: i32 = 0;
        let mut current_card = String::new();
        let mut i: usize = 0;
        let len = content.len();

        let mut current_prelude = String::new();
        let mut prelude_started = false;

        while i < len {
            if let Some((comment_inside, next)) = parse_comment(content, i) {
                if !no_prelude && !inside_card && !prelude_started {
                    let trimmed = content[comment_inside].trim_start();
                    if PRELUDE_STARTS
                        .iter()
                        .any(|start| trimmed.starts_with(start))
                    {
                        prelude_started = true;
                    }
                }
                i = next;
                continue;
            }

            if !inside_card && CARD_TYPES.iter().any(|ct| content[i..].starts_with(ct)) {
                inside_card = true;
                for ct in &CARD_TYPES {
                    if content[i..].starts_with(ct) {
                        balance = 1;
                        current_card.clear();
                        current_card.push_str(ct);
                        i += ct.len();
                        break;
                    }
                }
                continue;
            }

            if inside_card {
                let ch = content[i..].chars().next().unwrap();
                current_card.push(ch);
                if ch == '(' {
                    balance += 1;
                } else if ch == ')' {
                    balance -= 1;
                }
                i += ch.len_utf8();

                if balance == 0 {
                    results.push(format!(
                        "{}\n{}",
                        current_prelude.trim(),
                        current_card.trim()
                    ));
                    inside_card = false;
                    current_card.clear();
                }
                continue;
            }

            // Not inside a card and prelude only tracked after marker found
            let ch = content[i..].chars().next().unwrap();
            if prelude_started {
                if ch == '\n' && current_prelude.ends_with('\n') {
                    // skip duplicate new line``
                } else {
                    current_prelude.push(ch);
                }
            }
            i += ch.len_utf8();
        }

        results
    }
}

#[cfg(not(feature = "tree-sitter"))]
pub use parse_card_fallback::parse_cards_string;
#[cfg(feature = "tree-sitter")]
pub use parse_card_tree_sitter::parse_cards_string;

pub fn parse_cards_from_file_content(
    filepath: &PathBuf,
    content: String,
    cards_cache_manager: &mut CardsCacheManager,
    output: Arc<impl OutputManager + 'static>,
    i: &mut i64,
    deck_names: &mut HashSet<String>,
    cards: &mut Vec<CardInfo>,
) -> Result<TypFileStats, String> {
    let cfg = config::get();

    let mut file = TypFileStats::new(filepath.clone());

    let start = std::time::Instant::now();
    let parsed = parse_cards_string(&content, &output, false);
    let _duration = start.elapsed();

    if parsed.is_empty() {
        return Ok(file);
    }

    for card_str in parsed.into_iter() {
        if is_card_empty(&card_str) {
            file.empty_cards += 1;
            continue;
        }

        match CardInfo::from_string(*i, &card_str, filepath.clone()) {
            Ok(card_info) => {
                if cfg.is_deck_excluded(card_info.deck_name.as_str()) {
                    file.skipped_cards += 1;
                    continue;
                }
                cards_cache_manager.add_card_hash(
                    &card_info.deck_name,
                    &card_info.card_id,
                    &card_info.content_hash,
                );
                deck_names.insert(card_info.deck_name.clone());
                cards.push(card_info);
                *i += 1;
                file.total_cards += 1;
            }
            Err(_) => {
                output.send(OutputMessage::ParsingError(format!(
                    "Warning: Failed to parse card in file {:?}",
                    filepath.to_string_lossy()
                )));
            }
        }
    }
    Ok(file)
}