aboutsummaryrefslogtreecommitdiff
path: root/src/bibiman/citekeys/citekey_utils.rs
blob: 2de3600cd76cabb6fedf6fd0e01a3939847fa46f (plain)
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
// bibiman - a TUI for managing BibLaTeX databases
// Copyright (C) 2025  lukeflo
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program.  If not, see <https://www.gnu.org/licenses/>.
/////

use biblatex::{ChunksExt, Entry, Type};
use indoc::formatdoc;
use owo_colors::{
    OwoColorize,
    colors::{BrightBlue, Green, White},
};

use crate::bibiman::{citekeys::CitekeyCase, sanitize::sanitize_single_string_fully};

pub(super) const SKIPPED_ENTRIES: [&str; 2] = ["set", "xdata"];

pub(super) fn formatting_help() {
    let help = vec![
        formatdoc!(
            "{} {}\n",
            env!("CARGO_PKG_NAME").fg::<Green>().bold(),
            env!("CARGO_PKG_VERSION")
        ),
        formatdoc!("{}", "USAGE".bold()),
        formatdoc!(
            "\t{} {} {} {} {}\n",
            env!("CARGO_PKG_NAME").fg::<White>().bold(),
            "format-citekeys".bold(),
            "[OPTIONS]".bold(),
            "--source=<SOURCE>".bold(),
            "[--output=<TARGET>]".bold()
        ),
        formatdoc!(
            "
                \tThis help describes the CLI usage for the citekey formatting
                \tfunctionality of bibiman. The definition of patterns how the
                \tcitekeys should be formatted must be set in the config file.
                \tFor further informations how to use this patterns etc. see:
                \t{}
            ",
            "https://codeberg.org/lukeflo/bibiman/src/branch/main/CITEKEYS.md"
                .italic()
                .fg::<BrightBlue>()
        ),
        formatdoc!("{}", "OPTIONS".bold()),
        formatdoc!(
            "
                \t{}
                \tShow this help and exit
            ",
            "-h, --help".fg::<White>().bold()
        ),
        formatdoc!(
            "
                \t{}
                \tDon't apply any changes to the named files. Instead print all
                \told citekeys and the formatted strings that would have been
                \tapplied in the format: {} => {}
            ",
            "-d, --dry-run".fg::<White>().bold(),
            "old_key".italic(),
            "new_key".bold()
        ),
        formatdoc! {"
                \t{}
                \tThe bibfile for which the citekey formatting should be processed.
                \tTakes a path as argument.
            ", "-s, -f, --source=<PATH>, --file=<PATH>".fg::<White>().bold()},
        formatdoc!(
            "
                \t{}
                \tThe bibfile to which the updated content should be written.
                \tTakes a path as argument. If the file doesn't exist, it will be
                \tcreated.
                \tIf the argument isn't used, the original file will be {}!
            ",
            "-t, -o, --target=<PATH>, --output=<PATH>"
                .fg::<White>()
                .bold(),
            "overwritten".italic(),
        ),
        formatdoc!(
            "
                \t{}
                \tWhen this option is set, bibiman will also rename all PDFs and 
                \tnotefiles following the bibiman citekey-basename scheme at the 
                \tlocations set in the config file. This option can break file paths. 
                \tTry with {} first!
            ",
            "-u, --update-attachments".fg::<White>().bold(),
            "--dry-run".bold()
        ),
    ];
    let help = help.join("\n");
    println!("{}", help);
}

/// Build the citekey from the patterns defined in the config file
pub(super) fn build_citekey(
    entry: &Entry,
    pattern_fields: &[String],
    case: Option<&CitekeyCase>,
    ascii_only: bool,
    ignored_chars: &[char],
    ignored_words: &[String],
) -> String {
    // mut string the citekey is built from
    let mut new_citekey = String::new();

    // trailing delimiter of previous field
    let mut trailing_delimiter: Option<&str> = None;

    // loop over pattern fields process them
    'field_loop: for pattern in pattern_fields.iter() {
        // parse single values from pattern field
        let (field_name, max_words, max_chars, inner_delimiter, cur_trailing_delimiter) =
            split_formatting_pat(pattern);

        // built the part of the citekey from the current pattern field
        let formatted_field_str = {
            let mut formatted_str = String::new();

            // preformat the field depending on biblatex value
            let field = preformat_field(field_name, entry);

            // split at whitespaces, count fields and set counter for processed
            // splits
            let split_field = field.split_whitespace();
            let mut words_passed = 0;
            let field_count = field.split_whitespace().count();

            // If there is a trailing delimiter from the previous field, push it
            if let Some(del) = trailing_delimiter {
                formatted_str = del.to_string();
            };

            // If the current field isn't empty, set trailing delimiter for
            // upcoming loop repitition. If it's empty, start next run of loop
            // directly
            if !field.is_empty() {
                trailing_delimiter = cur_trailing_delimiter;
            } else {
                continue 'field_loop;
            }

            // loop over single parts of current field and add correct delimiter
            // process the single slices and add correct delimiter
            'word_loop: for (idx, field_slice) in split_field.enumerate() {
                // if the current slice is a common word from the ignore list,
                // skip it.
                if ignored_words.contains(&field_slice.to_lowercase()) {
                    continue;
                }

                // Create word slice char by char. We need to loop over chars
                // instead of a simple bytes index to also catch chars which
                // consist of more than one byte (äöüøæ etc...)
                let mut word_slice = String::new();
                let word_chars = field_slice.chars();
                let mut counter = 0;
                'char_loop: for mut c in word_chars {
                    // If camelcase is set, force first char of word to uppercase
                    if counter == 0 && case == Some(&CitekeyCase::Camel) {
                        c = c.to_ascii_uppercase()
                    }
                    if let Some(len) = max_chars
                        && counter >= len
                    {
                        break 'char_loop;
                    }
                    // if a word slice contains a special char, skip it
                    if ignored_chars.contains(&c) {
                        continue 'char_loop;
                    }
                    // if non-ascii chars should be mapped, check if needed and do it
                    if let Some(chars) = deunicode::deunicode_char(c)
                        && ascii_only
                    {
                        word_slice.push_str(chars);
                        counter += chars.len();
                    } else {
                        word_slice.push(c);
                        counter += 1;
                    }
                }
                // Don't count empty slices and don't add delimiter to those
                if !word_slice.is_empty() {
                    formatted_str = formatted_str + &word_slice;
                    words_passed += 1;
                    if max_words.is_some_and(|max| max == words_passed) || idx + 1 == field_count {
                        break 'word_loop;
                    } else {
                        formatted_str = formatted_str + inner_delimiter.unwrap_or("");
                    }
                } else {
                    continue 'word_loop;
                }
            }
            formatted_str
        };
        new_citekey = new_citekey + &formatted_field_str;
    }
    match case {
        Some(CitekeyCase::Lower) => new_citekey.to_lowercase(),
        Some(CitekeyCase::Upper) => new_citekey.to_uppercase(),
        // otherwise skip, since camelcase is processed in char loop
        _ => new_citekey,
    }
}

