Use a Unicode default with project-level LaTeX compatibility
This commit is contained in:
1 parent
38a2a4a958
commit
81ac3ae321
11 files changed
+741
-126
No files matched your search
+216
-7
@@ -1,7 +1,8 @@
|
||||
use std::{
|
||||
fs,
|
||||
io::{Read, Write},
|
||||
io::{self, Read, Write},
|
||||
path::{Component, Path, PathBuf},
|
||||
sync::atomic::{AtomicU64, Ordering},
|
||||
time::{SystemTime, UNIX_EPOCH},
|
||||
};
|
||||
|
||||
@@ -19,12 +20,32 @@ pub(super) struct ProjectFile {
|
||||
pub(super) size: u64,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, serde::Deserialize, serde::Serialize)]
|
||||
#[serde(rename_all = "lowercase")]
|
||||
pub(super) enum CompileMode {
|
||||
#[default]
|
||||
Auto,
|
||||
Unicode,
|
||||
PdfLatex,
|
||||
}
|
||||
|
||||
impl CompileMode {
|
||||
fn as_str(self) -> &'static str {
|
||||
match self {
|
||||
Self::Auto => "auto",
|
||||
Self::Unicode => "unicode",
|
||||
Self::PdfLatex => "pdflatex",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(serde::Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub(super) struct ProjectInfo {
|
||||
pub(super) id: String,
|
||||
pub(super) name: String,
|
||||
pub(super) main_file: String,
|
||||
pub(super) compile_mode: CompileMode,
|
||||
pub(super) created_at: u64,
|
||||
pub(super) updated_at: u64,
|
||||
pub(super) files: Vec<ProjectFile>,
|
||||
@@ -33,6 +54,7 @@ pub(super) struct ProjectInfo {
|
||||
struct Meta {
|
||||
name: String,
|
||||
main_file: String,
|
||||
compile_mode: CompileMode,
|
||||
created_at: u64,
|
||||
updated_at: u64,
|
||||
}
|
||||
@@ -74,6 +96,7 @@ impl ProjectStore {
|
||||
let mut meta = self.load_meta(id).unwrap_or_else(|| Meta {
|
||||
name: id.to_string(),
|
||||
main_file: String::new(),
|
||||
compile_mode: CompileMode::Auto,
|
||||
created_at: now_secs(),
|
||||
updated_at: now_secs(),
|
||||
});
|
||||
@@ -82,6 +105,7 @@ impl ProjectStore {
|
||||
id: id.to_string(),
|
||||
name: meta.name,
|
||||
main_file: meta.main_file,
|
||||
compile_mode: meta.compile_mode,
|
||||
created_at: meta.created_at,
|
||||
updated_at: meta.updated_at,
|
||||
files,
|
||||
@@ -89,12 +113,29 @@ impl ProjectStore {
|
||||
}
|
||||
|
||||
pub(super) fn create_empty(&self, name: &str) -> Result<ProjectInfo, String> {
|
||||
self.create_empty_with_mode(name, CompileMode::Auto)
|
||||
}
|
||||
|
||||
pub(super) fn create_empty_with_mode(
|
||||
&self,
|
||||
name: &str,
|
||||
compile_mode: CompileMode,
|
||||
) -> Result<ProjectInfo, String> {
|
||||
let name = clean_name(name);
|
||||
let id = self.unique_id(&slug(&name));
|
||||
let dir = self.root.join(&id);
|
||||
fs::create_dir_all(&dir).map_err(|error| format!("could not create project: {error}"))?;
|
||||
let source =
|
||||
"\\documentclass{article}\n\\begin{document}\nHello, world.\n\\end{document}\n";
|
||||
let source = if compile_mode == CompileMode::Unicode {
|
||||
concat!(
|
||||
"\\documentclass{article}\n",
|
||||
"\\usepackage[UTF8,scheme=plain,fontset=fandol]{ctex}\n",
|
||||
"\\begin{document}\n",
|
||||
"你好,世界。Hello, world.\n",
|
||||
"\\end{document}\n",
|
||||
)
|
||||
} else {
|
||||
"\\documentclass{article}\n\\begin{document}\nHello, world.\n\\end{document}\n"
|
||||
};
|
||||
fs::write(dir.join("main.tex"), source)
|
||||
.map_err(|error| format!("could not write main.tex: {error}"))?;
|
||||
self.save_meta(
|
||||
@@ -102,6 +143,7 @@ impl ProjectStore {
|
||||
&Meta {
|
||||
name,
|
||||
main_file: "main.tex".to_string(),
|
||||
compile_mode,
|
||||
created_at: now_secs(),
|
||||
updated_at: now_secs(),
|
||||
},
|
||||
@@ -173,6 +215,7 @@ impl ProjectStore {
|
||||
&Meta {
|
||||
name,
|
||||
main_file,
|
||||
compile_mode: CompileMode::Auto,
|
||||
created_at: now_secs(),
|
||||
updated_at: now_secs(),
|
||||
},
|
||||
@@ -180,6 +223,29 @@ impl ProjectStore {
|
||||
self.info(&id)
|
||||
}
|
||||
|
||||
pub(super) fn set_compile_mode(
|
||||
&self,
|
||||
id: &str,
|
||||
mode: CompileMode,
|
||||
) -> Result<ProjectInfo, String> {
|
||||
let mut info = self.info(id)?;
|
||||
if info.compile_mode != mode {
|
||||
info.compile_mode = mode;
|
||||
info.updated_at = now_secs();
|
||||
self.save_meta(
|
||||
id,
|
||||
&Meta {
|
||||
name: info.name.clone(),
|
||||
main_file: info.main_file.clone(),
|
||||
compile_mode: mode,
|
||||
created_at: info.created_at,
|
||||
updated_at: info.updated_at,
|
||||
},
|
||||
)?;
|
||||
}
|
||||
Ok(info)
|
||||
}
|
||||
|
||||
pub(super) fn delete(&self, id: &str) -> Result<(), String> {
|
||||
let dir = self.project_dir(id)?;
|
||||
if !dir.is_dir() {
|
||||
@@ -322,6 +388,7 @@ impl ProjectStore {
|
||||
&Meta {
|
||||
name: stem.to_string(),
|
||||
main_file: file_name.to_string(),
|
||||
compile_mode: CompileMode::Auto,
|
||||
created_at: now_secs(),
|
||||
updated_at: now_secs(),
|
||||
},
|
||||
@@ -411,6 +478,7 @@ impl ProjectStore {
|
||||
let text = fs::read_to_string(self.meta_path(id)).ok()?;
|
||||
let mut name = String::new();
|
||||
let mut main_file = String::new();
|
||||
let mut compile_mode = CompileMode::Auto;
|
||||
let mut created_at = 0;
|
||||
let mut updated_at = 0;
|
||||
for line in text.lines() {
|
||||
@@ -420,6 +488,13 @@ impl ProjectStore {
|
||||
match key {
|
||||
"name" => name = value.to_string(),
|
||||
"main" => main_file = value.to_string(),
|
||||
"compile_mode" => {
|
||||
compile_mode = match value {
|
||||
"unicode" => CompileMode::Unicode,
|
||||
"pdflatex" => CompileMode::PdfLatex,
|
||||
_ => CompileMode::Auto,
|
||||
};
|
||||
}
|
||||
"created" => created_at = value.parse().unwrap_or(0),
|
||||
"updated" => updated_at = value.parse().unwrap_or(0),
|
||||
_ => {}
|
||||
@@ -432,6 +507,7 @@ impl ProjectStore {
|
||||
name
|
||||
},
|
||||
main_file,
|
||||
compile_mode,
|
||||
created_at,
|
||||
updated_at,
|
||||
})
|
||||
@@ -439,20 +515,48 @@ impl ProjectStore {
|
||||
|
||||
fn save_meta(&self, id: &str, meta: &Meta) -> Result<(), String> {
|
||||
let text = format!(
|
||||
"name={}\nmain={}\ncreated={}\nupdated={}\n",
|
||||
"name={}\nmain={}\ncreated={}\nupdated={}\ncompile_mode={}\n",
|
||||
meta.name.replace(['\n', '\r'], " "),
|
||||
meta.main_file,
|
||||
meta.created_at,
|
||||
meta.updated_at
|
||||
meta.updated_at,
|
||||
meta.compile_mode.as_str()
|
||||
);
|
||||
fs::write(self.meta_path(id), text)
|
||||
.map_err(|error| format!("could not save project metadata: {error}"))
|
||||
let path = self.meta_path(id);
|
||||
let replace = (|| -> io::Result<()> {
|
||||
static NEXT: AtomicU64 = AtomicU64::new(0);
|
||||
let (mut file, temporary) = loop {
|
||||
let temporary = path.with_extension(format!(
|
||||
"{}.{}.pending",
|
||||
std::process::id(),
|
||||
NEXT.fetch_add(1, Ordering::Relaxed),
|
||||
));
|
||||
match fs::OpenOptions::new()
|
||||
.write(true)
|
||||
.create_new(true)
|
||||
.open(&temporary)
|
||||
{
|
||||
Ok(file) => break (file, temporary),
|
||||
Err(error) if error.kind() == io::ErrorKind::AlreadyExists => continue,
|
||||
Err(error) => return Err(error),
|
||||
}
|
||||
};
|
||||
let written = file.write_all(text.as_bytes());
|
||||
drop(file);
|
||||
let result = written.and_then(|()| fs::rename(&temporary, path));
|
||||
if result.is_err() {
|
||||
let _ = fs::remove_file(temporary);
|
||||
}
|
||||
result
|
||||
})();
|
||||
replace.map_err(|error| format!("could not save project metadata: {error}"))
|
||||
}
|
||||
|
||||
fn touch(&self, id: &str) -> Result<(), String> {
|
||||
let mut meta = self.load_meta(id).unwrap_or_else(|| Meta {
|
||||
name: id.to_string(),
|
||||
main_file: String::new(),
|
||||
compile_mode: CompileMode::Auto,
|
||||
created_at: now_secs(),
|
||||
updated_at: now_secs(),
|
||||
});
|
||||
@@ -566,6 +670,111 @@ fn entry_path(entry: &str) -> Option<String> {
|
||||
Some(trimmed.to_string())
|
||||
}
|
||||
|
||||
/// Detect the engine from editor directives and LaTeX package declarations.
|
||||
/// Ambiguous documents retain the pdfLaTeX-compatible mode.
|
||||
pub(super) fn resolve_compile_mode(source: &str) -> CompileMode {
|
||||
let source = source.trim_start_matches('\u{feff}');
|
||||
for line in source.lines().map(str::trim) {
|
||||
if line.is_empty() {
|
||||
continue;
|
||||
}
|
||||
let Some(comment) = line.strip_prefix('%') else {
|
||||
break;
|
||||
};
|
||||
let Some((key, program)) = comment.split_once('=') else {
|
||||
continue;
|
||||
};
|
||||
let mut words = key.split_whitespace();
|
||||
if !words
|
||||
.next()
|
||||
.is_some_and(|word| word.eq_ignore_ascii_case("!tex"))
|
||||
|| !words.next().is_some_and(|word| {
|
||||
word.eq_ignore_ascii_case("program") || word.eq_ignore_ascii_case("ts-program")
|
||||
})
|
||||
|| words.next().is_some()
|
||||
{
|
||||
continue;
|
||||
}
|
||||
match program.split_whitespace().next() {
|
||||
Some(program) if program.eq_ignore_ascii_case("xelatex") => {
|
||||
return CompileMode::Unicode;
|
||||
}
|
||||
Some(program) if program.eq_ignore_ascii_case("pdflatex") => {
|
||||
return CompileMode::PdfLatex;
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
let mut uncommented = String::new();
|
||||
for line in source.lines() {
|
||||
let mut escaped = false;
|
||||
let end = line
|
||||
.char_indices()
|
||||
.find_map(|(index, ch)| {
|
||||
let comment = ch == '%' && !escaped;
|
||||
escaped = ch == '\\' && !escaped;
|
||||
comment.then_some(index)
|
||||
})
|
||||
.unwrap_or(line.len());
|
||||
uncommented.push_str(&line[..end]);
|
||||
uncommented.push('\n');
|
||||
}
|
||||
let mut remaining = uncommented.as_str();
|
||||
while let Some((_, command)) = remaining.split_once('\\') {
|
||||
let end = command
|
||||
.find(|ch: char| !ch.is_ascii_alphabetic())
|
||||
.unwrap_or(command.len());
|
||||
let (name, after) = command.split_at(end);
|
||||
if name.is_empty() {
|
||||
let mut chars = after.chars();
|
||||
chars.next();
|
||||
remaining = chars.as_str();
|
||||
continue;
|
||||
}
|
||||
remaining = after;
|
||||
let argument = match name {
|
||||
"begin"
|
||||
| "documentclass"
|
||||
| "usepackage"
|
||||
| "RequirePackage"
|
||||
| "RequirePackageWithOptions" => tex_command_argument(after),
|
||||
_ => None,
|
||||
};
|
||||
let Some(argument) = argument else {
|
||||
continue;
|
||||
};
|
||||
match name {
|
||||
"begin" if argument == "document" => break,
|
||||
"documentclass"
|
||||
if matches!(argument, "ctexart" | "ctexrep" | "ctexbook" | "ctexbeamer") =>
|
||||
{
|
||||
return CompileMode::Unicode;
|
||||
}
|
||||
"usepackage" | "RequirePackage" | "RequirePackageWithOptions"
|
||||
if argument.split(',').any(|package| {
|
||||
matches!(
|
||||
package.trim(),
|
||||
"ctex" | "xeCJK" | "fontspec" | "unicode-math"
|
||||
)
|
||||
}) =>
|
||||
{
|
||||
return CompileMode::Unicode;
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
CompileMode::PdfLatex
|
||||
}
|
||||
|
||||
fn tex_command_argument(source: &str) -> Option<&str> {
|
||||
let mut source = source.trim_start();
|
||||
if let Some(options) = source.strip_prefix('[') {
|
||||
source = options.split_once(']')?.1.trim_start();
|
||||
}
|
||||
Some(source.strip_prefix('{')?.split_once('}')?.0.trim())
|
||||
}
|
||||
|
||||
fn detect_main(directory: &Path, names: &[String]) -> Option<String> {
|
||||
for candidate in ["main.tex", "document.tex", "paper.tex", "article.tex"] {
|
||||
if let Some(name) = names.iter().find(|name| name.as_str() == candidate) {
|
||||
|
||||
Reference in new issue
Block a user