Skip to content
This repository has been archived by the owner on Nov 5, 2024. It is now read-only.

Configuring the Output Directory #39

Open
wants to merge 7 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 5 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ parking_lot = "0.12.1"
regex = "1.7.2"
same-file = "1"
serde_json = "1.0.94"
home = "0.5"
siphasher = "0.3"
tokio = { version = "1.26.0", features = [
"macros",
Expand Down
22 changes: 22 additions & 0 deletions addons/vscode/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,28 @@
"Export PDFs when you save a file.",
"Export PDFs as you type in a file."
]
},
"typst-lsp.outputRoot": {
"title": "Output Directory Root",
"description": "The directory that your output directory path is relative to.",
"type": "string",
"default": "source",
"enum": [
"source",
"workspace",
"absolute"
],
"enumDescriptions": [
"The folder containing the source file",
"The VSCode workspace",
"Your home directory"
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Shouldn't this be "The root of the filesystem"?

Copy link
Author

@liamrosenfeld liamrosenfeld Mar 30, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

That would make sense. I was designing it with a Unix filesystem in mind where VSCode would only have permission to save into the home directory anyway. I guess that is misleading when calling it "Absolute". I can change it to absolute and ensure it can handle ~/.

]
},
"typst-lsp.outputPath": {
"title": "Output Directory Path",
"description": "The directory where to export PDFs. Relative to output directory root setting.",
"type": "string",
"default": ""
}
}
},
Expand Down
10 changes: 9 additions & 1 deletion src/command.rs
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,15 @@ impl Backend {
.map_err(|_| Error::invalid_params("Could not convert file URI to path"))?,
)
.map_err(|_| Error::internal_error())?;
self.compile_diags_export(file_uri, text, true).await;
let config = self.config.read().await;
self.compile_diags_export(
file_uri,
text,
true,
config.output_root,
&config.output_path,
)
.await;
Ok(())
}
}
15 changes: 15 additions & 0 deletions src/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,22 @@ impl Default for ExportPdfMode {
}
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum OutputRoot {
Source,
Workspace,
Absolute,
}

impl Default for OutputRoot {
fn default() -> Self {
Self::Source
}
}

#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct Config {
pub export_pdf: ExportPdfMode,
pub output_root: OutputRoot,
pub output_path: String,
}
75 changes: 70 additions & 5 deletions src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -196,7 +196,30 @@ impl LanguageServer for Backend {
_ => config::ExportPdfMode::OnSave,
})
.unwrap_or_default();

let output_root = settings
.get("outputRoot")
.map(|val| match val {
JsonValue::String(val) => match val.as_str() {
"source" => config::OutputRoot::Source,
"workspace" => config::OutputRoot::Workspace,
"absolute" => config::OutputRoot::Absolute,
_ => config::OutputRoot::default(),
},
_ => config::OutputRoot::default(),
})
.unwrap_or_default();

let output_path = settings
.get("outputPath")
.and_then(|x| x.as_str())
.unwrap_or_default()
.to_string();

config.export_pdf = export_pdf;
config.output_root = output_root;
config.output_path = output_path;

self.client
.log_message(MessageType::INFO, "New settings applied")
.await;
Expand Down Expand Up @@ -226,6 +249,8 @@ impl Backend {
uri,
text,
matches!(config.export_pdf, config::ExportPdfMode::OnType),
config.output_root,
&config.output_path,
)
.await;
}
Expand All @@ -236,17 +261,26 @@ impl Backend {
uri,
text,
matches!(config.export_pdf, config::ExportPdfMode::OnSave),
config.output_root,
&config.output_path,
)
.await;
}

async fn compile_diags_export(&self, uri: Url, text: String, export: bool) {
async fn compile_diags_export(
&self,
file: Url,
text: String,
export: bool,
output_root: config::OutputRoot,
relative_dir: &str,
) {
let mut world_lock = self.world.write().await;
let world = world_lock.as_mut().unwrap();

world.reset();

match world.resolve_with(Path::new(&uri.to_file_path().unwrap()), &text) {
match world.resolve_with(Path::new(&file.to_file_path().unwrap()), &text) {
Ok(id) => {
world.main = id;
}
Expand All @@ -263,7 +297,38 @@ impl Backend {
Ok(document) => {
let buffer = typst::export::pdf(&document);
if export {
let output_path = uri.to_file_path().unwrap().with_extension("pdf");
let output_path = {
let root_dir = match output_root {
config::OutputRoot::Source => {
file.to_file_path().unwrap().parent().unwrap().to_path_buf()
}
config::OutputRoot::Workspace => world.root().to_path_buf(),
config::OutputRoot::Absolute => home::home_dir().unwrap(),
Copy link
Contributor

@beeb beeb Mar 30, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I would make the root path an Optional, and make it None for Absolute. When the root is OutputRoot::Absolute, we should use the outputPath only, which should include / or C:\ (be an absolute path), and ignore the root.

};

let file_name = format!(
"{}.pdf",
file.to_file_path()
.unwrap()
.file_stem()
.unwrap()
.to_string_lossy()
);

let path: PathBuf = [root_dir.to_str().unwrap(), relative_dir, &file_name]
.iter()
.collect();

// create intermediate dirs if missing
if let Some(parent) = path.parent() {
// discard result because if this failed and was necessary,
// the save will fail and the error will be handled there
let _ = fs::create_dir_all(parent);
}

path
};

fs_message = match fs::write(&output_path, buffer)
.map_err(|_| "failed to write PDF file".to_string())
{
Expand All @@ -273,7 +338,7 @@ impl Backend {
}),
Err(e) => Some(LogMessage {
message_type: MessageType::ERROR,
message: format!("{:?}", e),
message: format!("{:?} (writing to: {:?})", e, output_path),
}),
};
}
Expand All @@ -291,7 +356,7 @@ impl Backend {

self.client
.publish_diagnostics(
uri.clone(),
file.clone(),
messages
.into_iter()
.map(|(message, range)| Diagnostic {
Expand Down