/// Preformat some fields which are very common to be used in citekeys
pub(super) fn preformat_field(field: &str, entry: &Entry) -> String {
    match field {
        // Sanitize all macro code from string
        "title" => {
            sanitize_single_string_fully(&entry.get_as::<String>(field).unwrap_or("".into()))
        }
        // Get author names. Fall back to editors before setting empty string
        "author" => {
            if let Ok(authors) = entry.author() {
                let mut last_names = String::new();
                for a in authors.iter() {
                    last_names = last_names + &a.name + " ";
                }
                last_names
            } else if let Ok(editors) = entry.editors() {
                let mut last_names = String::new();
                for editortypes in editors.iter() {
                    for e in editortypes.0.iter() {
                        last_names = last_names + &e.name + " ";
                    }
                }
                last_names
            } else {
                "".to_string()
            }
        }
        // Get year of date field, fallback to year field
        "year" => {
            if let Ok(date) = entry.date() {
                date.to_chunks().format_verbatim()[..4].to_string()
            } else {
                entry.get_as::<String>(field).unwrap_or("".into())
            }
        }
        // Sanitize all macro code from string
        "subtitle" => {
            sanitize_single_string_fully(&entry.get_as::<String>(field).unwrap_or("".into()))
        }
        "editor" => {
            if let Ok(editors) = entry.editors() {
                let mut last_names = String::new();
                for editortypes in editors.iter() {
                    for e in editortypes.0.iter() {
                        last_names = last_names + &e.name + " ";
                    }
                }
                last_names
            } else {
                "".to_string()
            }
        }
        "pubtype" | "entrytype" => entry.entry_type.to_string(),
        _ => entry.get_as::<String>(field).unwrap_or("".into()),
    }
}

/// Split a formatting pattern of kind
/// `<field>;<word count>;<char count>;<inside delimiter>;<trailing delimiter>`,
/// e.g.: `title;3;3;_;:` will give `("title", 3, 3, "_", ":")`
pub(super) fn split_formatting_pat(
    pattern: &str,
) -> (
    &str,
    Option<usize>,
    Option<usize>,
    Option<&str>,
    Option<&str>,
) {
    let mut splits = pattern.split(';');
    (
        splits
            .next()
            .expect("Need field value for formatting citekey"),
        if let Some(next) = splits.next()
            && next.len() > 0
        {
            next.parse::<usize>().ok()
        } else {
            None
        },
        if let Some(next) = splits.next()
            && next.len() > 0
        {
            next.parse::<usize>().ok()
        } else {
            None
        },
        splits.next(),
        splits.next(),
    )
}

#[cfg(test)]
mod test {
    use crate::bibiman::citekeys::citekey_utils::split_formatting_pat;

    #[test]
    fn split_citekey_pattern() {
        let pattern = "title;3;5;_;_";

        assert_eq!(
            split_formatting_pat(pattern),
            ("title", Some(3), Some(5), Some("_"), Some("_"))
        );

        let pattern = "year";

        assert_eq!(
            split_formatting_pat(pattern),
            ("year", None, None, None, None)
        );

        let pattern = "author;1;;;_";
        assert_eq!(
            split_formatting_pat(pattern),
            ("author", Some(1), None, Some(""), Some("_"))
        );
    }
}