fresh-editor 0.3.7

A lightweight, fast terminal-based text editor with LSP support and TypeScript plugins
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
//! Shared configuration types used by both schema generation and runtime.
//!
//! These types are kept in a separate module so that the schema generator
//! can import them without pulling in heavy runtime dependencies.

use std::collections::HashMap;
use std::collections::HashSet;

use schemars::JsonSchema;
use serde::{Deserialize, Serialize};

/// Constants for menu context state keys
/// These are used both in menu item `when` conditions and `checkbox` states
pub mod context_keys {
    /// True when the active buffer is a real, user-visible buffer.
    /// False when it's the synthesized placeholder kept alive by the
    /// close path with `auto_create_empty_buffer_on_last_buffer_close`
    /// disabled. Buffer-specific menu items gate on this so they don't
    /// pretend to operate on a non-existent buffer.
    pub const HAS_BUFFER: &str = "has_buffer";
    pub const LINE_NUMBERS: &str = "line_numbers";
    pub const LINE_WRAP: &str = "line_wrap";
    pub const PAGE_VIEW: &str = "page_view";
    /// Backward-compatible alias for PAGE_VIEW
    pub const COMPOSE_MODE: &str = "compose_mode";
    pub const FILE_EXPLORER: &str = "file_explorer";
    pub const MENU_BAR: &str = "menu_bar";
    pub const FILE_EXPLORER_FOCUSED: &str = "file_explorer_focused";
    pub const MOUSE_CAPTURE: &str = "mouse_capture";
    pub const MOUSE_HOVER: &str = "mouse_hover";
    pub const LSP_AVAILABLE: &str = "lsp_available";
    pub const FILE_EXPLORER_SHOW_HIDDEN: &str = "file_explorer_show_hidden";
    pub const FILE_EXPLORER_SHOW_GITIGNORED: &str = "file_explorer_show_gitignored";
    pub const HAS_SELECTION: &str = "has_selection";
    pub const CAN_COPY: &str = "can_copy";
    pub const CAN_PASTE: &str = "can_paste";
    pub const FORMATTER_AVAILABLE: &str = "formatter_available";
    pub const INLAY_HINTS: &str = "inlay_hints";
    pub const SESSION_MODE: &str = "session_mode";
    pub const VERTICAL_SCROLLBAR: &str = "vertical_scrollbar";
    pub const HORIZONTAL_SCROLLBAR: &str = "horizontal_scrollbar";
    pub const SCROLL_SYNC: &str = "scroll_sync";
    pub const HAS_SAME_BUFFER_SPLITS: &str = "has_same_buffer_splits";
    pub const KEYMAP_DEFAULT: &str = "keymap_default";
    pub const KEYMAP_EMACS: &str = "keymap_emacs";
    pub const KEYMAP_VSCODE: &str = "keymap_vscode";
    pub const KEYMAP_MACOS_GUI: &str = "keymap_macos_gui";
}

/// Configuration for process resource limits
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, JsonSchema)]
pub struct ProcessLimits {
    /// Maximum memory usage as percentage of total system memory (None = no limit)
    /// Default is 50% of total system memory
    #[serde(default)]
    pub max_memory_percent: Option<u32>,

    /// Maximum CPU usage as percentage of total CPU (None = no limit)
    /// For multi-core systems, 100% = 1 core, 200% = 2 cores, etc.
    #[serde(default)]
    pub max_cpu_percent: Option<u32>,

    /// Enable resource limiting (can be disabled per-platform)
    #[serde(default = "default_true")]
    pub enabled: bool,
}

fn default_true() -> bool {
    true
}

impl Default for ProcessLimits {
    fn default() -> Self {
        Self {
            max_memory_percent: Some(50),       // 50% of total memory
            max_cpu_percent: Some(90),          // 90% of total CPU
            enabled: cfg!(target_os = "linux"), // Only enabled on Linux by default
        }
    }
}

impl ProcessLimits {
    /// Create a new ProcessLimits with no restrictions
    pub fn unlimited() -> Self {
        Self {
            max_memory_percent: None,
            max_cpu_percent: None,
            enabled: false,
        }
    }

    /// Get the default CPU limit (90% of total CPU)
    pub fn default_cpu_limit_percent() -> u32 {
        90
    }
}

