Improve syntax detection

Currently, gitui prioritizes file extensions for syntax detection.
When a file lacks an extension (e.g. Makefile), or the extension
isn't tied to a specific format (e.g. .lock), it disables syntax
highlighting. Gitui will now try to detect the syntax from the entire
filename and the first line of the file using find_syntax_for_file().
This commit is contained in:
Lena 2025-02-18 21:28:54 +01:00
parent cb4294a72b
commit 0e1eb8ae80
No known key found for this signature in database
GPG key ID: BF30558F199B4027

View file

@ -6,7 +6,6 @@ use once_cell::sync::Lazy;
use ratatui::text::{Line, Span}; use ratatui::text::{Line, Span};
use scopetime::scope_time; use scopetime::scope_time;
use std::{ use std::{
ffi::OsStr,
ops::Range, ops::Range,
path::{Path, PathBuf}, path::{Path, PathBuf},
sync::{Arc, Mutex}, sync::{Arc, Mutex},
@ -73,24 +72,20 @@ impl SyntaxText {
params: &RunParams<AsyncAppNotification, ProgressPercent>, params: &RunParams<AsyncAppNotification, ProgressPercent>,
) -> asyncgit::Result<Self> { ) -> asyncgit::Result<Self> {
scope_time!("syntax_highlighting"); scope_time!("syntax_highlighting");
let mut state = { let mut state = {
scope_time!("syntax_highlighting.0"); scope_time!("syntax_highlighting.0");
let syntax = file_path let plain_text = || SYNTAX_SET.find_syntax_plain_text();
.extension() let syntax = SYNTAX_SET
.and_then(OsStr::to_str) .find_syntax_for_file(
.map_or_else( file_path.to_str().unwrap_or_default(),
|| { )
SYNTAX_SET.find_syntax_by_path( .unwrap_or_else(|e| {
file_path.to_str().unwrap_or_default(), log::error!("Could not read the file to detect its syntax: {e}");
) Some(plain_text())
}, })
|ext| SYNTAX_SET.find_syntax_by_extension(ext), .unwrap_or_else(plain_text);
);
ParseState::new(syntax.unwrap_or_else(|| { ParseState::new(syntax)
SYNTAX_SET.find_syntax_plain_text()
}))
}; };
let highlighter = Highlighter::new( let highlighter = Highlighter::new(