aboutsummaryrefslogtreecommitdiff
path: root/helix-term/src/ui/statusline.rs
blob: 2939a257328a4e0b7b9f96f5b4d1029e599d70e8 (plain) (blame)
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
use helix_core::{coords_at_pos, encoding, Position};
use helix_lsp::lsp::DiagnosticSeverity;
use helix_view::document::DEFAULT_LANGUAGE_NAME;
use helix_view::{
    document::{Mode, SCRATCH_BUFFER_NAME},
    graphics::Rect,
    Document, Editor, View,
};

use crate::ui::ProgressSpinners;

use helix_view::editor::StatusLineElement as StatusLineElementID;
use tui::buffer::Buffer as Surface;
use tui::text::{Span, Spans};

pub struct RenderContext<'a> {
    pub editor: &'a Editor,
    pub doc: &'a Document,
    pub view: &'a View,
    pub focused: bool,
    pub spinners: &'a ProgressSpinners,
}

impl<'a> RenderContext<'a> {
    pub fn new(
        editor: &'a Editor,
        doc: &'a Document,
        view: &'a View,
        focused: bool,
        spinners: &'a ProgressSpinners,
    ) -> Self {
        RenderContext {
            editor,
            doc,
            view,
            focused,
            spinners,
        }
    }
}

pub fn render(context: &mut RenderContext, viewport: Rect, surface: &mut Surface) {
    let base_style = if context.focused {
        context.editor.theme.get("ui.statusline")
    } else {
        context.editor.theme.get("ui.statusline.inactive")
    };

    surface.set_style(viewport.with_height(1), base_style);

    let statusline = render_statusline(context, viewport.width as usize);

    surface.set_spans(
        viewport.x,
        viewport.y,
        &statusline,
        statusline.width() as u16,
    );
}

pub fn render_statusline<'a>(context: &mut RenderContext, width: usize) -> Spans<'a> {
    let config = context.editor.config();

    let element_ids = &config.statusline.left;
    let mut left = element_ids
        .iter()
        .map(|element_id| get_render_function(*element_id))
        .flat_map(|render| render(context).0)
        .collect::<Vec<Span>>();

    let element_ids = &config.statusline.center;
    let mut center = element_ids
        .iter()
        .map(|element_id| get_render_function(*element_id))
        .flat_map(|render| render(context).0)
        .collect::<Vec<Span>>();

    let element_ids = &config.statusline.right;
    let mut right = element_ids
        .iter()
        .map(|element_id| get_render_function(*element_id))
        .flat_map(|render| render(context).0)
        .collect::<Vec<Span>>();

    let left_area_width: usize = left.iter().map(|s| s.width()).sum();
    let center_area_width: usize = center.iter().map(|s| s.width()).sum();
    let right_area_width: usize = right.iter().map(|s| s.width()).sum();

    let min_spacing_between_areas = 1usize;
    let sides_space_required = left_area_width + right_area_width + min_spacing_between_areas;
    let total_space_required = sides_space_required + center_area_width + min_spacing_between_areas;

    let mut statusline: Vec<Span> = vec![];

    if center_area_width > 0 && total_space_required <= width {
        // SAFETY: this subtraction cannot underflow because `left_area_width + center_area_width + right_area_width`
        // is smaller than `total_space_required`, which is smaller than `width` in this branch.
        let total_spacers = width - (left_area_width + center_area_width + right_area_width);
        // This is how much padding space it would take on either side to align the center area to the middle.
        let center_margin = (width - center_area_width) / 2;
        let left_spacers = if left_area_width < center_margin && right_area_width < center_margin {
            // Align the center area to the middle if there is enough space on both sides.
            center_margin - left_area_width
        } else {
            // Otherwise split the available space evenly and use it as margin.
            // The center element won't be aligned to the middle but it will be evenly
            // spaced between the left and right areas.
            total_spacers / 2
        };
        let right_spacers = total_spacers - left_spacers;

        statusline.append(&mut left);
        statusline.push(" ".repeat(left_spacers).into());
        statusline.append(&mut center);
        statusline.push(" ".repeat(right_spacers).into());
        statusline.append(&mut right);
    } else if right_area_width > 0 && sides_space_required <= width {
        let side_areas_width = left_area_width + right_area_width;
        statusline.append(&mut left);
        statusline.push(" ".repeat(width - side_areas_width).into());
        statusline.append(&mut right);
    } else if left_area_width <= width {
        statusline.append(&mut left);
    }

    statusline.into()
}

