Compare commits
27
Commits
abfdea2e78
...
main
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
5bd36b5380 | ||
|
|
7c50234101 | ||
|
|
085ddaa0bf | ||
|
|
24666266d3 | ||
|
|
9b50509910 | ||
|
|
3711e99528 | ||
|
|
7798d556bc | ||
|
|
b4a8084350 | ||
|
|
2bb0a5c099 | ||
|
|
2b0c852e99 | ||
|
|
30ca17e17f | ||
|
|
cac6d0ae31 | ||
|
|
c1057be18e | ||
|
|
06173555f6 | ||
|
|
308dcf2911 | ||
|
|
d5ecc05345 | ||
|
|
853efc406d | ||
|
|
035acb614f | ||
|
|
51173860be | ||
|
|
b157941d5e | ||
|
|
1efb44206b | ||
|
|
e193f96709 | ||
|
|
e6cc71fa47 | ||
|
|
bbb19754bd | ||
|
|
c2e208a20b | ||
|
|
b157703162 | ||
|
|
ea07d11034 |
No files matched your search
Generated
+796
-672
File diff suppressed because it is too large.
Load diff
+26
-15
@@ -1,20 +1,31 @@
|
|||||||
[package]
|
[package]
|
||||||
name = "karnaugh"
|
name = "karnaugh"
|
||||||
version = "0.1.0"
|
version = "0.2.0"
|
||||||
edition = "2024"
|
edition = "2024"
|
||||||
|
|
||||||
[dependencies]
|
[dependencies]
|
||||||
axum = "0.8.7"
|
axum = "0.8.9"
|
||||||
flate2 = "1.1.5"
|
flate2 = "1.1.9"
|
||||||
itertools = "0.14.0"
|
itertools = "0.15.0"
|
||||||
tar = "0.4.44"
|
tar = "0.4.46"
|
||||||
time = "0.3.47"
|
time = "0.3.53"
|
||||||
tokio = { version = "1.48.0", features = ["macros", "rt-multi-thread"] }
|
tokio = { version = "1.53.0", features = ["macros", "rt-multi-thread"] }
|
||||||
tower-http = { version = "0.6.8", features = ["compression-br", "fs", "trace"] }
|
tower-http = { version = "0.7.0", features = [
|
||||||
tracing = "0.1.43"
|
"compression-br",
|
||||||
tracing-subscriber = "0.3.22"
|
"fs",
|
||||||
typst-html = { git = "https://github.com/mkorje/typst.git", branch = "mathml" }
|
"trace",
|
||||||
typst-kit = { git = "https://github.com/mkorje/typst.git", branch = "mathml" }
|
"set-header",
|
||||||
typst = { git = "https://github.com/mkorje/typst.git", branch = "mathml" }
|
] }
|
||||||
ureq = "3.1.4"
|
tracing = "0.1.44"
|
||||||
clap = { version = "4.6.0", features = ["derive"] }
|
tracing-subscriber = "0.3.23"
|
||||||
|
typst-html = "0.15.1"
|
||||||
|
typst-kit = "0.15.1"
|
||||||
|
typst = "0.15.1"
|
||||||
|
ureq = "3.3.0"
|
||||||
|
clap = { version = "4.6.2", features = ["derive"] }
|
||||||
|
typst-library = "0.15.1"
|
||||||
|
typst-utils = "0.15.1"
|
||||||
|
tree-house = "0.4.0"
|
||||||
|
tree-house-bindings = { version = "0.3.2", features = ["ropey"] }
|
||||||
|
ropey = "1.6.1"
|
||||||
|
toml = "0.8.23"
|
||||||
Generated
+46
-3
@@ -18,13 +18,34 @@
|
|||||||
"type": "github"
|
"type": "github"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"helix": {
|
||||||
|
"inputs": {
|
||||||
|
"nixpkgs": [
|
||||||
|
"nixpkgs"
|
||||||
|
],
|
||||||
|
"rust-overlay": "rust-overlay"
|
||||||
|
},
|
||||||
|
"locked": {
|
||||||
|
"lastModified": 1784219418,
|
||||||
|
"narHash": "sha256-yfNBfV6HWAQU/xZXwrFoedsSYsDmCDIlTHRxAZI6teY=",
|
||||||
|
"owner": "helix-editor",
|
||||||
|
"repo": "helix",
|
||||||
|
"rev": "f6f3eb1fe4a73933466f30175843059a4381a985",
|
||||||
|
"type": "github"
|
||||||
|
},
|
||||||
|
"original": {
|
||||||
|
"owner": "helix-editor",
|
||||||
|
"repo": "helix",
|
||||||
|
"type": "github"
|
||||||
|
}
|
||||||
|
},
|
||||||
"nixpkgs": {
|
"nixpkgs": {
|
||||||
"locked": {
|
"locked": {
|
||||||
"lastModified": 1773821835,
|
"lastModified": 1784120854,
|
||||||
"narHash": "sha256-TJ3lSQtW0E2JrznGVm8hOQGVpXjJyXY2guAxku2O9A4=",
|
"narHash": "sha256-KesHgItiZPgGX740axSiQLcIQ8D24MDqNpkKYWIek8k=",
|
||||||
"owner": "nixos",
|
"owner": "nixos",
|
||||||
"repo": "nixpkgs",
|
"repo": "nixpkgs",
|
||||||
"rev": "b40629efe5d6ec48dd1efba650c797ddbd39ace0",
|
"rev": "753cc8a3a87467296ddd1fa93f0cc3e81120ee46",
|
||||||
"type": "github"
|
"type": "github"
|
||||||
},
|
},
|
||||||
"original": {
|
"original": {
|
||||||
@@ -37,9 +58,31 @@
|
|||||||
"root": {
|
"root": {
|
||||||
"inputs": {
|
"inputs": {
|
||||||
"flake-utils": "flake-utils",
|
"flake-utils": "flake-utils",
|
||||||
|
"helix": "helix",
|
||||||
"nixpkgs": "nixpkgs"
|
"nixpkgs": "nixpkgs"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"rust-overlay": {
|
||||||
|
"inputs": {
|
||||||
|
"nixpkgs": [
|
||||||
|
"helix",
|
||||||
|
"nixpkgs"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"locked": {
|
||||||
|
"lastModified": 1775358767,
|
||||||
|
"narHash": "sha256-f2eC+WIfhjevCPQILuV08i/kmKZzYZpUvkom/33VxCA=",
|
||||||
|
"owner": "oxalica",
|
||||||
|
"repo": "rust-overlay",
|
||||||
|
"rev": "20fd44bc663daa53a2575e01293e24e681d62244",
|
||||||
|
"type": "github"
|
||||||
|
},
|
||||||
|
"original": {
|
||||||
|
"owner": "oxalica",
|
||||||
|
"repo": "rust-overlay",
|
||||||
|
"type": "github"
|
||||||
|
}
|
||||||
|
},
|
||||||
"systems": {
|
"systems": {
|
||||||
"locked": {
|
"locked": {
|
||||||
"lastModified": 1681028828,
|
"lastModified": 1681028828,
|
||||||
|
|||||||
@@ -2,6 +2,8 @@
|
|||||||
inputs = {
|
inputs = {
|
||||||
nixpkgs.url = "github:nixos/nixpkgs/nixos-unstable";
|
nixpkgs.url = "github:nixos/nixpkgs/nixos-unstable";
|
||||||
flake-utils.url = "github:numtide/flake-utils";
|
flake-utils.url = "github:numtide/flake-utils";
|
||||||
|
helix.url = "github:helix-editor/helix";
|
||||||
|
helix.inputs.nixpkgs.follows = "nixpkgs";
|
||||||
};
|
};
|
||||||
|
|
||||||
outputs =
|
outputs =
|
||||||
@@ -9,6 +11,7 @@
|
|||||||
self,
|
self,
|
||||||
nixpkgs,
|
nixpkgs,
|
||||||
flake-utils,
|
flake-utils,
|
||||||
|
helix,
|
||||||
...
|
...
|
||||||
}:
|
}:
|
||||||
flake-utils.lib.eachDefaultSystem (
|
flake-utils.lib.eachDefaultSystem (
|
||||||
@@ -19,11 +22,55 @@
|
|||||||
};
|
};
|
||||||
in
|
in
|
||||||
rec {
|
rec {
|
||||||
|
packages.syntax =
|
||||||
|
let
|
||||||
|
grammars = pkgs.callPackage "${helix}/grammars.nix" { };
|
||||||
|
in
|
||||||
|
pkgs.stdenv.mkDerivation {
|
||||||
|
name = "syntax";
|
||||||
|
nativeBuildInputs = [ pkgs.patchelf ];
|
||||||
|
phases = [
|
||||||
|
"buildPhase"
|
||||||
|
"installPhase"
|
||||||
|
];
|
||||||
|
buildPhase = ''
|
||||||
|
mkdir -p build
|
||||||
|
cp -r ${helix}/runtime/queries/* ./build/
|
||||||
|
chmod u+w ./build -R
|
||||||
|
for so in ${grammars}/*.so; do
|
||||||
|
name=$(basename "$so" .so)
|
||||||
|
if [ -d "./build/$name" ]; then
|
||||||
|
cp "$so" "./build/$name/$name.so"
|
||||||
|
chmod u+w "./build/$name/$name.so"
|
||||||
|
patchelf --shrink-rpath "./build/$name/$name.so"
|
||||||
|
fi
|
||||||
|
done
|
||||||
|
'';
|
||||||
|
installPhase = ''
|
||||||
|
mkdir -p $out
|
||||||
|
cp -r ./build/* $out/
|
||||||
|
'';
|
||||||
|
};
|
||||||
|
packages.themes = pkgs.stdenv.mkDerivation {
|
||||||
|
name = "themes";
|
||||||
|
phases = [ "installPhase" ];
|
||||||
|
installPhase = ''
|
||||||
|
mkdir -p $out
|
||||||
|
cp ${helix}/runtime/themes/*.toml $out/
|
||||||
|
'';
|
||||||
|
};
|
||||||
packages.karnaugh = pkgs.rustPlatform.buildRustPackage (final: {
|
packages.karnaugh = pkgs.rustPlatform.buildRustPackage (final: {
|
||||||
pname = "karnaugh";
|
pname = "karnaugh";
|
||||||
version = "0.1.0";
|
version = "0.2.0";
|
||||||
src = self;
|
src = pkgs.lib.fileset.toSource {
|
||||||
cargoHash = "sha256-4jmvuQiQz5TCkY//L2qyx0AiDTxHu8EocFfysgaTaHU=";
|
root = ./.;
|
||||||
|
fileset = pkgs.lib.fileset.unions [
|
||||||
|
./Cargo.toml
|
||||||
|
./Cargo.lock
|
||||||
|
./src
|
||||||
|
];
|
||||||
|
};
|
||||||
|
cargoLock.lockFile = ./Cargo.lock;
|
||||||
});
|
});
|
||||||
packages.container = pkgs.dockerTools.buildImage {
|
packages.container = pkgs.dockerTools.buildImage {
|
||||||
name = "karnaugh";
|
name = "karnaugh";
|
||||||
@@ -31,22 +78,30 @@
|
|||||||
|
|
||||||
copyToRoot = pkgs.buildEnv {
|
copyToRoot = pkgs.buildEnv {
|
||||||
name = "karnaugh-root";
|
name = "karnaugh-root";
|
||||||
paths = [packages.karnaugh];
|
paths = [ packages.karnaugh ];
|
||||||
pathsToLink = ["/bin"];
|
pathsToLink = [ "/bin" ];
|
||||||
};
|
};
|
||||||
|
|
||||||
config = {
|
config = {
|
||||||
Cmd = ["/bin/karnaugh"];
|
Entrypoint = [
|
||||||
|
"/bin/karnaugh"
|
||||||
|
"--syntax-root"
|
||||||
|
"${packages.syntax}"
|
||||||
|
"--themes-root"
|
||||||
|
"${packages.themes}"
|
||||||
|
];
|
||||||
};
|
};
|
||||||
};
|
};
|
||||||
packages.default = packages.karnaugh;
|
packages.default = packages.karnaugh;
|
||||||
|
|
||||||
devShells.default = pkgs.mkShell {
|
devShells.default = pkgs.mkShell {
|
||||||
buildInputs = with pkgs; [
|
buildInputs = with pkgs; [
|
||||||
cargo
|
cargo
|
||||||
rustc
|
rustc
|
||||||
rustfmt
|
rustfmt
|
||||||
clippy
|
clippy
|
||||||
|
cargo-edit
|
||||||
|
cargo-audit
|
||||||
];
|
];
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|||||||
+29
-5
@@ -8,7 +8,7 @@ use ::typst::syntax::VirtualPath;
|
|||||||
use axum::{
|
use axum::{
|
||||||
Router,
|
Router,
|
||||||
extract::{Path, State},
|
extract::{Path, State},
|
||||||
http::StatusCode,
|
http::{HeaderValue, StatusCode, header::CACHE_CONTROL},
|
||||||
response::{Html, IntoResponse, Response},
|
response::{Html, IntoResponse, Response},
|
||||||
routing::get,
|
routing::get,
|
||||||
};
|
};
|
||||||
@@ -17,6 +17,7 @@ use itertools::Itertools;
|
|||||||
use tower_http::{
|
use tower_http::{
|
||||||
compression::CompressionLayer,
|
compression::CompressionLayer,
|
||||||
services::{ServeDir, ServeFile},
|
services::{ServeDir, ServeFile},
|
||||||
|
set_header::SetResponseHeaderLayer,
|
||||||
trace::TraceLayer,
|
trace::TraceLayer,
|
||||||
};
|
};
|
||||||
use tracing::{Level, info};
|
use tracing::{Level, info};
|
||||||
@@ -24,6 +25,8 @@ use tracing_subscriber::FmtSubscriber;
|
|||||||
|
|
||||||
use crate::typst::TypstContext;
|
use crate::typst::TypstContext;
|
||||||
|
|
||||||
|
mod syntax;
|
||||||
|
mod themes;
|
||||||
mod typst;
|
mod typst;
|
||||||
|
|
||||||
#[derive(Clone)]
|
#[derive(Clone)]
|
||||||
@@ -58,6 +61,14 @@ struct AppConfig {
|
|||||||
#[arg(short = 'd', long, value_name = "DIR", default_value = "/tmp/karnaugh")]
|
#[arg(short = 'd', long, value_name = "DIR", default_value = "/tmp/karnaugh")]
|
||||||
packages_root: PathBuf,
|
packages_root: PathBuf,
|
||||||
|
|
||||||
|
/// The directory where the syntax files are stored.
|
||||||
|
#[arg(short = 'g', long, value_name = "DIR", default_value = None)]
|
||||||
|
syntax_root: Option<PathBuf>,
|
||||||
|
|
||||||
|
/// The directory where Helix theme `.toml` files are stored.
|
||||||
|
#[arg(short = 't', long, value_name = "DIR", default_value = None)]
|
||||||
|
themes_root: Option<PathBuf>,
|
||||||
|
|
||||||
/// The log level to use
|
/// The log level to use
|
||||||
#[arg(short = 'l', long, value_name = "LEVEL", default_value_t = Level::INFO)]
|
#[arg(short = 'l', long, value_name = "LEVEL", default_value_t = Level::INFO)]
|
||||||
log_level: Level,
|
log_level: Level,
|
||||||
@@ -93,23 +104,36 @@ async fn main() {
|
|||||||
.with_max_level(state.config.log_level)
|
.with_max_level(state.config.log_level)
|
||||||
.init();
|
.init();
|
||||||
|
|
||||||
|
syntax::init(&state.config);
|
||||||
|
themes::init(&state.config);
|
||||||
|
|
||||||
// TODO: Replace with config option
|
// TODO: Replace with config option
|
||||||
let mut favicon = state.config.get_full_assets_path();
|
let mut favicon = state.config.get_full_assets_path();
|
||||||
favicon.push(PathBuf::from("favicon.svg"));
|
favicon.push(PathBuf::from("favicon.svg"));
|
||||||
|
|
||||||
|
let assets_service = ServeDir::new(state.config.get_full_assets_path());
|
||||||
|
|
||||||
let app = Router::new()
|
let app = Router::new()
|
||||||
.route("/", get(root_handler))
|
.route("/", get(root_handler))
|
||||||
.route("/{*path}", get(typst_handler))
|
.route("/{*path}", get(typst_handler))
|
||||||
.route_service("/favicon.ico", ServeFile::new(favicon))
|
.route_service("/favicon.ico", ServeFile::new(favicon))
|
||||||
.nest_service("/assets", ServeDir::new(&state.config.assets_root))
|
.nest_service("/assets", assets_service)
|
||||||
.with_state(state.clone())
|
.with_state(state.clone())
|
||||||
.layer(TraceLayer::new_for_http())
|
.layer(TraceLayer::new_for_http())
|
||||||
.layer(CompressionLayer::new());
|
.layer(CompressionLayer::new())
|
||||||
|
.layer(SetResponseHeaderLayer::overriding(
|
||||||
|
CACHE_CONTROL,
|
||||||
|
HeaderValue::from_static("public, max-age=86400, immutable"),
|
||||||
|
));
|
||||||
|
|
||||||
let socket = SocketAddrV4::new(Ipv4Addr::new(0, 0, 0, 0), state.config.port);
|
let socket = SocketAddrV4::new(Ipv4Addr::new(0, 0, 0, 0), state.config.port);
|
||||||
info!("Serving Karnaugh on socket {}", socket);
|
info!("Serving Karnaugh on socket {}", socket);
|
||||||
let listener = tokio::net::TcpListener::bind(socket).await.unwrap();
|
let listener = tokio::net::TcpListener::bind(socket)
|
||||||
axum::serve(listener, app).await.unwrap();
|
.await
|
||||||
|
.unwrap_or_else(|_| panic!("Failed to bind to socket {}", socket));
|
||||||
|
axum::serve(listener, app)
|
||||||
|
.await
|
||||||
|
.expect("Failed to serve site");
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn root_handler(State(state): State<AppState>) -> impl IntoResponse {
|
async fn root_handler(State(state): State<AppState>) -> impl IntoResponse {
|
||||||
|
|||||||
+293
@@ -0,0 +1,293 @@
|
|||||||
|
use std::{
|
||||||
|
borrow::Cow,
|
||||||
|
collections::{BTreeSet, HashMap},
|
||||||
|
error::Error,
|
||||||
|
fs,
|
||||||
|
path::{Path, PathBuf},
|
||||||
|
sync::{Arc, OnceLock, RwLock},
|
||||||
|
time::Duration,
|
||||||
|
};
|
||||||
|
|
||||||
|
use ropey::Rope;
|
||||||
|
use tracing::{info, warn};
|
||||||
|
use tree_house::{
|
||||||
|
InjectionLanguageMarker, Language, LanguageConfig, LanguageLoader, Syntax,
|
||||||
|
highlighter::{Highlight, HighlightEvent, Highlighter},
|
||||||
|
read_query,
|
||||||
|
};
|
||||||
|
use tree_house_bindings::Grammar;
|
||||||
|
use typst::{
|
||||||
|
foundations::{Content, Func, NativeElement, NativeFunc, func},
|
||||||
|
text::TextElem,
|
||||||
|
};
|
||||||
|
use typst_html::{HtmlAttr, HtmlElem, attr, tag};
|
||||||
|
|
||||||
|
use crate::AppConfig;
|
||||||
|
|
||||||
|
/// Where grammars are loaded from, captured at `init`.
|
||||||
|
static SYNTAX_ROOT: OnceLock<PathBuf> = OnceLock::new();
|
||||||
|
|
||||||
|
/// LanguageRegistries keyed by ScopeSet
|
||||||
|
static REGISTRIES: OnceLock<RwLock<HashMap<BTreeSet<String>, Arc<LanguageRegistry>>>> =
|
||||||
|
OnceLock::new();
|
||||||
|
|
||||||
|
/// Get the index of the longest prefix of `scope` present in `scopes`.
|
||||||
|
fn highlight_for_scope(scope: &str, scopes: &[String]) -> Option<Highlight> {
|
||||||
|
let mut candidate = scope;
|
||||||
|
loop {
|
||||||
|
if let Some(i) = scopes.iter().position(|n| n == candidate) {
|
||||||
|
return Some(Highlight::new(i as u32));
|
||||||
|
}
|
||||||
|
match candidate.rfind('.') {
|
||||||
|
Some(dot) => candidate = &candidate[..dot],
|
||||||
|
None => return None,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
struct LanguageRegistry {
|
||||||
|
syntax_root: PathBuf,
|
||||||
|
/// The scope vocabulary.
|
||||||
|
scopes: Vec<String>,
|
||||||
|
/// Name to Language mapping, Option to allow storing None for failed
|
||||||
|
/// configuration and preventing reloading.
|
||||||
|
by_name: RwLock<HashMap<String, Option<Language>>>,
|
||||||
|
configs: RwLock<Vec<&'static LanguageConfig>>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl LanguageRegistry {
|
||||||
|
fn new(syntax_root: PathBuf, scopes: Vec<String>) -> Self {
|
||||||
|
Self {
|
||||||
|
syntax_root,
|
||||||
|
scopes,
|
||||||
|
by_name: RwLock::new(HashMap::new()),
|
||||||
|
configs: RwLock::new(Vec::new()),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The `Language` for `name`, loading and configuring its grammar on first
|
||||||
|
/// request. Returns `None` if the grammar is missing or fails to load.
|
||||||
|
fn language(&self, name: &str) -> Option<Language> {
|
||||||
|
if let Some(cached) = self.by_name.read().unwrap().get(name) {
|
||||||
|
return *cached;
|
||||||
|
}
|
||||||
|
|
||||||
|
let loaded = self.load(name);
|
||||||
|
|
||||||
|
let mut by_name = self.by_name.write().unwrap();
|
||||||
|
if let Some(cached) = by_name.get(name) {
|
||||||
|
return *cached;
|
||||||
|
}
|
||||||
|
let language = loaded.map(|config| {
|
||||||
|
let mut configs = self.configs.write().unwrap();
|
||||||
|
configs.push(config);
|
||||||
|
Language::new((configs.len() - 1) as u32)
|
||||||
|
});
|
||||||
|
by_name.insert(name.to_owned(), language);
|
||||||
|
language
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Loads and configures the grammar named `name`, leaking the config to a
|
||||||
|
/// `'static` borrow. `None` if the `.so` is absent or parsing fails.
|
||||||
|
fn load(&self, name: &str) -> Option<&'static LanguageConfig> {
|
||||||
|
let lang_dir = self.syntax_root.join(name);
|
||||||
|
if !lang_dir.join(format!("{name}.so")).exists() {
|
||||||
|
warn!("No grammar found for language {name}");
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
match load_language(name, &lang_dir, &self.syntax_root) {
|
||||||
|
Ok(config) => {
|
||||||
|
config.configure(|scope| highlight_for_scope(scope, &self.scopes));
|
||||||
|
Some(Box::leak(Box::new(config)))
|
||||||
|
}
|
||||||
|
Err(e) => {
|
||||||
|
warn!("Failed to load grammar {name}: {e}");
|
||||||
|
None
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Fetch or build the registry configured for `scopes`.
|
||||||
|
fn registry_for(scopes: BTreeSet<String>) -> Option<Arc<LanguageRegistry>> {
|
||||||
|
let registries = REGISTRIES.get()?;
|
||||||
|
|
||||||
|
// Fast path: already built.
|
||||||
|
if let Some(registry) = registries.read().unwrap().get(&scopes) {
|
||||||
|
return Some(registry.clone());
|
||||||
|
}
|
||||||
|
|
||||||
|
let syntax_root = SYNTAX_ROOT.get()?;
|
||||||
|
let ordered = scopes.iter().cloned().collect();
|
||||||
|
let registry = Arc::new(LanguageRegistry::new(syntax_root.clone(), ordered));
|
||||||
|
|
||||||
|
Some(
|
||||||
|
registries
|
||||||
|
.write()
|
||||||
|
.unwrap()
|
||||||
|
.entry(scopes)
|
||||||
|
.or_insert(registry)
|
||||||
|
.clone(),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn load_language(
|
||||||
|
name: &str,
|
||||||
|
lang_dir: &Path,
|
||||||
|
syntax_root: &Path,
|
||||||
|
) -> Result<LanguageConfig, Box<dyn Error>> {
|
||||||
|
let grammar = unsafe { Grammar::new(name, &lang_dir.join(format!("{name}.so")))? };
|
||||||
|
|
||||||
|
let read = |kind: &str| {
|
||||||
|
read_query(name, |lang| {
|
||||||
|
fs::read_to_string(syntax_root.join(lang).join(format!("{kind}.scm")))
|
||||||
|
.unwrap_or_default()
|
||||||
|
})
|
||||||
|
};
|
||||||
|
|
||||||
|
let config = LanguageConfig::new(
|
||||||
|
grammar,
|
||||||
|
&read("highlights"),
|
||||||
|
&read("injections"),
|
||||||
|
&read("locals"),
|
||||||
|
)?;
|
||||||
|
|
||||||
|
Ok(config)
|
||||||
|
}
|
||||||
|
|
||||||
|
impl LanguageLoader for LanguageRegistry {
|
||||||
|
fn language_for_marker(&self, marker: InjectionLanguageMarker<'_>) -> Option<Language> {
|
||||||
|
match marker {
|
||||||
|
InjectionLanguageMarker::Name(name) => self.language(name),
|
||||||
|
InjectionLanguageMarker::Match(text) => {
|
||||||
|
let name: Cow<str> = text.into();
|
||||||
|
self.language(name.as_ref())
|
||||||
|
}
|
||||||
|
_ => None,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn get_config(&self, lang: Language) -> Option<&LanguageConfig> {
|
||||||
|
self.configs.read().unwrap().get(lang.idx()).copied()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn init(config: &AppConfig) {
|
||||||
|
match &config.syntax_root {
|
||||||
|
Some(syntax_root) => {
|
||||||
|
info!("Loading syntax files from {}", syntax_root.display());
|
||||||
|
SYNTAX_ROOT.get_or_init(|| syntax_root.clone());
|
||||||
|
REGISTRIES.get_or_init(|| RwLock::new(HashMap::new()));
|
||||||
|
}
|
||||||
|
None => {
|
||||||
|
warn!(
|
||||||
|
"No syntax root has been configured, improved tree-sitter highlighting will not be possible."
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn highlight_func() -> Func {
|
||||||
|
highlight::func()
|
||||||
|
}
|
||||||
|
|
||||||
|
#[func]
|
||||||
|
fn highlight(
|
||||||
|
text: String,
|
||||||
|
#[named]
|
||||||
|
#[default(false)]
|
||||||
|
block: bool,
|
||||||
|
#[named]
|
||||||
|
#[default(None)]
|
||||||
|
lang: Option<String>,
|
||||||
|
#[named]
|
||||||
|
#[default(None)]
|
||||||
|
light: Option<String>,
|
||||||
|
#[named]
|
||||||
|
#[default(None)]
|
||||||
|
dark: Option<String>,
|
||||||
|
) -> Content {
|
||||||
|
let highlighted = highlight_code(&text, lang.as_deref(), light.as_deref(), dark.as_deref())
|
||||||
|
.unwrap_or_else(|| TextElem::packed(text));
|
||||||
|
|
||||||
|
if block {
|
||||||
|
HtmlElem::new(tag::pre)
|
||||||
|
.with_body(Some(highlighted))
|
||||||
|
.with_attr(HtmlAttr::constant("class"), "code-block")
|
||||||
|
.pack()
|
||||||
|
} else {
|
||||||
|
HtmlElem::new(tag::code)
|
||||||
|
.with_body(Some(highlighted))
|
||||||
|
.with_attr(HtmlAttr::constant("class"), "code-inline")
|
||||||
|
.pack()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Highlights `source` as `lang`.
|
||||||
|
fn highlight_code(
|
||||||
|
source: &str,
|
||||||
|
lang: Option<&str>,
|
||||||
|
light: Option<&str>,
|
||||||
|
dark: Option<&str>,
|
||||||
|
) -> Option<Content> {
|
||||||
|
let (lang, light, dark) = (lang?, light?, dark?);
|
||||||
|
let Some(scopes) = crate::themes::shared_scopes(light, dark) else {
|
||||||
|
warn!("Unknown theme in pair (light={light}, dark={dark})");
|
||||||
|
return None;
|
||||||
|
};
|
||||||
|
let registry = registry_for(scopes)?;
|
||||||
|
let language = registry.language(lang)?;
|
||||||
|
|
||||||
|
let rope = Rope::from_str(source);
|
||||||
|
let slice = rope.slice(..);
|
||||||
|
let loader = registry.as_ref();
|
||||||
|
let syntax = Syntax::new(slice, language, Duration::from_secs(3), loader).ok()?;
|
||||||
|
let mut hl = Highlighter::new(&syntax, slice, loader, 0..source.len() as u32);
|
||||||
|
|
||||||
|
let src = source.as_bytes();
|
||||||
|
let src_len = source.len() as u32;
|
||||||
|
let mut pos: u32 = 0;
|
||||||
|
let mut classes = String::new();
|
||||||
|
let mut nodes = Vec::<Content>::new();
|
||||||
|
|
||||||
|
loop {
|
||||||
|
let next = hl.next_event_offset().min(src_len);
|
||||||
|
|
||||||
|
if next > pos {
|
||||||
|
let text = std::str::from_utf8(&src[pos as usize..next as usize]).ok()?;
|
||||||
|
let node = TextElem::packed(text);
|
||||||
|
nodes.push(if classes.is_empty() {
|
||||||
|
node
|
||||||
|
} else {
|
||||||
|
HtmlElem::new(tag::span)
|
||||||
|
.with_attr(attr::class, classes.clone())
|
||||||
|
.with_body(Some(node))
|
||||||
|
.pack()
|
||||||
|
});
|
||||||
|
pos = next;
|
||||||
|
}
|
||||||
|
|
||||||
|
if pos >= src_len {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
|
||||||
|
let (event, highlights) = hl.advance();
|
||||||
|
let base = match event {
|
||||||
|
// Replace the active highlights
|
||||||
|
HighlightEvent::Refresh => String::new(),
|
||||||
|
// Extend the active highlights
|
||||||
|
HighlightEvent::Push => classes.clone(),
|
||||||
|
};
|
||||||
|
classes = highlights.fold(base, |mut acc, h| {
|
||||||
|
let name = registry.scopes[h.idx()].replace('.', "-");
|
||||||
|
if !acc.is_empty() {
|
||||||
|
acc.push(' ');
|
||||||
|
}
|
||||||
|
acc.push_str("hl-");
|
||||||
|
acc.push_str(&name);
|
||||||
|
acc
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
Some(Content::sequence(nodes))
|
||||||
|
}
|
||||||
+336
@@ -0,0 +1,336 @@
|
|||||||
|
use std::{
|
||||||
|
collections::{BTreeSet, HashMap, HashSet},
|
||||||
|
fs,
|
||||||
|
path::Path,
|
||||||
|
sync::OnceLock,
|
||||||
|
};
|
||||||
|
|
||||||
|
use toml::{Table, Value};
|
||||||
|
use tracing::{info, warn};
|
||||||
|
use typst::foundations::{Func, NativeFunc, func};
|
||||||
|
|
||||||
|
use crate::AppConfig;
|
||||||
|
|
||||||
|
static REGISTRY: OnceLock<ThemeRegistry> = OnceLock::new();
|
||||||
|
|
||||||
|
#[derive(Debug)]
|
||||||
|
struct ThemeRegistry {
|
||||||
|
themes: HashMap<String, Theme>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl ThemeRegistry {
|
||||||
|
fn new(theme_root: &Path) -> Self {
|
||||||
|
let mut helix_themes = HashMap::new();
|
||||||
|
for entry in fs::read_dir(theme_root).into_iter().flatten().flatten() {
|
||||||
|
let name = entry
|
||||||
|
.path()
|
||||||
|
.file_prefix()
|
||||||
|
.unwrap()
|
||||||
|
.to_string_lossy()
|
||||||
|
.into_owned();
|
||||||
|
if let Ok(text) = fs::read_to_string(entry.path())
|
||||||
|
&& let Ok(toml) = toml::from_str::<Table>(&text)
|
||||||
|
{
|
||||||
|
helix_themes.insert(name, toml);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// resolve inheritance
|
||||||
|
while helix_themes
|
||||||
|
.values()
|
||||||
|
.any(|table| table.contains_key("inherits"))
|
||||||
|
{
|
||||||
|
let old_themes = helix_themes.clone();
|
||||||
|
old_themes
|
||||||
|
.keys()
|
||||||
|
.filter(|name| old_themes.get(*name).unwrap().contains_key("inherits"))
|
||||||
|
.for_each(|name| {
|
||||||
|
let parent_name = old_themes
|
||||||
|
.get(name)
|
||||||
|
.unwrap()
|
||||||
|
.get("inherits")
|
||||||
|
.unwrap()
|
||||||
|
.as_str()
|
||||||
|
.unwrap();
|
||||||
|
let parent = old_themes.get(parent_name).unwrap();
|
||||||
|
if !parent.contains_key("inherits") {
|
||||||
|
let table = helix_themes.get_mut(name).unwrap();
|
||||||
|
parent.into_iter().for_each(|(k, v)| {
|
||||||
|
if k == "palette" {
|
||||||
|
let parent_palette = v.as_table();
|
||||||
|
let child_palette = table
|
||||||
|
.entry(k.clone())
|
||||||
|
.or_insert_with(|| Value::Table(Table::new()))
|
||||||
|
.as_table_mut();
|
||||||
|
if let (Some(parent_palette), Some(child_palette)) =
|
||||||
|
(parent_palette, child_palette)
|
||||||
|
{
|
||||||
|
for (pk, pv) in parent_palette {
|
||||||
|
child_palette
|
||||||
|
.entry(pk.clone())
|
||||||
|
.or_insert_with(|| pv.clone());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} else if !table.contains_key(k) {
|
||||||
|
table.insert(k.clone(), v.clone());
|
||||||
|
}
|
||||||
|
});
|
||||||
|
table.remove("inherits");
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
let themes = helix_themes
|
||||||
|
.into_iter()
|
||||||
|
.flat_map(|(name, table)| match Theme::from_toml(table) {
|
||||||
|
Some(theme) => Some((name, theme)),
|
||||||
|
None => {
|
||||||
|
warn!("Theme {name} is missing an `ui.background`, skipping it");
|
||||||
|
None
|
||||||
|
}
|
||||||
|
})
|
||||||
|
.collect();
|
||||||
|
|
||||||
|
Self { themes }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
|
||||||
|
struct Color(String);
|
||||||
|
|
||||||
|
impl Color {
|
||||||
|
fn from_str(color: &str) -> Option<Self> {
|
||||||
|
if color.starts_with('#') {
|
||||||
|
Some(Self(color.into()))
|
||||||
|
} else {
|
||||||
|
None
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn from_palette(color: &str, palette: &HashMap<String, Color>) -> Option<Self> {
|
||||||
|
if color.starts_with('#') {
|
||||||
|
Self::from_str(color)
|
||||||
|
} else if let Some(color) = palette.get(color) {
|
||||||
|
Some(color.clone())
|
||||||
|
} else {
|
||||||
|
// Neither a hex literal nor a palette entry; assume a named CSS
|
||||||
|
// colour and pass it through verbatim.
|
||||||
|
warn!("Unresolved colour {color}, passing it through as a literal");
|
||||||
|
Some(Self(color.into()))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
|
||||||
|
struct Style {
|
||||||
|
fg: Option<Color>,
|
||||||
|
bold: bool,
|
||||||
|
italic: bool,
|
||||||
|
underlined: bool,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Style {
|
||||||
|
fn from_toml(style: Value, palette: &HashMap<String, Color>) -> Option<Self> {
|
||||||
|
let resolve = |s: &str| Color::from_palette(s, palette);
|
||||||
|
match style {
|
||||||
|
Value::String(s) => Some(Self {
|
||||||
|
fg: resolve(&s),
|
||||||
|
bold: false,
|
||||||
|
italic: false,
|
||||||
|
underlined: false,
|
||||||
|
}),
|
||||||
|
Value::Table(table) => {
|
||||||
|
let fg = table.get("fg").and_then(Value::as_str).and_then(resolve);
|
||||||
|
let modifiers: HashSet<&str> = table
|
||||||
|
.get("modifiers")
|
||||||
|
.and_then(Value::as_array)
|
||||||
|
.into_iter()
|
||||||
|
.flatten()
|
||||||
|
.flat_map(Value::as_str)
|
||||||
|
.collect();
|
||||||
|
Some(Self {
|
||||||
|
fg,
|
||||||
|
bold: modifiers.contains("bold"),
|
||||||
|
italic: modifiers.contains("italic"),
|
||||||
|
underlined: modifiers.contains("underlined"),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
_ => None,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug)]
|
||||||
|
struct Theme {
|
||||||
|
foreground: Option<Color>,
|
||||||
|
background: Option<Color>,
|
||||||
|
styles: HashMap<String, Style>,
|
||||||
|
}
|
||||||
|
|
||||||
|
static IGNORED_SCOPES: &[&str] = &["warning", "error", "info", "hint"];
|
||||||
|
|
||||||
|
impl Theme {
|
||||||
|
fn from_toml(theme: Table) -> Option<Self> {
|
||||||
|
let palette = theme
|
||||||
|
.get("palette")
|
||||||
|
.and_then(Value::as_table)
|
||||||
|
.cloned()
|
||||||
|
.map(|table| {
|
||||||
|
table
|
||||||
|
.into_iter()
|
||||||
|
.flat_map(|(k, v)| v.as_str().and_then(Color::from_str).map(|v| (k, v)))
|
||||||
|
.collect::<HashMap<String, Color>>()
|
||||||
|
})
|
||||||
|
.unwrap_or_default();
|
||||||
|
|
||||||
|
let resolve = |c: &str| Color::from_palette(c, &palette);
|
||||||
|
|
||||||
|
let ui_background = theme.get("ui.background").and_then(Value::as_table)?;
|
||||||
|
let foreground = ui_background
|
||||||
|
.get("fg")
|
||||||
|
.and_then(Value::as_str)
|
||||||
|
.and_then(resolve);
|
||||||
|
let background = ui_background
|
||||||
|
.get("bg")
|
||||||
|
.and_then(Value::as_str)
|
||||||
|
.and_then(resolve);
|
||||||
|
|
||||||
|
let styles = theme
|
||||||
|
.into_iter()
|
||||||
|
.filter(|(k, _)| {
|
||||||
|
!k.starts_with("ui.")
|
||||||
|
&& !k.starts_with("diagnostic.")
|
||||||
|
&& !IGNORED_SCOPES.contains(&k.as_str())
|
||||||
|
})
|
||||||
|
.flat_map(|(k, v)| Style::from_toml(v, &palette).map(|v| (k, v)))
|
||||||
|
.collect();
|
||||||
|
|
||||||
|
Some(Self {
|
||||||
|
foreground,
|
||||||
|
background,
|
||||||
|
styles,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn init(config: &AppConfig) {
|
||||||
|
match &config.themes_root {
|
||||||
|
Some(themes_root) => {
|
||||||
|
info!("Loading themes from {}", themes_root.display());
|
||||||
|
REGISTRY.get_or_init(|| ThemeRegistry::new(themes_root));
|
||||||
|
}
|
||||||
|
None => {
|
||||||
|
warn!("No themes root has been configured, theme-based colouring will not be possible.")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The intersection of scopes between two themes.
|
||||||
|
pub fn shared_scopes(light: &str, dark: &str) -> Option<BTreeSet<String>> {
|
||||||
|
let registry = REGISTRY.get()?;
|
||||||
|
let light = registry.themes.get(light)?;
|
||||||
|
let dark = registry.themes.get(dark)?;
|
||||||
|
Some(
|
||||||
|
light
|
||||||
|
.styles
|
||||||
|
.keys()
|
||||||
|
.filter(|k| dark.styles.contains_key(*k))
|
||||||
|
.cloned()
|
||||||
|
.collect(),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn theme_css_func() -> Func {
|
||||||
|
theme_css::func()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn scope_to_selector(scope: &str) -> String {
|
||||||
|
format!(".hl-{}", scope.replace('.', "-"))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn style_declarations(style: &Style) -> String {
|
||||||
|
let mut parts = Vec::new();
|
||||||
|
if let Some(Color(hex)) = &style.fg {
|
||||||
|
parts.push(format!("color:{hex}"));
|
||||||
|
}
|
||||||
|
parts.push(format!(
|
||||||
|
"font-weight:{}",
|
||||||
|
if style.bold { "bold" } else { "normal" }
|
||||||
|
));
|
||||||
|
parts.push(format!(
|
||||||
|
"font-style:{}",
|
||||||
|
if style.italic { "italic" } else { "normal" }
|
||||||
|
));
|
||||||
|
parts.push(format!(
|
||||||
|
"text-decoration:{}",
|
||||||
|
if style.underlined {
|
||||||
|
"underline"
|
||||||
|
} else {
|
||||||
|
"none"
|
||||||
|
}
|
||||||
|
));
|
||||||
|
parts.join(";")
|
||||||
|
}
|
||||||
|
|
||||||
|
fn generate_css(scopes: &[&str], theme: &Theme) -> String {
|
||||||
|
let mut rules = Vec::new();
|
||||||
|
|
||||||
|
// The theme's editor foreground/background colour the code block itself.
|
||||||
|
let mut block_style = Vec::new();
|
||||||
|
if let Some(Color(hex)) = &theme.foreground {
|
||||||
|
block_style.push(format!("color:{hex}"));
|
||||||
|
}
|
||||||
|
if let Some(Color(hex)) = &theme.background {
|
||||||
|
block_style.push(format!("background:{hex}"));
|
||||||
|
}
|
||||||
|
if !block_style.is_empty() {
|
||||||
|
rules.push(format!(".code-block{{{}}}", block_style.join(";")));
|
||||||
|
}
|
||||||
|
|
||||||
|
let mut groups: HashMap<&Style, Vec<&str>> = HashMap::new();
|
||||||
|
for &scope in scopes {
|
||||||
|
if let Some(style) = theme.styles.get(scope) {
|
||||||
|
groups.entry(style).or_default().push(scope);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
let mut group_rules: Vec<String> = groups
|
||||||
|
.iter()
|
||||||
|
.map(|(style, scopes)| {
|
||||||
|
let selectors = scopes
|
||||||
|
.iter()
|
||||||
|
.map(|s| scope_to_selector(s))
|
||||||
|
.collect::<Vec<_>>()
|
||||||
|
.join(",");
|
||||||
|
format!("{}{{{}}}", selectors, style_declarations(style))
|
||||||
|
})
|
||||||
|
.collect();
|
||||||
|
// Sort so the emitted stylesheet is deterministic across runs.
|
||||||
|
group_rules.sort();
|
||||||
|
rules.extend(group_rules);
|
||||||
|
|
||||||
|
rules.join("\n")
|
||||||
|
}
|
||||||
|
|
||||||
|
#[func]
|
||||||
|
fn theme_css(light: String, dark: String) -> String {
|
||||||
|
let Some(registry) = REGISTRY.get() else {
|
||||||
|
return String::new();
|
||||||
|
};
|
||||||
|
let Some(light_theme) = registry.themes.get(&light) else {
|
||||||
|
warn!("Unknown light theme: {light}");
|
||||||
|
return String::new();
|
||||||
|
};
|
||||||
|
let Some(dark_theme) = registry.themes.get(&dark) else {
|
||||||
|
warn!("Unknown dark theme: {dark}");
|
||||||
|
return String::new();
|
||||||
|
};
|
||||||
|
|
||||||
|
let shared = shared_scopes(&light, &dark).unwrap_or_default();
|
||||||
|
let shared: Vec<&str> = shared.iter().map(String::as_str).collect();
|
||||||
|
|
||||||
|
let light_css = generate_css(&shared, light_theme);
|
||||||
|
let dark_css = generate_css(&shared, dark_theme);
|
||||||
|
|
||||||
|
format!("{light_css}\n@media (prefers-color-scheme:dark){{{dark_css}}}")
|
||||||
|
}
|
||||||
@@ -5,11 +5,12 @@ use tracing::info;
|
|||||||
use typst::{
|
use typst::{
|
||||||
Library, LibraryExt, World,
|
Library, LibraryExt, World,
|
||||||
diag::{FileError, FileResult, PackageError, PackageResult, SourceDiagnostic},
|
diag::{FileError, FileResult, PackageError, PackageResult, SourceDiagnostic},
|
||||||
foundations::{Bytes, Datetime, Duration},
|
foundations::{Bytes, Datetime, Dict, Duration, Value},
|
||||||
syntax::{FileId, RootedPath, Source, VirtualPath, VirtualRoot, package::PackageSpec},
|
syntax::{FileId, RootedPath, Source, VirtualPath, VirtualRoot, package::PackageSpec},
|
||||||
text::{Font, FontBook},
|
text::{Font, FontBook},
|
||||||
utils::LazyHash,
|
utils::LazyHash,
|
||||||
};
|
};
|
||||||
|
use typst_html::HtmlOptions;
|
||||||
use typst_kit::fonts::FontStore;
|
use typst_kit::fonts::FontStore;
|
||||||
|
|
||||||
use crate::AppConfig;
|
use crate::AppConfig;
|
||||||
@@ -22,7 +23,21 @@ pub struct TypstContext {
|
|||||||
|
|
||||||
impl TypstContext {
|
impl TypstContext {
|
||||||
pub fn new(config: AppConfig) -> Self {
|
pub fn new(config: AppConfig) -> Self {
|
||||||
|
let mut inputs = Dict::new();
|
||||||
|
if config.syntax_root.is_some() {
|
||||||
|
inputs.insert(
|
||||||
|
"highlight".into(),
|
||||||
|
Value::Func(crate::syntax::highlight_func()),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
if config.themes_root.is_some() {
|
||||||
|
inputs.insert(
|
||||||
|
"theme_css".into(),
|
||||||
|
Value::Func(crate::themes::theme_css_func()),
|
||||||
|
);
|
||||||
|
}
|
||||||
let library = Library::builder()
|
let library = Library::builder()
|
||||||
|
.with_inputs(inputs)
|
||||||
.with_features([typst::Feature::Html].into_iter().collect())
|
.with_features([typst::Feature::Html].into_iter().collect())
|
||||||
.build();
|
.build();
|
||||||
let library = LazyHash::new(library);
|
let library = LazyHash::new(library);
|
||||||
@@ -41,12 +56,14 @@ impl TypstContext {
|
|||||||
let world = DocumentWorld::new(path, self);
|
let world = DocumentWorld::new(path, self);
|
||||||
let compiled = typst::compile(&world);
|
let compiled = typst::compile(&world);
|
||||||
|
|
||||||
|
let html_options = HtmlOptions::default();
|
||||||
|
|
||||||
// TODO: Log warnings
|
// TODO: Log warnings
|
||||||
|
|
||||||
// TODO: Log errors
|
// TODO: Log errors
|
||||||
compiled
|
compiled
|
||||||
.output
|
.output
|
||||||
.and_then(|doc| typst_html::html(&doc))
|
.and_then(|doc| typst_html::html(&doc, &html_options))
|
||||||
.map_err(|err| err.into_iter().collect())
|
.map_err(|err| err.into_iter().collect())
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -116,7 +133,8 @@ impl<'a> DocumentWorld<'a> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
fn resolve_project_file(&self, path: &VirtualPath) -> FileResult<PathBuf> {
|
fn resolve_project_file(&self, path: &VirtualPath) -> FileResult<PathBuf> {
|
||||||
Ok(path.realize(&self.context.config.content_root))
|
path.realize(&self.context.config.content_root)
|
||||||
|
.map_err(FileError::Realize)
|
||||||
}
|
}
|
||||||
|
|
||||||
fn resolve_package_file(&self, path: &VirtualPath, spec: &PackageSpec) -> FileResult<PathBuf> {
|
fn resolve_package_file(&self, path: &VirtualPath, spec: &PackageSpec) -> FileResult<PathBuf> {
|
||||||
@@ -129,17 +147,23 @@ impl<'a> DocumentWorld<'a> {
|
|||||||
|
|
||||||
fn resolve_common_file(&self, path: &VirtualPath, spec: &PackageSpec) -> FileResult<PathBuf> {
|
fn resolve_common_file(&self, path: &VirtualPath, spec: &PackageSpec) -> FileResult<PathBuf> {
|
||||||
let path = get_package_path(path, spec);
|
let path = get_package_path(path, spec);
|
||||||
Ok(path.realize(&self.context.config.get_full_common_path()))
|
path.realize(&self.context.config.get_full_common_path())
|
||||||
|
.map_err(FileError::Realize)
|
||||||
}
|
}
|
||||||
|
|
||||||
fn resolve_preview_file(&self, path: &VirtualPath, spec: &PackageSpec) -> FileResult<PathBuf> {
|
fn resolve_preview_file(&self, path: &VirtualPath, spec: &PackageSpec) -> FileResult<PathBuf> {
|
||||||
let package_path = self.get_package(spec)?;
|
let package_path = self.get_package(spec)?;
|
||||||
Ok(path.realize(&package_path))
|
path.realize(&package_path).map_err(FileError::Realize)
|
||||||
}
|
}
|
||||||
|
|
||||||
fn get_package(&self, spec: &PackageSpec) -> PackageResult<PathBuf> {
|
fn get_package(&self, spec: &PackageSpec) -> PackageResult<PathBuf> {
|
||||||
let path = get_package_path(&VirtualPath::new("").unwrap(), spec);
|
let path = get_package_path(
|
||||||
let path = path.realize(&self.context.config.packages_root);
|
&VirtualPath::new("").expect("Failed to create empty virtual path"),
|
||||||
|
spec,
|
||||||
|
);
|
||||||
|
let path = path
|
||||||
|
.realize(&self.context.config.packages_root)
|
||||||
|
.map_err(|_| PackageError::NotFound(spec.clone()))?;
|
||||||
|
|
||||||
if path.exists() {
|
if path.exists() {
|
||||||
return Ok(path);
|
return Ok(path);
|
||||||
@@ -177,6 +201,9 @@ impl<'a> DocumentWorld<'a> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
fn get_package_path(file_path: &VirtualPath, spec: &PackageSpec) -> VirtualPath {
|
fn get_package_path(file_path: &VirtualPath, spec: &PackageSpec) -> VirtualPath {
|
||||||
let package_path = VirtualPath::new(format!("{}/{}", spec.name, spec.version)).unwrap();
|
let package_path = VirtualPath::new(format!("{}/{}", spec.name, spec.version))
|
||||||
package_path.join(file_path.get_without_slash()).unwrap()
|
.expect("Failed to create virtual path representing package path.");
|
||||||
|
package_path
|
||||||
|
.join(file_path.get_without_slash())
|
||||||
|
.expect("Failed to join file path into package path.")
|
||||||
}
|
}
|
||||||
Reference in new issue
Block a user