/// LSP features that can be routed to specific servers in a multi-server setup.
///
/// Features are classified as either "merged" (results from all servers are combined)
/// or "exclusive" (first eligible server wins). This classification is used by the
/// dispatch layer, not by this enum itself.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "snake_case")]
pub enum LspFeature {
    /// Diagnostics (merged: combined from all servers)
    Diagnostics,
    /// Code completion (merged: combined from all servers)
    Completion,
    /// Code actions / quick fixes (merged: combined from all servers)
    CodeAction,
    /// Document symbols (merged: combined from all servers)
    DocumentSymbols,
    /// Workspace symbols (merged: combined from all servers)
    WorkspaceSymbols,
    /// Hover information (exclusive: first eligible server wins)
    Hover,
    /// Go to definition, declaration, type definition, implementation (exclusive)
    Definition,
    /// Find references (exclusive)
    References,
    /// Document formatting and range formatting (exclusive)
    Format,
    /// Rename and prepare rename (exclusive)
    Rename,
    /// Signature help (exclusive)
    SignatureHelp,
    /// Inlay hints (exclusive)
    InlayHints,
    /// Folding ranges (exclusive)
    FoldingRange,
    /// Semantic tokens (exclusive)
    SemanticTokens,
    /// Document highlight (exclusive)
    DocumentHighlight,
}

impl LspFeature {
    /// Whether this feature produces merged results from all eligible servers.
    /// Merged features send requests to all servers and combine the results.
    /// Non-merged (exclusive) features use only the first eligible server.
    pub fn is_merged(&self) -> bool {
        matches!(
            self,
            LspFeature::Diagnostics
                | LspFeature::Completion
                | LspFeature::CodeAction
                | LspFeature::DocumentSymbols
                | LspFeature::WorkspaceSymbols
        )
    }
}

/// Feature filter for an LSP server, controlling which features it handles.
///
/// - `All`: The server handles all features (default).
/// - `Only(set)`: The server handles only the listed features.
/// - `Except(set)`: The server handles all features except the listed ones.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub enum FeatureFilter {
    #[default]
    All,
    Only(HashSet<LspFeature>),
    Except(HashSet<LspFeature>),
}

impl FeatureFilter {
    /// Check if this filter allows a given feature.
    pub fn allows(&self, feature: LspFeature) -> bool {
        match self {
            FeatureFilter::All => true,
            FeatureFilter::Only(set) => set.contains(&feature),
            FeatureFilter::Except(set) => !set.contains(&feature),
        }
    }

    /// Build a FeatureFilter from the only_features/except_features config fields.
    pub fn from_config(
        only: &Option<Vec<LspFeature>>,
        except: &Option<Vec<LspFeature>>,
    ) -> FeatureFilter {
        match (only, except) {
            (Some(only), _) => FeatureFilter::Only(only.iter().copied().collect()),
            (_, Some(except)) => FeatureFilter::Except(except.iter().copied().collect()),
            _ => FeatureFilter::All,
        }
    }
}

/// Wrapper for deserializing a per-language LSP config that can be either
/// a single server object or an array of server objects.
///
/// ```json
/// { "lsp": { "rust": { "command": "rust-analyzer" } } }          // single
/// { "lsp": { "python": [{ "command": "pyright" }, { "command": "ruff" }] } }  // multi
/// ```
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(untagged)]
pub enum LspLanguageConfig {
    /// Multiple servers for this language (array form)
    Multi(Vec<LspServerConfig>),
    /// A single server for this language (object form)
    Single(Box<LspServerConfig>),
}

/// Custom JsonSchema: always advertise the canonical array form so the settings
/// UI renders a structured array editor. The `#[serde(untagged)]` on the enum
/// still accepts both single-object and array forms during deserialization.
impl JsonSchema for LspLanguageConfig {
    fn schema_name() -> std::borrow::Cow<'static, str> {
        std::borrow::Cow::Borrowed("LspLanguageConfig")
    }

    fn json_schema(generator: &mut schemars::SchemaGenerator) -> schemars::Schema {
        schemars::json_schema!({
            "description": "One or more LSP server configs for this language.\nAccepts both a single object and an array for backwards compatibility.",
            "type": "array",
            "items": generator.subschema_for::<LspServerConfig>()
        })
    }
}

impl LspLanguageConfig {
    /// Convert to a Vec of server configs.
    pub fn into_vec(self) -> Vec<LspServerConfig> {
        match self {
            LspLanguageConfig::Single(c) => vec![*c],
            LspLanguageConfig::Multi(v) => v,
        }
    }

    /// Get a reference as a slice of server configs.
    pub fn as_slice(&self) -> &[LspServerConfig] {
        match self {
            LspLanguageConfig::Single(c) => std::slice::from_ref(c.as_ref()),
            LspLanguageConfig::Multi(v) => v,
        }
    }

