fix: dedicated shell syntax highlighting and readme code block styling
HEAD
main
3 files changed, 384 insertions(+), 22 deletions(-)
@@ -129,4 +129,24 @@
html.contains(r#"src="https://github.com/user-attachments/assets/1234?a=1&b=2""#)
);
}
#[test]
fn shell_highlight_preserves_urls_and_highlights_commands_and_flags() {
let block = syntax_highlight::highlight_block(
"git clone https://github.com/y2w8/gitrs.git\nsudo $(which gitrs) --port 80\nNMRS_LOG=trace nmrs-tui\nexport PATH=\"$HOME/.cargo/bin:$PATH\"\n",
"sh",
);
assert!(block.contains(r#"<span class="hl-function">git</span>"#));
assert!(!block.contains("hl-comment"));
assert!(
block.contains(&v_htmlescape::escape("https://github.com/y2w8/gitrs.git").to_string())
);
assert!(block.contains(r#"<span class="hl-function-builtin">sudo</span>"#));
assert!(block.contains(r#"<span class="hl-function-builtin">which</span>"#));
assert!(block.contains(r#"<span class="hl-property">--port</span>"#));
assert!(block.contains(r#"<span class="hl-number">80</span>"#));
assert!(block.contains(r#"<span class="hl-constant">NMRS_LOG</span>"#));
assert!(block.contains(r#"<span class="hl-function">nmrs-tui</span>"#));
assert!(block.contains(r#"<span class="hl-variable">$HOME</span>"#));
}
}
@@ -89,6 +89,23 @@
const BUILTIN_VARS: &[&str] = &["self", "Self", "super", "crate", "this"];
const SHELL_KEYWORDS: &[&str] = &[
"if", "then", "else", "elif", "fi", "for", "in", "do", "done", "while", "until", "case",
"esac", "function", "select", "end", "begin", "switch", "and", "or", "not",
];
const SHELL_BUILTINS: &[&str] = &[
"cd", "echo", "printf", "export", "local", "readonly", "declare", "typeset", "set", "unset",
"read", "return", "exit", "source", "eval", "exec", "shift", "test", "alias", "unalias", "pwd",
"pushd", "popd", "trap", "wait", "true", "false", "which", "type", "command", "builtin",
"sudo", "doas", "env", "time", "nohup", "xargs", "jobs", "fg", "bg", "kill",
];
const SHELL_CMD_PREFIXES: &[&str] = &[
"sudo", "doas", "env", "time", "nohup", "command", "builtin", "exec", "then", "do", "else",
"elif", "and", "or", "not",
];
#[derive(Clone, Copy, PartialEq, Eq)]
enum Mode {
Code {
@@ -96,6 +113,7 @@
dash_comments: bool,
rust_like: bool,
},
Shell,
Config,
Style,
Markup,
@@ -136,18 +154,17 @@
.extension()
.and_then(|s| s.to_str())
.unwrap_or(file_name);
if matches!(
file_name,
".bashrc" | ".zshrc" | ".profile" | ".bash_profile"
) {
return Mode::Shell;
}
if matches!(
file_name,
"justfile"
| "makefile"
| "gnumakefile"
| "dockerfile"
| "containerfile"
| "pkgbuild"
| ".bashrc"
| ".zshrc"
| ".profile"
"justfile" | "makefile" | "gnumakefile" | "dockerfile" | "containerfile" | "pkgbuild"
) {
return Mode::Code {
hash_comments: true,
@@ -172,14 +189,18 @@
"lua" | "sql" => Mode::Code {
hash_comments: false,
dash_comments: true,
rust_like: false,
},
"sh" | "bash" | "zsh" | "fish" | "py" | "python" | "rb" | "ruby" | "nix" | "pl" | "r"
| "just" | "mk" | "cmake" => Mode::Code {
hash_comments: true,
dash_comments: false,
rust_like: false,
},
"sh" | "bash" | "zsh" | "fish" | "shell" | "console" | "ash" | "dash" | "ksh" => {
Mode::Shell
}
"py" | "python" | "rb" | "ruby" | "nix" | "pl" | "r" | "just" | "mk" | "cmake" => {
Mode::Code {
hash_comments: true,
dash_comments: false,
rust_like: false,
}
}
"c" | "h" | "cpp" | "hpp" | "cc" | "cxx" | "go" | "golang" | "js" | "jsx" | "ts"
| "tsx" | "javascript" | "typescript" | "java" | "cs" | "csharp" | "zig" | "kt"
| "kotlin" | "swift" | "dart" | "php" | "glsl" | "wgsl" | "hlsl" => Mode::Code {
@@ -191,11 +212,18 @@
| "timer" | "socket" | "target" | "mount" | "desktop" | "env" => Mode::Config,
"css" | "scss" | "sass" | "less" => Mode::Style,
"html" | "htm" | "xml" | "svg" | "xhtml" => Mode::Markup,
_ if source.starts_with("#!") => Mode::Code {
hash_comments: true,
dash_comments: false,
rust_like: false,
},
_ if source.starts_with("#!") => {
let first_line = source.lines().next().unwrap_or("");
if first_line.contains("sh") {
Mode::Shell
} else {
Mode::Code {
hash_comments: true,
dash_comments: false,
rust_like: false,
}
}
}
_ => Mode::Plain,
}
}
@@ -203,6 +231,7 @@
fn highlight_line(line: &str, mode: Mode, state: &mut State) -> String {
match mode {
Mode::Plain => escape_html(line),
Mode::Shell => highlight_shell_line(line, state),
Mode::Config => highlight_config_line(line),
Mode::Style => highlight_style_line(line, state),
Mode::Markup => highlight_markup_line(line, state),
@@ -278,8 +307,8 @@
continue;
}
// `//` and `/*` comments
if b == b'/' && i + 1 < len {
// `//` and `/*` comments (C-style languages only)
if !hash_comments && !dash_comments && b == b'/' && i + 1 < len {
if bytes[i + 1] == b'/' {
push_span(&mut out, "hl-comment", &line[i..]);
break;
@@ -563,6 +592,293 @@
}
"hl-variable"
}
fn highlight_shell_line(line: &str, state: &mut State) -> String {
let bytes = line.as_bytes();
let len = bytes.len();
let mut i = 0;
let mut out = String::with_capacity(len * 2);
let mut expect_cmd = true;
let mut allow_assign = false;
while i < len {
if *state == State::DoubleString {
i = scan_shell_double_string(line, i, &mut out, state);
continue;
}
let b = bytes[i];
if b.is_ascii_whitespace() {
let start = i;
while i < len && bytes[i].is_ascii_whitespace() {
i += 1;
}
out.push_str(&line[start..i]);
continue;
}
// `#` comment (only at start of line or after whitespace / `;`)
if b == b'#' && (i == 0 || bytes[i - 1].is_ascii_whitespace() || bytes[i - 1] == b';') {
push_span(&mut out, "hl-comment", &line[i..]);
break;
}
// Single-quoted literal string
if b == b'\'' {
let end = scan_single_string(line, i);
push_span(&mut out, "hl-string", &line[i..end]);
i = end;
expect_cmd = false;
continue;
}
// Double-quoted string with `$VAR` interpolation
if b == b'"' {
push_span(&mut out, "hl-string", "\"");
*state = State::DoubleString;
i = scan_shell_double_string(line, i + 1, &mut out, state);
expect_cmd = false;
continue;
}
// Command substitution `$(` or `$VAR` / `${VAR}`
if b == b'$' {
if i + 1 < len && bytes[i + 1] == b'(' {
push_span(&mut out, "hl-operator", "$(");
i += 2;
expect_cmd = true;
allow_assign = false;
continue;
}
let end = scan_shell_var(line, i);
push_span(&mut out, "hl-variable", &line[i..end]);
i = end;
expect_cmd = false;
continue;
}
// Multi-char shell operators and pipes/separators
if let Some((op_len, resets_cmd)) = match_shell_operator(line, i) {
push_span(&mut out, "hl-operator", &line[i..i + op_len]);
i += op_len;
if resets_cmd {
expect_cmd = true;
allow_assign = false;
}
continue;
}
// Closing paren of `$(...)` or subshell
if b == b')' {
push_span(&mut out, "hl-operator", ")");
i += 1;
expect_cmd = false;
continue;
}
// Line continuation backslash at end of line
if b == b'\\' && i + 1 == len {
push_span(&mut out, "hl-operator", "\\");
break;
}
// Scan a full shell word (keeping flags, paths, URLs, `<repo>`, etc. intact)
let start = i;
while i < len && !is_shell_word_break(bytes, i) {
i += line[i..].chars().next().unwrap().len_utf8();
}
if i == start {
let ch_len = line[i..].chars().next().unwrap().len_utf8();
escape_into(&mut out, &line[i..i + ch_len]);
i += ch_len;
continue;
}
let word = &line[start..i];
// `VAR=value` environment assignment (before a command or after `export`/`local`/etc.)
if (expect_cmd || allow_assign)
&& let Some(eq) = word.find('=')
&& eq > 0
&& is_shell_ident(&word[..eq])
{
let name = &word[..eq];
let val = &word[eq + 1..];
let name_class = if name.len() > 1
&& name
.bytes()
.all(|c| c.is_ascii_uppercase() || c.is_ascii_digit() || c == b'_')
{
"hl-constant"
} else {
"hl-variable"
};
push_span(&mut out, name_class, name);
push_span(&mut out, "hl-operator", "=");
if !val.is_empty() {
if val.bytes().all(|c| c.is_ascii_digit()) {
push_span(&mut out, "hl-number", val);
} else if matches!(val, "true" | "false") {
push_span(&mut out, "hl-boolean", val);
} else {
escape_into(&mut out, val);
}
}
continue;
}
if expect_cmd {
if SHELL_KEYWORDS.contains(&word) {
push_span(&mut out, "hl-keyword", word);
expect_cmd = SHELL_CMD_PREFIXES.contains(&word);
allow_assign = false;
} else if SHELL_BUILTINS.contains(&word) {
push_span(&mut out, "hl-function-builtin", word);
expect_cmd = SHELL_CMD_PREFIXES.contains(&word);
allow_assign = matches!(word, "export" | "local" | "readonly" | "declare" | "env");
} else {
push_span(&mut out, "hl-function", word);
expect_cmd = false;
allow_assign = false;
}
} else if word == "--" {
push_span(&mut out, "hl-operator", word);
} else if word.starts_with('-') && word.len() > 1 {
if let Some(eq) = word.find('=') {
push_span(&mut out, "hl-property", &word[..eq]);
push_span(&mut out, "hl-operator", "=");
escape_into(&mut out, &word[eq + 1..]);
} else {
push_span(&mut out, "hl-property", word);
}
} else if word.bytes().all(|c| c.is_ascii_digit()) {
push_span(&mut out, "hl-number", word);
} else if matches!(word, "true" | "false") {
push_span(&mut out, "hl-boolean", word);
} else if matches!(word, "in" | "do" | "then" | "fi" | "done" | "esac") {
push_span(&mut out, "hl-keyword", word);
} else {
escape_into(&mut out, word);
}
}
out
}
fn scan_shell_double_string(
line: &str,
mut i: usize,
out: &mut String,
state: &mut State,
) -> usize {
let bytes = line.as_bytes();
let len = bytes.len();
let mut seg_start = i;
while i < len {
if bytes[i] == b'\\' && i + 1 < len {
if i > seg_start {
push_span(out, "hl-string", &line[seg_start..i]);
}
let esc_end = (i + 2).min(len);
push_span(out, "hl-escape", &line[i..esc_end]);
i = esc_end;
seg_start = i;
} else if bytes[i] == b'$'
&& i + 1 < len
&& bytes[i + 1] != b'"'
&& !bytes[i + 1].is_ascii_whitespace()
{
if i > seg_start {
push_span(out, "hl-string", &line[seg_start..i]);
}
let var_end = scan_shell_var(line, i);
push_span(out, "hl-variable", &line[i..var_end]);
i = var_end;
seg_start = i;
} else if bytes[i] == b'"' {
push_span(out, "hl-string", &line[seg_start..=i]);
*state = State::Normal;
return i + 1;
} else {
i += line[i..].chars().next().unwrap().len_utf8();
}
}
if seg_start < len {
push_span(out, "hl-string", &line[seg_start..len]);
}
len
}
fn scan_shell_var(line: &str, start: usize) -> usize {
let bytes = line.as_bytes();
let len = bytes.len();
let mut i = start + 1;
if i >= len {
return i;
}
if bytes[i] == b'{' {
if let Some(close) = line[i..].find('}') {
return i + close + 1;
}
return len;
}
if matches!(bytes[i], b'?' | b'$' | b'!' | b'@' | b'*' | b'#' | b'-')
|| bytes[i].is_ascii_digit()
{
return i + 1;
}
while i < len && is_ident_continue(bytes[i]) {
i += 1;
}
i
}
fn match_shell_operator(line: &str, i: usize) -> Option<(usize, bool)> {
let rest = &line[i..];
for (op, resets) in [
("2>&1", false),
("1>&2", false),
("<<-", false),
("&&", true),
("||", true),
("|&", true),
(";;", true),
(">>", false),
("<<", false),
(">&", false),
("<&", false),
("|", true),
(";", true),
("&", true),
] {
if rest.starts_with(op) {
return Some((op.len(), resets));
}
}
// Single `<` or `>` only when standalone redirection (not `<repo>` placeholder)
if (rest.starts_with('>') || rest.starts_with('<'))
&& (i == 0 || line.as_bytes()[i - 1].is_ascii_whitespace())
&& (rest.len() == 1 || rest.as_bytes()[1].is_ascii_whitespace())
{
return Some((1, false));
}
None
}
fn is_shell_word_break(bytes: &[u8], i: usize) -> bool {
let b = bytes[i];
b.is_ascii_whitespace() || matches!(b, b'|' | b'&' | b';' | b'(' | b')' | b'"' | b'\'' | b'$')
}
fn is_shell_ident(s: &str) -> bool {
let bytes = s.as_bytes();
!bytes.is_empty()
&& is_ident_start(bytes[0])
&& bytes[1..].iter().all(|&b| is_ident_continue(b))
}
fn highlight_config_line(line: &str) -> String {
@@ -738,6 +738,32 @@
padding-bottom: 0.3rem;
}
.readme code {
background: var(--crust);
color: var(--green);
border: 1px solid var(--surface0);
padding: 0.1rem 0.35rem;
font-size: 0.88em;
}
.readme pre {
background: var(--crust);
border: 1px solid var(--surface1);
padding: 0.85rem 1.1rem;
margin: 0.85rem 0;
line-height: 1.55;
font-size: 0.88rem;
overflow-x: auto;
}
.readme pre code {
background: transparent;
color: var(--text);
border: none;
padding: 0;
font-size: inherit;
}
.readme p {
font-size: 0.92rem;
color: var(--subtext1);