add option to specify syntax

This commit is contained in:
LordMZTE 2021-11-17 18:48:47 +01:00
parent 33ba1c05a0
commit cee0464998

View file

@ -1,12 +1,13 @@
use std::{
io::{BufRead, Cursor},
fs::File,
io::{BufRead, BufReader, Cursor},
path::PathBuf,
};
use clap::{crate_authors, crate_version, Parser};
use miette::{bail, IntoDiagnostic, WrapErr};
use miette::{bail, miette, IntoDiagnostic, WrapErr};
use syntect::{
easy::HighlightFile,
easy::HighlightLines,
highlighting::{Color, Style, ThemeSet},
parsing::SyntaxSet,
};
@ -26,6 +27,9 @@ enum Cmd {
#[clap(about = "Print available themes and exit")]
ListThemes,
#[clap(about = "Print available syntaxes and exit")]
ListSyntaxes,
#[clap(about = "Highlight a file", alias = "hl")]
Highlight {
#[clap(about = "The file to highlight")]
@ -38,6 +42,13 @@ enum Cmd {
about = "The color scheme to use"
)]
theme: String,
#[clap(
long,
short,
about = "The syntax to use. Uses file extension if not provided."
)]
syntax: Option<String>,
},
}
@ -54,6 +65,7 @@ fn main() -> miette::Result<()> {
.into_diagnostic()
.wrap_err("Failed to load static dracula theme")?,
);
let ss = SyntaxSet::load_defaults_newlines();
match opt.cmd {
Cmd::ListThemes => {
@ -63,22 +75,52 @@ fn main() -> miette::Result<()> {
Ok(())
},
Cmd::Highlight { file, theme } => {
let ss = SyntaxSet::load_defaults_newlines();
Cmd::ListSyntaxes => {
let mut syntaxes = ss.syntaxes().to_vec();
syntaxes.sort_by(|a, b| a.name.cmp(&b.name));
for syn in syntaxes {
println!("{}\t[{}]", syn.name, syn.file_extensions.join(", "))
}
Ok(())
},
Cmd::Highlight {
file,
theme,
syntax,
} => {
let theme = if let Some(t) = ts.themes.get(&theme) {
t
} else {
bail!("No such theme! Use list-themes to list themes.");
};
let mut h = HighlightFile::new(file, &ss, theme)
.into_diagnostic()
.wrap_err("Failed to open file")?;
let syntax = if let Some(syn) = syntax {
ss.find_syntax_by_name(&syn)
} else {
ss.find_syntax_for_file(&file)
.into_diagnostic()
.wrap_err("Failed to open file for finding syntax.")?
};
let reader = BufReader::new(
File::open(file)
.into_diagnostic()
.wrap_err("Failed to open file")?,
);
let syntax = syntax.ok_or_else(|| {
miette!("Couldn't find syntax. Set one that exists.\nList with list-syntaxes.")
})?;
let mut hl = HighlightLines::new(syntax, theme);
print!("<pre>");
for line in h.reader.lines() {
for line in reader.lines() {
let line = line.into_diagnostic().wrap_err("Failed to read file")?;
let regions = h.highlight_lines.highlight(&line, &ss);
let regions = hl.highlight(&line, &ss);
for (
Style {