fresh-core 0.2.11

Core types and utilities for the Fresh editor
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
//! Hook System: Event subscription and notification for plugins
//!
//! Hooks allow plugins to subscribe to editor events and react to them.

use anyhow::Result;
use std::collections::HashMap;
use std::ops::Range;
use std::path::PathBuf;

use crate::action::Action;
use crate::api::{ViewTokenWire, ViewTokenWireKind};
use crate::{BufferId, CursorId, SplitId};

/// Arguments passed to hook callbacks
#[derive(Debug, Clone, serde::Serialize)]
pub enum HookArgs {
    /// Before a file is opened
    BeforeFileOpen { path: PathBuf },

    /// After a file is successfully opened
    AfterFileOpen { buffer_id: BufferId, path: PathBuf },

    /// Before a buffer is saved to disk
    BeforeFileSave { buffer_id: BufferId, path: PathBuf },

    /// After a buffer is successfully saved
    AfterFileSave { buffer_id: BufferId, path: PathBuf },

    /// A buffer was closed
    BufferClosed { buffer_id: BufferId },

    /// Before text is inserted
    BeforeInsert {
        buffer_id: BufferId,
        position: usize,
        text: String,
    },

    /// After text was inserted
    AfterInsert {
        buffer_id: BufferId,
        position: usize,
        text: String,
        /// Byte position where the affected range starts
        affected_start: usize,
        /// Byte position where the affected range ends (after the inserted text)
        affected_end: usize,
        /// Line number where insertion occurred (0-indexed)
        start_line: usize,
        /// Line number where insertion ended (0-indexed)
        end_line: usize,
        /// Number of lines added by this insertion
        lines_added: usize,
    },

    /// Before text is deleted
    BeforeDelete {
        buffer_id: BufferId,
        range: Range<usize>,
    },

    /// After text was deleted
    AfterDelete {
        buffer_id: BufferId,
        range: Range<usize>,
        deleted_text: String,
        /// Byte position where the deletion occurred
        affected_start: usize,
        /// Length of the deleted content in bytes
        deleted_len: usize,
        /// Line number where deletion started (0-indexed)
        start_line: usize,
        /// Line number where deletion ended (0-indexed, in original buffer)
        end_line: usize,
        /// Number of lines removed by this deletion
        lines_removed: usize,
    },

    /// Cursor moved to a new position
    CursorMoved {
        buffer_id: BufferId,
        cursor_id: CursorId,
        old_position: usize,
        new_position: usize,
        /// Line number at new position (1-indexed)
        line: usize,
    },

    /// Buffer became active
    BufferActivated { buffer_id: BufferId },

    /// Buffer was deactivated
    BufferDeactivated { buffer_id: BufferId },

    /// LSP diagnostics were updated for a file
    DiagnosticsUpdated {
        /// The URI of the file that was updated
        uri: String,
        /// Number of diagnostics in the update
        count: usize,
    },

    /// Before a command/action is executed
    PreCommand { action: Action },

    /// After a command/action was executed
    PostCommand { action: Action },

    /// Editor has been idle for N milliseconds (no input)
    Idle { milliseconds: u64 },

    /// Editor is initializing
    EditorInitialized,

    /// Rendering is starting for a buffer (called once per buffer before render_line hooks)
    RenderStart { buffer_id: BufferId },

    /// A line is being rendered (called during the rendering pass)
    RenderLine {
        buffer_id: BufferId,
        line_number: usize,
        byte_start: usize,
        byte_end: usize,
        content: String,
    },

    /// Lines have changed and need processing (batched for efficiency)
    LinesChanged {
        buffer_id: BufferId,
        lines: Vec<LineInfo>,
    },

    /// Prompt input changed (user typed/edited)
    PromptChanged { prompt_type: String, input: String },

    /// Prompt was confirmed (user pressed Enter)
    PromptConfirmed {
        prompt_type: String,
        input: String,
        selected_index: Option<usize>,
    },

    /// Prompt was cancelled (user pressed Escape/Ctrl+G)
    PromptCancelled { prompt_type: String, input: String },

    /// Prompt suggestion selection changed (user navigated with Up/Down)
    PromptSelectionChanged {
        prompt_type: String,
        selected_index: usize,
    },

    /// Request keyboard shortcuts data (key, action) for the help buffer
    KeyboardShortcuts { bindings: Vec<(String, String)> },

    /// LSP find references response received
    LspReferences {
        /// The symbol name being queried
        symbol: String,
        /// The locations where the symbol is referenced
        locations: Vec<LspLocation>,
    },