fn get_render_function<'a>(
    element_id: StatusLineElementID,
) -> impl Fn(&RenderContext) -> Spans<'a> {
    match element_id {
        helix_view::editor::StatusLineElement::Mode => render_mode,
        helix_view::editor::StatusLineElement::Spinner => render_lsp_spinner,
        helix_view::editor::StatusLineElement::FileBaseName => render_file_base_name,
        helix_view::editor::StatusLineElement::FileName => render_file_name,
        helix_view::editor::StatusLineElement::FileAbsolutePath => render_file_absolute_path,
        helix_view::editor::StatusLineElement::FileModificationIndicator => {
            render_file_modification_indicator
        }
        helix_view::editor::StatusLineElement::ReadOnlyIndicator => render_read_only_indicator,
        helix_view::editor::StatusLineElement::FileEncoding => render_file_encoding,
        helix_view::editor::StatusLineElement::FileLineEnding => render_file_line_ending,
        helix_view::editor::StatusLineElement::FileType => render_file_type,
        helix_view::editor::StatusLineElement::Diagnostics => render_diagnostics,
        helix_view::editor::StatusLineElement::WorkspaceDiagnostics => render_workspace_diagnostics,
        helix_view::editor::StatusLineElement::Selections => render_selections,
        helix_view::editor::StatusLineElement::PrimarySelectionLength => {
            render_primary_selection_length
        }
        helix_view::editor::StatusLineElement::Position => render_position,
        helix_view::editor::StatusLineElement::PositionPercentage => render_position_percentage,
        helix_view::editor::StatusLineElement::TotalLineNumbers => render_total_line_numbers,
        helix_view::editor::StatusLineElement::Separator => render_separator,
        helix_view::editor::StatusLineElement::Spacer => render_spacer,
        helix_view::editor::StatusLineElement::VersionControl => render_version_control,
        helix_view::editor::StatusLineElement::Register => render_register,
    }
}

fn render_mode<'a>(context: &RenderContext) -> Spans<'a> {
    let visible = context.focused;
    let config = context.editor.config();
    let modenames = &config.statusline.mode;
    let modename = if visible {
        match context.editor.mode() {
            Mode::Insert => modenames.insert.clone(),
            Mode::Select => modenames.select.clone(),
            Mode::Normal => modenames.normal.clone(),
        }
    } else {
        // If not focused, explicitly leave an empty space.
        " ".into()
    };
    let modename = format!(" {} ", modename);
    if config.color_modes {
        Span::styled(
            modename,
            match context.editor.mode() {
                Mode::Insert => context.editor.theme.get("ui.statusline.insert"),
                Mode::Select => context.editor.theme.get("ui.statusline.select"),
                Mode::Normal => context.editor.theme.get("ui.statusline.normal"),
            },
        )
        .into()
    } else {
        Span::raw(modename).into()
    }
}

// TODO think about handling multiple language servers
fn render_lsp_spinner<'a>(context: &RenderContext) -> Spans<'a> {
    let language_server = context.doc.language_servers().next();
    Span::raw(
        language_server
            .and_then(|srv| {
                context
                    .spinners
                    .get(srv.id())
                    .and_then(|spinner| spinner.frame())
            })
            // Even if there's no spinner; reserve its space to avoid elements frequently shifting.
            .unwrap_or(" ")
            .to_string(),
    )
    .into()
}

fn render_diagnostics<'a>(context: &RenderContext) -> Spans<'a> {
    let (warnings, errors) = context
        .doc
        .diagnostics()
        .iter()
        .fold((0, 0), |mut counts, diag| {
            use helix_core::diagnostic::Severity;
            match diag.severity {
                Some(Severity::Warning) => counts.0 += 1,
                Some(Severity::Error) | None => counts.1 += 1,
                _ => {}
            }
            counts
        });

    let mut output = Spans::default();

    if warnings > 0 {
        output.0.push(Span::styled(
            "●".to_string(),
            context.editor.theme.get("warning"),
        ));
        output.0.push(Span::raw(format!(" {} ", warnings)));
    }

    if errors > 0 {
        output.0.push(Span::styled(
            "●".to_string(),
            context.editor.theme.get("error"),
        ));
        output.0.push(Span::raw(format!(" {} ", errors)));
    }

    output
}

fn render_workspace_diagnostics<'a>(context: &RenderContext) -> Spans<'a> {
    let (warnings, errors) =
        context
            .editor
            .diagnostics
            .values()
            .flatten()
            .fold((0, 0), |mut counts, (diag, _)| {
                match diag.severity {
                    Some(DiagnosticSeverity::WARNING) => counts.0 += 1,
                    Some(DiagnosticSeverity::ERROR) | None => counts.1 += 1,
                    _ => {}
                }
                counts
            });

    let mut output = Spans::default();

    if warnings > 0 || errors > 0 {
        output.0.push(Span::raw(" W "));
    }

    if warnings > 0 {
        output.0.push(Span::styled(
            "●".to_string(),
            context.editor.theme.get("warning"),
        ));
        output.0.push(Span::raw(format!(" {} ", warnings)));
    }

    if errors > 0 {
        output.0.push(Span::styled(
            "●".to_string(),
            context.editor.theme.get("error"),
        ));
        output.0.push(Span::raw(format!(" {} ", errors)));
    }

    output
}

fn render_selections<'a>(context: &RenderContext) -> Spans<'a> {
    let count = context.doc.selection(context.view.id).len();
    Span::raw(format!(
        " {} sel{} ",
        count,
        if count == 1 { "" } else { "s" }
    ))
    .into()
}