    /// Get a mutable reference as a slice of server configs.
    pub fn as_mut_slice(&mut self) -> &mut [LspServerConfig] {
        match self {
            LspLanguageConfig::Single(c) => std::slice::from_mut(c),
            LspLanguageConfig::Multi(v) => v,
        }
    }
}

impl Default for LspLanguageConfig {
    fn default() -> Self {
        LspLanguageConfig::Single(Box::default())
    }
}

/// LSP server configuration
#[derive(Debug, Clone, Default, Serialize, Deserialize, JsonSchema)]
#[schemars(extend("x-display-field" = "/command"))]
pub struct LspServerConfig {
    /// Command to spawn the server.
    /// Required when enabled=true, ignored when enabled=false.
    #[serde(default)]
    #[schemars(extend("x-order" = 1))]
    pub command: String,

    /// Whether the server is enabled
    #[serde(default = "default_true")]
    #[schemars(extend("x-order" = 2))]
    pub enabled: bool,

    /// Display name for this server (e.g., "tsserver", "eslint").
    /// Defaults to the command basename if not specified.
    #[serde(default)]
    #[schemars(extend("x-order" = 3))]
    pub name: Option<String>,

    /// Arguments to pass to the server
    #[serde(default)]
    #[schemars(extend("x-order" = 4))]
    pub args: Vec<String>,

    /// Whether to auto-start this LSP server when opening matching files
    /// If false (default), the server must be started manually via command palette
    #[serde(default)]
    #[schemars(extend("x-order" = 5))]
    pub auto_start: bool,

    /// File/directory names to search for when detecting the workspace root.
    /// The editor walks upward from the opened file's directory looking for
    /// any of these markers. The first directory containing a match becomes
    /// the workspace root sent to the LSP server.
    ///
    /// If empty, falls back to `[".git"]` as a universal marker.
    /// If the walk reaches a filesystem boundary without a match, uses the
    /// file's parent directory (never cwd or $HOME).
    #[serde(default)]
    #[schemars(extend("x-order" = 6))]
    pub root_markers: Vec<String>,

    /// Environment variables to set for the LSP server process.
    /// These are added to (or override) the inherited parent environment.
    #[serde(default)]
    #[schemars(extend("x-section" = "Advanced", "x-order" = 10))]
    pub env: HashMap<String, String>,

    /// Override the LSP languageId sent in textDocument/didOpen based on file extension.
    /// Maps file extension (without dot) to LSP language ID string.
    /// For example: `{"tsx": "typescriptreact", "jsx": "javascriptreact"}`
    #[serde(default)]
    #[schemars(extend("x-section" = "Advanced", "x-order" = 11))]
    pub language_id_overrides: HashMap<String, String>,

    /// Custom initialization options to send to the server
    /// These are passed in the `initializationOptions` field of the LSP Initialize request
    #[serde(default)]
    #[schemars(extend("x-section" = "Advanced", "x-order" = 12))]
    pub initialization_options: Option<serde_json::Value>,

    /// Restrict this server to only handle the listed features.
    /// Mutually exclusive with `except_features`. If neither is set, all features are handled.
    #[serde(default)]
    #[schemars(extend("x-section" = "Advanced", "x-order" = 13))]
    pub only_features: Option<Vec<LspFeature>>,

    /// Exclude the listed features from this server.
    /// Mutually exclusive with `only_features`. If neither is set, all features are handled.
    #[serde(default)]
    #[schemars(extend("x-section" = "Advanced", "x-order" = 14))]
    pub except_features: Option<Vec<LspFeature>>,

    /// Process resource limits (memory and CPU)
    #[serde(default)]
    #[schemars(extend("x-section" = "Advanced", "x-order" = 15))]
    pub process_limits: ProcessLimits,
}

impl LspServerConfig {
    /// Merge this config with defaults, using default values for empty/unset fields.
    ///
    /// This is used when loading configs where fields like `command` may be empty
    /// (serde's default) because they weren't specified in the user's config file.
    /// Resolve the display name for this server.
    /// Returns the explicit name if set, otherwise the basename of the command.
    pub fn display_name(&self) -> String {
        if let Some(ref name) = self.name {
            return name.clone();
        }
        // Use command basename
        std::path::Path::new(&self.command)
            .file_name()
            .and_then(|n| n.to_str())
            .unwrap_or(&self.command)
            .to_string()
    }

    /// Build the FeatureFilter for this server config.
    pub fn feature_filter(&self) -> FeatureFilter {
        FeatureFilter::from_config(&self.only_features, &self.except_features)
    }

