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
|
use std::{
path::Path,
process::{Command, Stdio},
};
use base_db::{Document, LatexIndentConfig, Workspace};
use distro::Language;
use lsp_types::TextEdit;
use rowan::{TextLen, TextRange};
use tempfile::tempdir;
use crate::util::line_index_ext::LineIndexExt;
pub fn format_with_latexindent(
workspace: &Workspace,
document: &Document,
) -> Option<Vec<TextEdit>> {
let config = workspace.config();
let target_dir = tempdir().ok()?;
let source_dir = workspace.current_dir(&document.dir).to_file_path().ok()?;
let target_file = target_dir
.path()
.join(if document.language == Language::Bib {
"file.bib"
} else {
"file.tex"
});
std::fs::write(&target_file, &document.text).ok()?;
let args = build_arguments(&config.formatting.latex_indent, &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.text;
let new_text = String::from_utf8_lossy(&output.stdout).into_owned();
if new_text.is_empty() {
None
} else {
let line_index = &document.line_index;
Some(vec![TextEdit {
range: line_index.line_col_lsp_range(TextRange::new(0.into(), old_text.text_len())),
new_text,
}])
}
}
fn build_arguments(config: &LatexIndentConfig, target_file: &Path) -> Vec<String> {
let mut args = Vec::new();
args.push(match &config.local {
Some(yaml_file) => format!("--local={yaml_file}"),
None => "--local".to_string(),
});
if config.modify_line_breaks {
args.push("--modifylinebreaks".to_string());
}
args.push(target_file.display().to_string());
args
}
|