summaryrefslogtreecommitdiff
path: root/support/texlab/src/features/formatting/latexindent.rs
blob: 3dab10c923239078778cec074043fbbcc52dc00f (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
use std::{
    path::Path,
    process::{Command, Stdio},
};

use lsp_types::TextEdit;
use rowan::{TextLen, TextRange};
use tempfile::tempdir;

use crate::{
    db::{Document, Language, Workspace},
    util::line_index_ext::LineIndexExt,
    Db, LatexindentOptions,
};

pub fn format_with_latexindent(db: &dyn Db, document: Document) -> Option<Vec<TextEdit>> {
    let workspace = Workspace::get(db);
    let options = workspace.options(db);
    let target_dir = tempdir().ok()?;
    let source_dir = workspace
        .working_dir(db, document.directory(db))
        .path(db)
        .as_deref()?;

    let target_file = target_dir
        .path()
        .join(if document.language(db) == Language::Bib {
            "file.bib"
        } else {
            "file.tex"
        });
    std::fs::write(&target_file, document.contents(db).text(db)).ok()?;

    let args = build_arguments(&options.latexindent, &target_file);

    log::debug!(
        "Running latexindent in folder \"{}\" with args: {:?}",
        source_dir.display(),
        args,
    );

    let output = Command::new("latexindent")
        .args(&args)
        .stdin(Stdio::null())
        .stdout(Stdio::piped())
        .stderr(Stdio::null())
        .current_dir(source_dir)
        .output()
        .ok()?;

    let old_text = document.contents(db).text(db);
    let new_text = String::from_utf8_lossy(&output.stdout).into_owned();
    if new_text.is_empty() {
        None
    } else {
        let line_index = document.contents(db).line_index(db);
        Some(vec![TextEdit {
            range: line_index.line_col_lsp_range(TextRange::new(0.into(), old_text.text_len())),
            new_text,
        }])
    }
}

fn build_arguments(options: &LatexindentOptions, target_file: &Path) -> Vec<String> {
    let mut args = Vec::new();

    args.push(match &options.local {
        Some(yaml_file) => format!("--local={yaml_file}"),
        None => "--local".to_string(),
    });

    if options.modify_line_breaks {
        args.push("--modifylinebreaks".to_string());
    }

    args.push(target_file.display().to_string());
    args
}