    /// View transform request
    ViewTransformRequest {
        buffer_id: BufferId,
        split_id: SplitId,
        /// Byte offset of the viewport start
        viewport_start: usize,
        /// Byte offset of the viewport end
        viewport_end: usize,
        /// Base tokens (Text, Newline, Space) from the source
        tokens: Vec<ViewTokenWire>,
        /// Byte positions of all cursors in this buffer
        cursor_positions: Vec<usize>,
    },

    /// Mouse click event
    MouseClick {
        /// Column (x coordinate) in screen cells
        column: u16,
        /// Row (y coordinate) in screen cells
        row: u16,
        /// Mouse button: "left", "right", "middle"
        button: String,
        /// Modifier keys
        modifiers: String,
        /// Content area X offset
        content_x: u16,
        /// Content area Y offset
        content_y: u16,
    },

    /// Mouse move/hover event
    MouseMove {
        /// Column (x coordinate) in screen cells
        column: u16,
        /// Row (y coordinate) in screen cells
        row: u16,
        /// Content area X offset
        content_x: u16,
        /// Content area Y offset
        content_y: u16,
    },

    /// LSP server request (server -> client)
    LspServerRequest {
        /// The language/server that sent the request
        language: String,
        /// The JSON-RPC method name
        method: String,
        /// The server command used to spawn this LSP
        server_command: String,
        /// The request parameters as a JSON string
        params: Option<String>,
    },

    /// Viewport changed (scrolled or resized)
    ViewportChanged {
        split_id: SplitId,
        buffer_id: BufferId,
        top_byte: usize,
        top_line: Option<usize>,
        width: u16,
        height: u16,
    },

    /// LSP server failed to start or crashed
    LspServerError {
        /// The language that failed
        language: String,
        /// The server command that failed
        server_command: String,
        /// Error type: "not_found", "spawn_failed", "timeout", "crash"
        error_type: String,
        /// Human-readable error message
        message: String,
    },

    /// User clicked the LSP status indicator
    LspStatusClicked {
        /// The language of the current buffer
        language: String,
        /// Whether there's an active error
        has_error: bool,
    },

    /// User selected an action from an action popup
    ActionPopupResult {
        /// The popup ID
        popup_id: String,
        /// The action ID selected, or "dismissed"
        action_id: String,
    },

    /// Background process output (streaming)
    ProcessOutput {
        /// The process ID
        process_id: u64,
        /// The output data
        data: String,
    },

    /// Buffer language was changed (e.g. via "Set Language" command or Save-As)
    LanguageChanged {
        buffer_id: BufferId,
        /// The new language identifier (e.g., "markdown", "rust", "text")
        language: String,
    },
}

/// Information about a single line for the LinesChanged hook
#[derive(Debug, Clone, serde::Serialize)]
pub struct LineInfo {
    /// Line number (0-based)
    pub line_number: usize,
    /// Byte offset where the line starts in the buffer
    pub byte_start: usize,
    /// Byte offset where the line ends (exclusive)
    pub byte_end: usize,
    /// The content of the line
    pub content: String,
}

/// Location information for LSP references
#[derive(Debug, Clone, serde::Serialize)]
pub struct LspLocation {
    /// File path
    pub file: String,
    /// Line number (1-based)
    pub line: u32,
    /// Column number (1-based)
    pub column: u32,
}

/// Type for hook callbacks
pub type HookCallback = Box<dyn Fn(&HookArgs) -> bool + Send + Sync>;

/// Registry for managing hooks
pub struct HookRegistry {
    /// Map from hook name to list of callbacks
    hooks: HashMap<String, Vec<HookCallback>>,
}

impl HookRegistry {
    /// Create a new hook registry
    pub fn new() -> Self {
        Self {
            hooks: HashMap::new(),
        }
    }

    /// Add a hook callback for a specific hook name
    pub fn add_hook(&mut self, name: &str, callback: HookCallback) {
        self.hooks
            .entry(name.to_string())
            .or_default()
            .push(callback);
    }

    /// Remove all hooks for a specific name
    pub fn remove_hooks(&mut self, name: &str) {
        self.hooks.remove(name);
    }

    /// Run all hooks for a specific name
    pub fn run_hooks(&self, name: &str, args: &HookArgs) -> bool {
        if let Some(hooks) = self.hooks.get(name) {
            for callback in hooks {
                if !callback(args) {
                    return false;
                }
            }
        }
        true
    }

    /// Get count of registered callbacks for a hook
    pub fn hook_count(&self, name: &str) -> usize {
        self.hooks.get(name).map(|v| v.len()).unwrap_or(0)
    }

    /// Get all registered hook names
    pub fn hook_names(&self) -> Vec<String> {
        self.hooks.keys().cloned().collect()
    }
}

