TextMateLib 1.0
Modern C++ implementation of the TextMate syntax highlighting engine
Loading...
Searching...
No Matches
syntax_highlighter.h
1#ifndef TEXTMATELIB_SYNTAX_HIGHLIGHTER_H
2#define TEXTMATELIB_SYNTAX_HIGHLIGHTER_H
3
4#include "types.h"
5#include "session.h"
6#include "theme.h"
7#include "grammar.h"
8#include <string>
9#include <vector>
10#include <memory>
11#include <cstdint>
12#include <map>
13
14namespace tml {
15
16// Forward declarations
17class SyntaxHighlighter;
18class HighlighterCache;
19
20// HighlightedToken represents a single token with complete styling information
21struct HighlightedToken {
22 int startIndex; // Character position in line where token starts
23 int endIndex; // Character position in line where token ends
24 std::vector<std::string> scopes; // Scope path (e.g., "source.js string.quoted.double")
25
26 // Applied styling from theme
27 std::string foregroundColor; // Hex color (#RRGGBB) or color name
28 std::string backgroundColor; // Hex color or empty string
29 int fontStyle; // Combination of FontStyle flags (bold, italic, underline, strikethrough)
30
31 // Metadata
32 StandardTokenType tokenType; // Token classification: Comment, String, RegEx, Other
33 std::string debugInfo; // Debug information (scope chain, etc.)
34
35 HighlightedToken()
36 : startIndex(0),
37 endIndex(0),
38 fontStyle(static_cast<int>(FontStyle::None)),
39 tokenType(StandardTokenType::Other) {}
40};
41
42// HighlightedLine represents complete highlighting information for a single line
43struct HighlightedLine {
44 int lineIndex; // Line number in document
45 std::string content; // The actual line content
46 std::vector<HighlightedToken> tokens; // Tokens with applied styling
47 bool isComplete; // Whether tokenization completed without timeout
48 uint64_t version; // Version number for cache invalidation
49
50 HighlightedLine()
51 : lineIndex(-1),
52 isComplete(true),
53 version(0) {}
54};
55
56// SyntaxHighlightingMetadata provides debugging and performance information
57struct SyntaxHighlightingMetadata {
58 uint64_t sessionId; // Unique session identifier
59 int lineCount; // Total lines in document
60 int cachedLineCount; // Number of cached highlighted lines
61
62 // Performance metrics
63 double averageLineTokenizationMs; // Average tokenization time per line
64 int64_t lastUpdateMs; // Timestamp of last update
65
66 // Theme information
67 std::string themeName; // Name of active theme
68 int themeColorCount; // Number of colors in theme
69
70 SyntaxHighlightingMetadata()
71 : sessionId(0),
72 lineCount(0),
73 cachedLineCount(0),
74 averageLineTokenizationMs(0.0),
75 lastUpdateMs(0),
76 themeColorCount(0) {}
77};
78
79// Main SyntaxHighlighter class
80// Combines Session API (incremental tokenization) with Theme system (color/style application)
81// Provides convenient high-level interface for text editors to get syntax-highlighted content
82class SyntaxHighlighter {
83private:
84 // Core components
85 std::shared_ptr<IGrammar> grammar; // Grammar for tokenization
86 Theme* theme; // Theme for styling (referenced, not owned)
87 std::shared_ptr<SessionImpl> session; // Session for incremental tokenization with state management
88 std::unique_ptr<HighlighterCache> cache; // Optional cache for highlighted lines
89
90 // Performance tracking
91 uint64_t createdAtMs;
92 uint64_t lastUpdateMs;
93
94 // Helper methods
95
96 /// Convert a single IToken to HighlightedToken by applying theme styling
97 /// @param token Raw token from tokenization
98 /// @return HighlightedToken with resolved colors and styles
99 HighlightedToken tokenToHighlighted(const IToken& token);
100
101 /// Build scope stack from token scopes
102 /// @param scopes Vector of scope names
103 /// @return ScopeStack for theme matching
104 ScopeStack* buildScopeStack(const std::vector<std::string>& scopes);
105
106 /// Get current timestamp in milliseconds
107 static uint64_t getCurrentTimeMs();
108
109public:
110 // ============================================================================
111 // Lifecycle
112 // ============================================================================
113
114 /// Create a new SyntaxHighlighter
115 /// @param gram IGrammar for tokenization
116 /// @param thm Theme for coloring and styling
117 /// @param enableCache Enable optional line caching (default: true)
118 SyntaxHighlighter(
119 std::shared_ptr<IGrammar> gram,
120 Theme* thm,
121 bool enableCache = true
122 );
123
124 ~SyntaxHighlighter();
125
126 // Delete copy operations (session has internal state)
127 SyntaxHighlighter(const SyntaxHighlighter&) = delete;
128 SyntaxHighlighter& operator=(const SyntaxHighlighter&) = delete;
129
130 // Allow move operations
131 SyntaxHighlighter(SyntaxHighlighter&&) noexcept = default;
132 SyntaxHighlighter& operator=(SyntaxHighlighter&&) noexcept = default;
133
134 // ============================================================================
135 // Document Management
136 // ============================================================================
137
138 /// Load a complete document
139 /// @param lines Document lines
140 void setDocument(const std::vector<std::string>& lines);
141
142 /// Edit a single line
143 /// @param lineIndex Line to edit
144 /// @param newContent New content for the line
145 void editLine(int lineIndex, const std::string& newContent);
146
147 /// Insert lines at specified position
148 /// @param startIndex Insert position
149 /// @param lines Lines to insert
150 void insertLines(int startIndex, const std::vector<std::string>& lines);
151
152 /// Remove lines
153 /// @param startIndex Start of removal
154 /// @param count Number of lines to remove
155 void removeLines(int startIndex, int count);
156
157 /// Get current line count
158 int getLineCount() const;
159
160 // ============================================================================
161 // Querying Highlighted Content
162 // ============================================================================
163
164 /// Get syntax-highlighted version of a single line
165 /// Returns fully resolved colors, fonts, and scope information
166 /// @param lineIndex Line to highlight
167 /// @return HighlightedLine with complete styling
168 HighlightedLine getHighlightedLine(int lineIndex);
169
170 /// Get syntax-highlighted version of a line range (batch query)
171 /// More efficient than calling getHighlightedLine multiple times
172 /// @param startIndex Start line (inclusive)
173 /// @param endIndex End line (inclusive)
174 /// @return Vector of HighlightedLine structs
175 std::vector<HighlightedLine> getHighlightedRange(int startIndex, int endIndex);
176
177 /// Get raw tokens for a line (without theme styling)
178 /// Useful for lower-level access or custom rendering
179 /// @param lineIndex Line to tokenize
180 /// @return Vector of IToken with scope information
181 std::vector<IToken> getLineTokens(int lineIndex);
182
183 // ============================================================================
184 // Theme Management
185 // ============================================================================
186
187 /// Switch to a different theme
188 /// Invalidates all cached highlighting (will be recomputed on next query)
189 /// @param newTheme New Theme to apply
190 void setTheme(Theme* newTheme);
191
192 /// Get the currently active theme
193 /// @return Pointer to active Theme
194 Theme* getTheme() const;
195
196 // ============================================================================
197 // Cache Management
198 // ============================================================================
199
200 /// Clear all cached highlighted lines
201 void clearCache();
202
203 /// Invalidate cached highlighting for a specific line range
204 /// Forces recomputation on next query
205 /// @param startIndex Start line
206 /// @param endIndex End line
207 void invalidateCacheRange(int startIndex, int endIndex);
208
209 // ============================================================================
210 // Debugging & Monitoring
211 // ============================================================================
212
213 /// Get debugging and performance metadata
214 /// @return SyntaxHighlightingMetadata with statistics
215 SyntaxHighlightingMetadata getMetadata() const;
216
217 /// Get the underlying SessionImpl (for advanced usage)
218 /// @return Pointer to internal SessionImpl
219 SessionImpl* getSession() const;
220};
221
222// Optional cache class for highlighted lines
223// Improves performance when repeatedly querying the same lines
224class HighlighterCache {
225private:
226 struct CachedEntry {
227 HighlightedLine line;
228 uint64_t version;
229 };
230
231 std::map<int, CachedEntry> lineCache;
232
233public:
234 HighlighterCache() = default;
235 ~HighlighterCache() = default;
236
237 // Delete copy operations
238 HighlighterCache(const HighlighterCache&) = delete;
239 HighlighterCache& operator=(const HighlighterCache&) = delete;
240
241 /// Check if a line is cached
242 /// @param lineIndex Line to check
243 /// @param version Current version number (for validation)
244 /// @return Cached HighlightedLine or nullptr if not cached/invalid
245 HighlightedLine* getCachedLine(int lineIndex, uint64_t version);
246
247 /// Cache a highlighted line
248 /// @param line HighlightedLine to cache
249 /// @param version Version number
250 void cacheLine(const HighlightedLine& line, uint64_t version);
251
252 /// Invalidate cache for a specific line
253 /// @param lineIndex Line to invalidate
254 void invalidateLine(int lineIndex);
255
256 /// Invalidate cache for a range
257 /// @param startIndex Start line
258 /// @param endIndex End line
259 void invalidateRange(int startIndex, int endIndex);
260
261 /// Clear entire cache
262 void clear();
263
264 /// Get cache statistics
265 size_t getCachedLineCount() const;
266};
267
268} // namespace tml
269
270#endif // TEXTMATELIB_SYNTAX_HIGHLIGHTER_H
FontStyle
Font styling attributes (italic, bold, underline, strikethrough)
Definition types.h:159
StandardTokenType
Standard TextMate token type for syntax classification.
Definition types.h:136
@ Other
Not a recognized standard type.
Core type definitions and interfaces for TextMateLib.