TextMateLib 1.0
Modern C++ implementation of the TextMate syntax highlighting engine
Loading...
Searching...
No Matches
session_c_api.h
1#ifndef TEXTMATELIB_SESSION_C_API_H
2#define TEXTMATELIB_SESSION_C_API_H
3
4#include "tml_export.h"
5
6#ifdef __cplusplus
7extern "C" {
8#endif
9
10#include <stdint.h>
11
12// ============================================================================
13// Session API - High-Level Stateful Tokenization
14// ============================================================================
15//
16// The Session API provides a stateful, incremental tokenization interface
17// designed for text editors. It manages line caching and state tracking
18// internally, allowing clients to work with high-level edit operations
19// (add, edit, remove) rather than low-level tokenization.
20//
21// Key Design Goals:
22// 1. Incremental tokenization - only retokenize affected lines
23// 2. Automatic state cascading - stop when state stabilizes
24// 3. Memory safety - reference counting prevents leaks
25// 4. Automatic cleanup - expired sessions are cleaned up
26//
27
28// Opaque session handle
29typedef uint64_t TextMateSession;
30
31// Represents a cached line with tokens and state
32typedef struct {
33 TextMateToken* tokens; // Array of tokens for this line
34 int32_t tokenCount; // Number of tokens
35 TextMateStateStack state; // State at end of line
36 uint64_t version; // Version number for change tracking
37} TextMateSessionLine;
38
39// Result structure for batch queries
40typedef struct {
41 TextMateSessionLine* lines; // Array of line results
42 int32_t lineCount; // Number of lines returned
43} TextMateSessionLinesResult;
44
45// ============================================================================
46// Session Lifecycle
47// ============================================================================
48
49// Create a new session for incremental tokenization
50//
51// Args:
52// grammar: The grammar to use for tokenization (must not be NULL)
53//
54// Returns:
55// Session ID on success, 0 on error
56//
57// Notes:
58// - Session starts with INITIAL state
59// - Reference count is set to 1 (ownership transferred to caller)
60// - Must call textmate_session_dispose() to release
61TML_API TextMateSession textmate_session_create(TextMateGrammar grammar);
62
63// Increment reference count for a session
64//
65// Args:
66// session: Session ID from textmate_session_create()
67//
68// Notes:
69// - Used when storing session handles in multiple places
70// - Must be paired with textmate_session_release()
71TML_API void textmate_session_retain(TextMateSession session);
72
73// Decrement reference count for a session
74//
75// Args:
76// session: Session ID
77//
78// Notes:
79// - When reference count reaches 0, session is destroyed
80// - Safe to call multiple times (decrements until 0)
81// - Finalizer safety net: finalizer calls this if not explicitly called
82TML_API void textmate_session_release(TextMateSession session);
83
84// Dispose a session explicitly
85//
86// Args:
87// session: Session ID
88//
89// Notes:
90// - Shorthand for textmate_session_release() (decrements refcount)
91// - Recommended way to dispose for API clarity
92// - Should be called from IDisposable.Dispose() in C#
93TML_API void textmate_session_dispose(TextMateSession session);
94
95// ============================================================================
96// Session State Management
97// ============================================================================
98
99// Set the complete document lines (initializes session)
100//
101// Args:
102// session: Session ID
103// lines: Array of line strings
104// lineCount: Number of lines
105//
106// Returns:
107// 0 on success, non-zero on error
108//
109// Notes:
110// - Clears existing cache and tokenizes all lines
111// - Uses initial state for first line
112// - Cascades state naturally between lines
113TML_API int textmate_session_set_lines(
114 TextMateSession session,
115 const char** lines,
116 int32_t lineCount
117);
118
119// Get current number of lines in session
120TML_API int32_t textmate_session_get_line_count(TextMateSession session);
121
122// ============================================================================
123// Incremental Tokenization Operations
124// ============================================================================
125
126// Edit (replace) a range of lines and retokenize
127//
128// Args:
129// session: Session ID
130// lines: New line content array
131// lineCount: Number of lines in array
132// startIndex: 0-based index of first line to replace
133// replaceCount: Number of existing lines to replace
134//
135// Returns:
136// 0 on success, non-zero on error
137//
138// Behavior:
139// 1. Replaces lines[startIndex:startIndex+replaceCount] with new lines
140// 2. Invalidates cached tokens from startIndex onwards
141// 3. Retokenizes from startIndex, cascading state until stable
142// 4. Stops early when state matches expected (incremental optimization)
143//
144// Example (user edits line 50):
145// textmate_session_edit(session, newLines, 1, 50, 1);
146// // Retokenizes line 50 and cascades forward until state stabilizes
147TML_API int textmate_session_edit(
148 TextMateSession session,
149 const char** lines,
150 int32_t lineCount,
151 int32_t startIndex,
152 int32_t replaceCount
153);
154
155// Add (insert) new lines at specified position
156//
157// Args:
158// session: Session ID
159// lines: New line content array to insert
160// lineCount: Number of lines to insert
161// insertIndex: 0-based position to insert at
162//
163// Returns:
164// 0 on success, non-zero on error
165//
166// Behavior:
167// 1. Shifts all lines at insertIndex and beyond down by lineCount
168// 2. Inserts new lines at insertIndex
169// 3. Invalidates cache from insertIndex onwards
170// 4. Retokenizes new lines, cascading forward
171//
172// Example (user pastes 5 lines at line 100):
173// textmate_session_add(session, pastedLines, 5, 100);
174TML_API int textmate_session_add(
175 TextMateSession session,
176 const char** lines,
177 int32_t lineCount,
178 int32_t insertIndex
179);
180
181// Remove (delete) a range of lines
182//
183// Args:
184// session: Session ID
185// startIndex: 0-based index of first line to remove
186// removeCount: Number of lines to remove
187//
188// Returns:
189// 0 on success, non-zero on error
190//
191// Behavior:
192// 1. Removes lines[startIndex:startIndex+removeCount]
193// 2. Shifts remaining lines up
194// 3. Invalidates cache from startIndex onwards
195// 4. Retokenizes forward until state stabilizes
196//
197// Example (user deletes 3 lines starting at line 50):
198// textmate_session_remove(session, 50, 3);
199TML_API int textmate_session_remove(
200 TextMateSession session,
201 int32_t startIndex,
202 int32_t removeCount
203);
204
205// ============================================================================
206// Query Operations
207// ============================================================================
208
209// Get cached tokens for a single line
210//
211// Args:
212// session: Session ID
213// lineIndex: 0-based line number
214//
215// Returns:
216// Result structure with tokens, or empty result if line not cached
217//
218// Notes:
219// - Returns cached tokens without retokenization
220// - Returns empty if line hasn't been tokenized yet
221// - Token pointers are valid until next edit operation
222TML_API TextMateTokenizeResult* textmate_session_get_line_tokens(
223 TextMateSession session,
224 int32_t lineIndex
225);
226
227// Get cached state for a single line (state at end of line)
228//
229// Args:
230// session: Session ID
231// lineIndex: 0-based line number
232//
233// Returns:
234// State stack, or NULL if line not tokenized
235//
236// Notes:
237// - Useful for external state analysis
238// - State is valid until next edit operation
239TML_API TextMateStateStack textmate_session_get_line_state(
240 TextMateSession session,
241 int32_t lineIndex
242);
243
244// Get tokens for a range of lines in a single call
245//
246// Args:
247// session: Session ID
248// startIndex: 0-based start line
249// endIndex: 0-based end line (inclusive)
250//
251// Returns:
252// Result array with all line tokens and states
253//
254// Notes:
255// - More efficient than multiple get_line_tokens() calls
256// - Useful for rendering screen buffers
257// - Must be freed with textmate_session_free_lines_result()
258TML_API TextMateSessionLinesResult* textmate_session_get_tokens_range(
259 TextMateSession session,
260 int32_t startIndex,
261 int32_t endIndex
262);
263
264// Free query result
265TML_API void textmate_session_free_tokens_result(
267);
268
269// Free batch query result
270TML_API void textmate_session_free_lines_result(
271 TextMateSessionLinesResult* result
272);
273
274// ============================================================================
275// Maintenance Operations
276// ============================================================================
277
278// Invalidate cached tokens for a range of lines
279//
280// Args:
281// session: Session ID
282// startIndex: 0-based start line
283// endIndex: 0-based end line (inclusive, -1 for end of file)
284//
285// Notes:
286// - Forces retokenization on next query
287// - Useful if grammar changed or external state modified
288// - Automatically called by edit/add/remove operations
289TML_API void textmate_session_invalidate_range(
290 TextMateSession session,
291 int32_t startIndex,
292 int32_t endIndex
293);
294
295// Clear entire session cache (but keep lines)
296//
297// Args:
298// session: Session ID
299//
300// Notes:
301// - Resets all cached tokens and states
302// - Useful for grammar changes
303// - Document structure preserved
304TML_API void textmate_session_clear_cache(TextMateSession session);
305
306// Cleanup expired sessions (automatic memory management)
307//
308// Args:
309// maxAgeMs: Remove sessions older than this (in milliseconds)
310//
311// Notes:
312// - Called periodically (e.g., every 100 operations)
313// - Part of automatic cleanup defense layer
314// - Safe to call frequently (low overhead)
315// - Helps prevent leaks from abandoned sessions
316TML_API void textmate_session_cleanup_expired(int32_t maxAgeMs);
317
318// Get session metadata
319//
320// Returns version/age info (useful for debugging, optional)
321typedef struct {
322 uint64_t createdAtMs; // Timestamp of creation
323 uint32_t referenceCount; // Current reference count
324 int32_t lineCount; // Current line count
325 int32_t cachedLineCount; // Number of cached lines
326 uint64_t memoryUsageBytes; // Approximate memory usage
327} TextMateSessionMetadata;
328
329TML_API TextMateSessionMetadata textmate_session_get_metadata(
330 TextMateSession session
331);
332
333#ifdef __cplusplus
334}
335#endif
336
337#endif // TEXTMATELIB_SESSION_C_API_H
void * TextMateGrammar
Handle to a grammar definition for a specific language.
Definition c_api.h:38
void * TextMateStateStack
Handle to a parsing state stack (immutable, used for incremental tokenization)
Definition c_api.h:41
Represents a single token in tokenized text.
Definition c_api.h:58
Result from tokenizing a single line with decoded tokens.
Definition c_api.h:72