fn render_primary_selection_length<'a>(context: &RenderContext) -> Spans<'a> {
    let tot_sel = context.doc.selection(context.view.id).primary().len();
    Span::raw(format!(
        " {} char{} ",
        tot_sel,
        if tot_sel == 1 { "" } else { "s" }
    ))
    .into()
}

fn get_position(context: &RenderContext) -> Position {
    coords_at_pos(
        context.doc.text().slice(..),
        context
            .doc
            .selection(context.view.id)
            .primary()
            .cursor(context.doc.text().slice(..)),
    )
}

fn render_position<'a>(context: &RenderContext) -> Spans<'a> {
    let position = get_position(context);
    Span::raw(format!(" {}:{} ", position.row + 1, position.col + 1)).into()
}

fn render_total_line_numbers<'a>(context: &RenderContext) -> Spans<'a> {
    let total_line_numbers = context.doc.text().len_lines();
    Span::raw(format!(" {} ", total_line_numbers)).into()
}

fn render_position_percentage<'a>(context: &RenderContext) -> Spans<'a> {
    let position = get_position(context);
    let maxrows = context.doc.text().len_lines();
    Span::raw(format!("{}%", (position.row + 1) * 100 / maxrows)).into()
}

fn render_file_encoding<'a>(context: &RenderContext) -> Spans<'a> {
    let enc = context.doc.encoding();

    if enc != encoding::UTF_8 {
        Span::raw(format!(" {} ", enc.name())).into()
    } else {
        Spans::default()
    }
}

fn render_file_line_ending<'a>(context: &RenderContext) -> Spans<'a> {
    use helix_core::LineEnding::*;
    let line_ending = match context.doc.line_ending {
        Crlf => "CRLF",
        LF => "LF",
        #[cfg(feature = "unicode-lines")]
        VT => "VT", // U+000B -- VerticalTab
        #[cfg(feature = "unicode-lines")]
        FF => "FF", // U+000C -- FormFeed
        #[cfg(feature = "unicode-lines")]
        CR => "CR", // U+000D -- CarriageReturn
        #[cfg(feature = "unicode-lines")]
        Nel => "NEL", // U+0085 -- NextLine
        #[cfg(feature = "unicode-lines")]
        LS => "LS", // U+2028 -- Line Separator
        #[cfg(feature = "unicode-lines")]
        PS => "PS", // U+2029 -- ParagraphSeparator
    };

    Span::raw(format!(" {} ", line_ending)).into()
}

fn render_file_type<'a>(context: &RenderContext) -> Spans<'a> {
    let file_type = context.doc.language_name().unwrap_or(DEFAULT_LANGUAGE_NAME);

    Span::raw(format!(" {} ", file_type)).into()
}

fn render_file_name<'a>(context: &RenderContext) -> Spans<'a> {
    let title = {
        let rel_path = context.doc.relative_path();
        let path = rel_path
            .as_ref()
            .map(|p| p.to_string_lossy())
            .unwrap_or_else(|| SCRATCH_BUFFER_NAME.into());
        format!(" {} ", path)
    };

    Span::raw(title).into()
}

fn render_file_absolute_path<'a>(context: &RenderContext) -> Spans<'a> {
    let title = {
        let path = context.doc.path();
        let path = path
            .as_ref()
            .map(|p| p.to_string_lossy())
            .unwrap_or_else(|| SCRATCH_BUFFER_NAME.into());
        format!(" {} ", path)
    };

    Span::raw(title).into()
}

fn render_file_modification_indicator<'a>(context: &RenderContext) -> Spans<'a> {
    let title = (if context.doc.is_modified() {
        "[+]"
    } else {
        "   "
    })
    .to_string();

    Span::raw(title).into()
}

fn render_read_only_indicator<'a>(context: &RenderContext) -> Spans<'a> {
    let title = if context.doc.readonly {
        " [readonly] "
    } else {
        ""
    }
    .to_string();
    Span::raw(title).into()
}

fn render_file_base_name<'a>(context: &RenderContext) -> Spans<'a> {
    let title = {
        let rel_path = context.doc.relative_path();
        let path = rel_path
            .as_ref()
            .and_then(|p| p.file_name().map(|s| s.to_string_lossy()))
            .unwrap_or_else(|| SCRATCH_BUFFER_NAME.into());
        format!(" {} ", path)
    };

    Span::raw(title).into()
}

fn render_separator<'a>(context: &RenderContext) -> Spans<'a> {
    let sep = &context.editor.config().statusline.separator;

    Span::styled(
        sep.to_string(),
        context.editor.theme.get("ui.statusline.separator"),
    )
    .into()
}

fn render_spacer<'a>(_context: &RenderContext) -> Spans<'a> {
    Span::raw(" ").into()
}

fn render_version_control<'a>(context: &RenderContext) -> Spans<'a> {
    let head = context
        .doc
        .version_control_head()
        .unwrap_or_default()
        .to_string();

    Span::raw(head).into()
}

fn render_register<'a>(context: &RenderContext) -> Spans<'a> {
    if let Some(reg) = context.editor.selected_register {
        Span::raw(format!(" reg={} ", reg)).into()
    } else {
        Spans::default()
    }
}