From 0e1eb8ae8079a2d89e2c166d831b37fc092bcd2c Mon Sep 17 00:00:00 2001 From: Lena <126529524+acuteenvy@users.noreply.github.com> Date: Tue, 18 Feb 2025 21:28:54 +0100 Subject: [PATCH] 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(). --- src/ui/syntax_text.rs | 27 +++++++++++---------------- 1 file changed, 11 insertions(+), 16 deletions(-) diff --git a/src/ui/syntax_text.rs b/src/ui/syntax_text.rs index fba036e7..938c514e 100644 --- a/src/ui/syntax_text.rs +++ b/src/ui/syntax_text.rs @@ -6,7 +6,6 @@ use once_cell::sync::Lazy; use ratatui::text::{Line, Span}; use scopetime::scope_time; use std::{ - ffi::OsStr, ops::Range, path::{Path, PathBuf}, sync::{Arc, Mutex}, @@ -73,24 +72,20 @@ impl SyntaxText { params: &RunParams, ) -> asyncgit::Result { scope_time!("syntax_highlighting"); - let mut state = { scope_time!("syntax_highlighting.0"); - let syntax = file_path - .extension() - .and_then(OsStr::to_str) - .map_or_else( - || { - SYNTAX_SET.find_syntax_by_path( - file_path.to_str().unwrap_or_default(), - ) - }, - |ext| SYNTAX_SET.find_syntax_by_extension(ext), - ); + let plain_text = || SYNTAX_SET.find_syntax_plain_text(); + let syntax = SYNTAX_SET + .find_syntax_for_file( + file_path.to_str().unwrap_or_default(), + ) + .unwrap_or_else(|e| { + log::error!("Could not read the file to detect its syntax: {e}"); + Some(plain_text()) + }) + .unwrap_or_else(plain_text); - ParseState::new(syntax.unwrap_or_else(|| { - SYNTAX_SET.find_syntax_plain_text() - })) + ParseState::new(syntax) }; let highlighter = Highlighter::new(