use std::fs;
use std::path::Path;
use std::sync::Mutex;
mod cache;
pub mod error;
mod incremental;
mod intermediate;
pub mod lsp;
mod macros;
mod math;
mod math_formatter;
mod output;
mod packages;
mod parser;
mod plugins;
mod streaming;
mod table;
pub(crate) mod utils;
mod watch;
pub use cache::{CacheConfig, CacheStats, DocumentCache};
pub use error::{LatexError, Position};
pub use incremental::IncrementalCompiler;
pub use intermediate::{IntermediateMeta, sibling_artifact, write_intermediates};
pub use lsp::{
CompletionKind, Severity, SymbolKind, TexCompletion, TexDiagnostic, TexPosition, TexRange,
TexSymbol, analyze_diagnostics, command_completions, completions_at, document_symbols,
hover_at,
};
pub use macros::expand_document;
pub use math_formatter::MathFormatter;
pub use output::{DocumentMeta, OutputFormat, PdfBackend, render_elements, render_elements_in_dir};
pub use packages::{PackageFetcher, PackageRequest};
pub use parser::{TexElement, TexParser};
pub use streaming::{ConsoleReporter, NoOpReporter, ProgressReporter, StreamingConverter};
pub use watch::{watch_batch, watch_single};
#[cfg(feature = "lsp")]
pub fn run_lsp_server() -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
lsp::run_stdio_server()
}
#[derive(Debug, Clone)]
pub struct ConversionOptions {
pub format: OutputFormat,
pub fetch_packages: bool,
pub package_cache: Option<std::path::PathBuf>,
pub keep_intermediate: bool,
}
impl Default for ConversionOptions {
fn default() -> Self {
Self {
format: OutputFormat::Pdf,
fetch_packages: false,
package_cache: None,
keep_intermediate: false,
}
}
}
impl ConversionOptions {
pub fn with_format(mut self, format: OutputFormat) -> Self {
self.format = format;
self
}
pub fn with_fetch_packages(mut self, fetch: bool) -> Self {
self.fetch_packages = fetch;
self
}
pub fn with_keep_intermediate(mut self, keep: bool) -> Self {
self.keep_intermediate = keep;
self
}
}
fn default_package_cache() -> std::path::PathBuf {
std::path::PathBuf::from(".rtex/cache")
}
pub trait TexConverter {
fn convert(&self, input: &Path, output: &Path) -> Result<(), LatexError>;
}
pub struct NativeTexConverter {
cache: Option<Mutex<DocumentCache>>,
options: ConversionOptions,
}
impl NativeTexConverter {
pub fn new() -> Self {
Self {
cache: None,
options: ConversionOptions::default(),
}
}
pub fn with_options(options: ConversionOptions) -> Self {
Self {
cache: None,
options,
}
}
pub fn with_cache() -> Self {
Self {
cache: Some(Mutex::new(DocumentCache::new())),
options: ConversionOptions::default(),
}
}
fn parse_content(&self, content: &str, base_dir: Option<&Path>) -> Vec<parser::TexElement> {
if let Some(ref cache) = self.cache {
let mut c = cache.lock().unwrap_or_else(|e| e.into_inner());
if let Some(els) = c.get_parsed(content) {
return els;
}
drop(c);
let els = self.parse_fresh(content, base_dir);
cache.lock().unwrap_or_else(|e| e.into_inner()).put_parsed(content, els.clone());
els
} else {
self.parse_fresh(content, base_dir)
}
}
fn parse_fresh(&self, content: &str, base_dir: Option<&Path>) -> Vec<parser::TexElement> {
let mut search_paths = Vec::new();
if self.options.fetch_packages {
let cache_dir = self
.options
.package_cache
.clone()
.unwrap_or_else(default_package_cache);
let fetcher = PackageFetcher::new(cache_dir);
let _ = fetcher.prepare_source(content);
search_paths = fetcher.search_paths();
}
let mut parser = TexParser::new(content.to_string());
if let Some(dir) = base_dir {
parser = parser.with_base_dir(dir);
}
if !search_paths.is_empty() {
parser = parser.with_search_paths(search_paths);
}
parser.parse()
}
pub fn convert_string(&self, tex: &str) -> Result<Vec<u8>, LatexError> {
self.convert_string_in_dir(tex, None, None)
}
pub fn convert_string_in_dir(
&self,
tex: &str,
base_dir: Option<&Path>,
output: Option<&Path>,
) -> Result<Vec<u8>, LatexError> {
let elements = self.parse_content(tex, base_dir);
let bytes = render_elements_in_dir(elements.clone(), self.options.format, base_dir)?;
if self.options.keep_intermediate {
if let Some(out) = output {
let expanded = expand_document(tex);
write_intermediates(out, &expanded, &elements, self.options.format)?;
}
}
Ok(bytes)
}
pub fn convert_file(input: &Path, output: &Path) -> Result<(), LatexError> {
let converter = Self::new();
converter.convert(input, output)
}
#[cfg(test)]
pub fn cache_stats(&self) -> Option<CacheStats> {
self.cache
.as_ref()
.map(|c| c.lock().unwrap_or_else(|e| e.into_inner()).stats().clone())
}
}
impl Default for NativeTexConverter {
fn default() -> Self {
Self::new()
}
}
impl TexConverter for NativeTexConverter {
fn convert(&self, input: &Path, output: &Path) -> Result<(), LatexError> {
if !input.exists() {
return Err(LatexError::InvalidPath);
}
let content = fs::read_to_string(input)?;
let base_dir = input.parent();
let bytes = self.convert_string_in_dir(&content, base_dir, Some(output))?;
fs::write(output, bytes).map_err(|source| LatexError::IoError {
path: output.to_path_buf(),
source,
})?;
Ok(())
}
}
pub fn convert_tex_string_to_pdf_bytes(tex: &str) -> Result<Vec<u8>, LatexError> {
NativeTexConverter::new().convert_string(tex)
}
pub fn convert_tex_string(tex: &str, format: OutputFormat) -> Result<Vec<u8>, LatexError> {
NativeTexConverter::with_options(ConversionOptions::default().with_format(format))
.convert_string(tex)
}
pub fn convert_tex_file(
input: &Path,
output: &Path,
options: &ConversionOptions,
) -> Result<(), LatexError> {
NativeTexConverter::with_options(options.clone()).convert(input, output)
}
pub fn convert_tex_to_pdf(input: &Path, output: &Path) -> Result<(), LatexError> {
let converter = NativeTexConverter::new();
converter.convert(input, output)
}
#[cfg(feature = "wasm")]
mod wasm;
#[cfg(test)]
mod tests;
#[cfg(test)]
mod example_tests;