    /// Merge this config with defaults, using default values for empty/unset fields.
    ///
    /// This is used when loading configs where fields like `command` may be empty
    /// (serde's default) because they weren't specified in the user's config file.
    pub fn merge_with_defaults(self, defaults: &LspServerConfig) -> LspServerConfig {
        LspServerConfig {
            name: self.name.or_else(|| defaults.name.clone()),
            command: if self.command.is_empty() {
                defaults.command.clone()
            } else {
                self.command
            },
            args: if self.args.is_empty() {
                defaults.args.clone()
            } else {
                self.args
            },
            enabled: self.enabled,
            auto_start: self.auto_start,
            process_limits: self.process_limits,
            only_features: self
                .only_features
                .or_else(|| defaults.only_features.clone()),
            except_features: self
                .except_features
                .or_else(|| defaults.except_features.clone()),
            initialization_options: self
                .initialization_options
                .or_else(|| defaults.initialization_options.clone()),
            env: {
                let mut merged = defaults.env.clone();
                merged.extend(self.env);
                merged
            },
            language_id_overrides: {
                let mut merged = defaults.language_id_overrides.clone();
                merged.extend(self.language_id_overrides);
                merged
            },
            root_markers: if self.root_markers.is_empty() {
                defaults.root_markers.clone()
            } else {
                self.root_markers
            },
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::collections::HashSet;

    #[test]
    fn test_lsp_feature_is_merged() {
        assert!(LspFeature::Diagnostics.is_merged());
        assert!(LspFeature::Completion.is_merged());
        assert!(LspFeature::CodeAction.is_merged());
        assert!(LspFeature::DocumentSymbols.is_merged());
        assert!(LspFeature::WorkspaceSymbols.is_merged());

        assert!(!LspFeature::Hover.is_merged());
        assert!(!LspFeature::Definition.is_merged());
        assert!(!LspFeature::References.is_merged());
        assert!(!LspFeature::Format.is_merged());
        assert!(!LspFeature::Rename.is_merged());
        assert!(!LspFeature::SignatureHelp.is_merged());
        assert!(!LspFeature::InlayHints.is_merged());
        assert!(!LspFeature::FoldingRange.is_merged());
        assert!(!LspFeature::SemanticTokens.is_merged());
        assert!(!LspFeature::DocumentHighlight.is_merged());
    }

    #[test]
    fn test_feature_filter_all() {
        let filter = FeatureFilter::All;
        assert!(filter.allows(LspFeature::Hover));
        assert!(filter.allows(LspFeature::Diagnostics));
        assert!(filter.allows(LspFeature::Completion));
        assert!(filter.allows(LspFeature::Rename));
    }

    #[test]
    fn test_feature_filter_only() {
        let mut set = HashSet::new();
        set.insert(LspFeature::Diagnostics);
        set.insert(LspFeature::Completion);
        let filter = FeatureFilter::Only(set);

        assert!(filter.allows(LspFeature::Diagnostics));
        assert!(filter.allows(LspFeature::Completion));
        assert!(!filter.allows(LspFeature::Hover));
        assert!(!filter.allows(LspFeature::Definition));
    }

    #[test]
    fn test_feature_filter_except() {
        let mut set = HashSet::new();
        set.insert(LspFeature::Format);
        set.insert(LspFeature::Rename);
        let filter = FeatureFilter::Except(set);

        assert!(filter.allows(LspFeature::Hover));
        assert!(filter.allows(LspFeature::Diagnostics));
        assert!(!filter.allows(LspFeature::Format));
        assert!(!filter.allows(LspFeature::Rename));
    }

    #[test]
    fn test_feature_filter_from_config_none() {
        let filter = FeatureFilter::from_config(&None, &None);
        assert!(matches!(filter, FeatureFilter::All));
    }

    #[test]
    fn test_feature_filter_from_config_only() {
        let only = Some(vec![LspFeature::Diagnostics, LspFeature::Completion]);
        let filter = FeatureFilter::from_config(&only, &None);
        assert!(filter.allows(LspFeature::Diagnostics));
        assert!(filter.allows(LspFeature::Completion));
        assert!(!filter.allows(LspFeature::Hover));
    }

    #[test]
    fn test_feature_filter_from_config_except() {
        let except = Some(vec![LspFeature::Format]);
        let filter = FeatureFilter::from_config(&None, &except);
        assert!(filter.allows(LspFeature::Hover));
        assert!(!filter.allows(LspFeature::Format));
    }

    #[test]
    fn test_feature_filter_default() {
        let filter = FeatureFilter::default();
        assert!(matches!(filter, FeatureFilter::All));
    }
}