impl Default for HookRegistry {
    fn default() -> Self {
        Self::new()
    }
}

/// Convert HookArgs to a serde_json::Value for plugin communication
pub fn hook_args_to_json(args: &HookArgs) -> Result<serde_json::Value> {
    let json_value = match args {
        HookArgs::RenderStart { buffer_id } => {
            serde_json::json!({
                "buffer_id": buffer_id.0,
            })
        }
        HookArgs::RenderLine {
            buffer_id,
            line_number,
            byte_start,
            byte_end,
            content,
        } => {
            serde_json::json!({
                "buffer_id": buffer_id.0,
                "line_number": line_number,
                "byte_start": byte_start,
                "byte_end": byte_end,
                "content": content,
            })
        }
        HookArgs::BufferActivated { buffer_id } => {
            serde_json::json!({ "buffer_id": buffer_id.0 })
        }
        HookArgs::BufferDeactivated { buffer_id } => {
            serde_json::json!({ "buffer_id": buffer_id.0 })
        }
        HookArgs::DiagnosticsUpdated { uri, count } => {
            serde_json::json!({
                "uri": uri,
                "count": count,
            })
        }
        HookArgs::BufferClosed { buffer_id } => {
            serde_json::json!({ "buffer_id": buffer_id.0 })
        }
        HookArgs::CursorMoved {
            buffer_id,
            cursor_id,
            old_position,
            new_position,
            line,
        } => {
            serde_json::json!({
                "buffer_id": buffer_id.0,
                "cursor_id": cursor_id.0,
                "old_position": old_position,
                "new_position": new_position,
                "line": line,
            })
        }
        HookArgs::BeforeInsert {
            buffer_id,
            position,
            text,
        } => {
            serde_json::json!({
                "buffer_id": buffer_id.0,
                "position": position,
                "text": text,
            })
        }
        HookArgs::AfterInsert {
            buffer_id,
            position,
            text,
            affected_start,
            affected_end,
            start_line,
            end_line,
            lines_added,
        } => {
            serde_json::json!({
                "buffer_id": buffer_id.0,
                "position": position,
                "text": text,
                "affected_start": affected_start,
                "affected_end": affected_end,
                "start_line": start_line,
                "end_line": end_line,
                "lines_added": lines_added,
            })
        }
        HookArgs::BeforeDelete { buffer_id, range } => {
            serde_json::json!({
                "buffer_id": buffer_id.0,
                "start": range.start,
                "end": range.end,
            })
        }
        HookArgs::AfterDelete {
            buffer_id,
            range,
            deleted_text,
            affected_start,
            deleted_len,
            start_line,
            end_line,
            lines_removed,
        } => {
            serde_json::json!({
                "buffer_id": buffer_id.0,
                "start": range.start,
                "end": range.end,
                "deleted_text": deleted_text,
                "affected_start": affected_start,
                "deleted_len": deleted_len,
                "start_line": start_line,
                "end_line": end_line,
                "lines_removed": lines_removed,
            })
        }
        HookArgs::BeforeFileOpen { path } => {
            serde_json::json!({ "path": path.to_string_lossy() })
        }
        HookArgs::AfterFileOpen { path, buffer_id } => {
            serde_json::json!({
                "path": path.to_string_lossy(),
                "buffer_id": buffer_id.0,
            })
        }
        HookArgs::BeforeFileSave { path, buffer_id } => {
            serde_json::json!({
                "path": path.to_string_lossy(),
                "buffer_id": buffer_id.0,
            })
        }
        HookArgs::AfterFileSave { path, buffer_id } => {
            serde_json::json!({
                "path": path.to_string_lossy(),
                "buffer_id": buffer_id.0,
            })
        }
        HookArgs::PreCommand { action } => {
            serde_json::json!({ "action": format!("{:?}", action) })
        }
        HookArgs::PostCommand { action } => {
            serde_json::json!({ "action": format!("{:?}", action) })
        }
        HookArgs::Idle { milliseconds } => {
            serde_json::json!({ "milliseconds": milliseconds })
        }
        HookArgs::EditorInitialized => {
            serde_json::json!({})
        }
        HookArgs::PromptChanged { prompt_type, input } => {
            serde_json::json!({
                "prompt_type": prompt_type,
                "input": input,
            })
        }
        HookArgs::PromptConfirmed {
            prompt_type,
            input,
            selected_index,
        } => {
            serde_json::json!({
                "prompt_type": prompt_type,
                "input": input,
                "selected_index": selected_index,
            })
        }
        HookArgs::PromptCancelled { prompt_type, input } => {
            serde_json::json!({
                "prompt_type": prompt_type,
                "input": input,
            })
        }
        HookArgs::PromptSelectionChanged {
            prompt_type,
            selected_index,
        } => {
            serde_json::json!({
                "prompt_type": prompt_type,
                "selected_index": selected_index,
            })
        }
        HookArgs::KeyboardShortcuts { bindings } => {
            let entries: Vec<serde_json::Value> = bindings
                .iter()
                .map(|(key, action)| serde_json::json!({ "key": key, "action": action }))
                .collect();
            serde_json::json!({ "bindings": entries })
        }
        HookArgs::LspReferences { symbol, locations } => {
            let locs: Vec<serde_json::Value> = locations
                .iter()
                .map(|loc| {
                    serde_json::json!({
                        "file": loc.file,
                        "line": loc.line,
                        "column": loc.column,
                    })
                })
                .collect();
            serde_json::json!({ "symbol": symbol, "locations": locs })
        }
        HookArgs::LinesChanged { buffer_id, lines } => {
            let lines_json: Vec<serde_json::Value> = lines
                .iter()
                .map(|line| {
                    serde_json::json!({
                        "line_number": line.line_number,
                        "byte_start": line.byte_start,
                        "byte_end": line.byte_end,
                        "content": line.content,
                    })
                })
                .collect();
            serde_json::json!({
                "buffer_id": buffer_id.0,
                "lines": lines_json,
            })
        }
        HookArgs::ViewTransformRequest {
            buffer_id,
            split_id,
            viewport_start,
            viewport_end,
            tokens,
            cursor_positions,
        } => {
            let tokens_json: Vec<serde_json::Value> = tokens
                .iter()
                .map(|token| {
                    let kind_json = match &token.kind {
                        ViewTokenWireKind::Text(s) => serde_json::json!({ "Text": s }),
                        ViewTokenWireKind::Newline => serde_json::json!("Newline"),
                        ViewTokenWireKind::Space => serde_json::json!("Space"),
                        ViewTokenWireKind::Break => serde_json::json!("Break"),
                        ViewTokenWireKind::BinaryByte(b) => serde_json::json!({ "BinaryByte": b }),
                    };
                    serde_json::json!({
                        "source_offset": token.source_offset,
                        "kind": kind_json,
                    })
                })
                .collect();
            serde_json::json!({
                "buffer_id": buffer_id.0,
                "split_id": split_id.0,
                "viewport_start": viewport_start,
                "viewport_end": viewport_end,
                "tokens": tokens_json,
                "cursor_positions": cursor_positions,
            })
        }
        HookArgs::MouseClick {
            column,
            row,
            button,
            modifiers,
            content_x,
            content_y,
        } => {
            serde_json::json!({
                "column": column,
                "row": row,
                "button": button,
                "modifiers": modifiers,
                "content_x": content_x,
                "content_y": content_y,
            })
        }
        HookArgs::MouseMove {
            column,
            row,
            content_x,
            content_y,
        } => {
            serde_json::json!({
                "column": column,
                "row": row,
                "content_x": content_x,
                "content_y": content_y,
            })
        }
        HookArgs::LspServerRequest {
            language,
            method,
            server_command,
            params,
        } => {
            serde_json::json!({
                "language": language,
                "method": method,
                "server_command": server_command,
                "params": params,
            })
        }
        HookArgs::ViewportChanged {
            split_id,
            buffer_id,
            top_byte,
            top_line,
            width,
            height,
        } => {
            serde_json::json!({
                "split_id": split_id.0,
                "buffer_id": buffer_id.0,
                "top_byte": top_byte,
                "top_line": top_line,
                "width": width,
                "height": height,
            })
        }
        HookArgs::LspServerError {
            language,
            server_command,
            error_type,
            message,
        } => {
            serde_json::json!({
                "language": language,
                "server_command": server_command,
                "error_type": error_type,
                "message": message,
            })
        }
        HookArgs::LspStatusClicked {
            language,
            has_error,
        } => {
            serde_json::json!({
                "language": language,
                "has_error": has_error,
            })
        }
        HookArgs::ActionPopupResult {
            popup_id,
            action_id,
        } => {
            serde_json::json!({
                "popup_id": popup_id,
                "action_id": action_id,
            })
        }
        HookArgs::ProcessOutput { process_id, data } => {
            serde_json::json!({
                "process_id": process_id,
                "data": data,
            })
        }
        HookArgs::LanguageChanged {
            buffer_id,
            language,
        } => {
            serde_json::json!({
                "buffer_id": buffer_id.0,
                "language": language,
            })
        }
    };

    Ok(json_value)
}