Build your personal knowledge base with Trilium Notes
TypeScript electronelectron-appknowledge-baseknowledge-graphknowledge-managementknowledge-management-graphlocal-firstnote-managmentnote-takernote-takingnotebooknotesnotes-apppersonal-knowledge-basepersonal-wikiscriptableself-hostedself-hostingwiki
use highlight.js in code_handlers where possible
perf3ct6e8ab373d872
diff --git a/src/services/llm/context/code_handlers.ts b/src/services/llm/context/code_handlers.tsindex 22a16b22b7..6af77e73a9 100644--- a/src/services/llm/context/code_handlers.ts+++ b/src/services/llm/context/code_handlers.ts@@ -2,6 +2,9 @@* Helper functions for processing code notes, including language detection and structure extraction*/+// Import highlight.js dynamically when needed+let hljs: any = null;+/*** Attempt to detect the programming language from code content or note attributes*/@@ -46,6 +49,51 @@ export function detectLanguage(content: string, mime: string): string {}}+ // For performance, limit the amount of code we pass to highlight.js+ // Use a maximum of ~10KB of code for detection+ const MAX_SAMPLE_SIZE = 10240;+ const codeSample = content.length > MAX_SAMPLE_SIZE+ ? content.substring(0, MAX_SAMPLE_SIZE)+ : content;++ try {+ // Browser environment+ if (typeof window !== 'undefined' && window.hljs) {+ const result = window.hljs.highlightAuto(codeSample);+ if (result && result.language) {+ return result.language;+ }+ }+ // Node.js environment+ else if (typeof process !== 'undefined' && process.versions && process.versions.node) {+ // Only load highlight.js if we haven't already+ if (!hljs) {+ try {+ // We need to dynamically require highlight.js+ // Using a try/catch since it might not be available+ hljs = require('@highlightjs/cdn-assets/highlight.min.js');+ } catch (e) {+ try {+ // Try alternative path+ hljs = require('highlight.js');+ } catch (e2) {+ console.debug("highlight.js not available in this environment, falling back to regex detection");+ }+ }+ }++ if (hljs && typeof hljs.highlightAuto === 'function') {+ const result = hljs.highlightAuto(codeSample);+ if (result && result.language) {+ return result.language;+ }+ }+ }+ } catch (e) {+ console.debug("Error using highlight.js for language detection:", e);+ }++ // Fallback to regex-based detection if highlight.js is not available or fails// Check for common language patterns in the first few linesconst firstLines = content.split('\n').slice(0, 10).join('\n');