Debian Codegraph @

helix-view/src/document.rs

raw symbols ◀ ▶ SCIP
1 Debian patch touch this file
1 use anyhow::{anyhow, bail, Error};
2 use arc_swap::access::DynAccess;
3 use arc_swap::ArcSwap;
4 use futures_util::future::BoxFuture;
5 use futures_util::FutureExt;
6 use helix_core::auto_pairs::AutoPairs;
7 use helix_core::chars::char_is_word;
8 use helix_core::command_line::Token;
9 use helix_core::diagnostic::DiagnosticProvider;
10 use helix_core::doc_formatter::TextFormat;
11 use helix_core::encoding::Encoding;
12 use helix_core::snippets::{ActiveSnippet, SnippetRenderCtx};
13 use helix_core::syntax::config::LanguageServerFeature;
14 use helix_core::text_annotations::{InlineAnnotation, Overlay};
15 use helix_event::TaskController;
16 use helix_lsp::util::lsp_pos_to_pos;
17 use helix_stdx::faccess::{copy_metadata, readonly};
18 use helix_vcs::{DiffHandle, DiffProviderRegistry};
19 use once_cell::sync::OnceCell;
20 use thiserror;
21
22 use ::parking_lot::Mutex;
23 use serde::de::{self, Deserialize, Deserializer};
24 use serde::Serialize;
25 use std::borrow::Cow;
26 use std::cell::Cell;
27 use std::collections::{HashMap, HashSet};
28 use std::fmt::Display;
29 use std::future::Future;
30 use std::io;
31 use std::path::{Path, PathBuf};
32 use std::str::FromStr;
33 use std::sync::{Arc, Weak};
34 use std::time::SystemTime;
35
36 use helix_core::{
37 editor_config::EditorConfig,
38 encoding,
39 history::{History, State, UndoKind},
40 indent::{auto_detect_indent_style, IndentStyle},
41 line_ending::auto_detect_line_ending,
42 syntax::{self, config::LanguageConfiguration},
43 ChangeSet, Diagnostic, LineEnding, Range, Rope, RopeBuilder, Selection, Syntax, Transaction,
44 };
45
46 use crate::{
47 editor::Config,
48 events::{DocumentDidChange, SelectionDidChange},
49 expansion,
50 view::ViewPosition,
51 DocumentId, Editor, Theme, View, ViewId,
52 };
53
54 /// 8kB of buffer space for encoding and decoding `Rope`s.
55 const BUF_SIZE: usize = 8192;
56
57 const DEFAULT_INDENT: IndentStyle = IndentStyle::Tabs;
58 const DEFAULT_TAB_WIDTH: usize = 4;
59
60 pub const DEFAULT_LANGUAGE_NAME: &str = "text";
61
62 pub const SCRATCH_BUFFER_NAME: &str = "[scratch]";
63
64 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
65 pub enum Mode {
66 Normal = 0,
67 Select = 1,
68 Insert = 2,
69 }
70
71 impl Display for Mode {
72 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
73 match self {
74 Mode::Normal => f.write_str("normal"),
75 Mode::Select => f.write_str("select"),
76 Mode::Insert => f.write_str("insert"),
77 }
78 }
79 }
80
81 impl FromStr for Mode {
82 type Err = Error;
83
84 fn from_str(s: &str) -> Result<Self, Self::Err> {
85 match s {
86 "normal" => Ok(Mode::Normal),
87 "select" => Ok(Mode::Select),
88 "insert" => Ok(Mode::Insert),
89 _ => bail!("Invalid mode '{}'", s),
90 }
91 }
92 }
93
94 // toml deserializer doesn't seem to recognize string as enum
95 impl<'de> Deserialize<'de> for Mode {
96 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
97 where
98 D: Deserializer<'de>,
99 {
100 let s = String::deserialize(deserializer)?;
101 s.parse().map_err(de::Error::custom)
102 }
103 }
104
105 impl Serialize for Mode {
106 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
107 where
108 S: serde::Serializer,
109 {
110 serializer.collect_str(self)
111 }
112 }
113 /// A snapshot of the text of a document that we want to write out to disk
114 #[derive(Debug, Clone)]
115 pub struct DocumentSavedEvent {
116 pub revision: usize,
117 pub save_time: SystemTime,
118 pub doc_id: DocumentId,
119 pub path: PathBuf,
120 pub text: Rope,
121 }
122
123 pub type DocumentSavedEventResult = Result<DocumentSavedEvent, anyhow::Error>;
124 pub type DocumentSavedEventFuture = BoxFuture<'static, DocumentSavedEventResult>;
125
126 #[derive(Debug)]
127 pub struct SavePoint {
128 /// The view this savepoint is associated with
129 pub view: ViewId,
130 revert: Mutex<Transaction>,
131 }
132
133 #[derive(Debug, thiserror::Error)]
134 pub enum DocumentOpenError {
135 #[error("path must be a regular file, symlink, or directory")]
136 IrregularFile,
137 #[error(transparent)]
138 IoError(#[from] io::Error),
139 }
140
141 pub struct Document {
142 pub(crate) id: DocumentId,
143 text: Rope,
144 selections: HashMap<ViewId, Selection>,
145 view_data: HashMap<ViewId, ViewData>,
146 pub active_snippet: Option<ActiveSnippet>,
147
148 /// Inlay hints annotations for the document, by view.
149 ///
150 /// To know if they're up-to-date, check the `id` field in `DocumentInlayHints`.
151 pub(crate) inlay_hints: HashMap<ViewId, DocumentInlayHints>,
152 /// Jump label overlays for each view.
153 pub(crate) jump_labels: HashMap<ViewId, Vec<Overlay>>,
154 /// LSP document highlights for each view, stored as char ranges.
155 pub(crate) document_highlights: HashMap<ViewId, DocumentHighlights>,
156 /// LSP code action hints for each view.
157 pub(crate) code_action_hints: HashSet<ViewId>,
158 /// Set to `true` when the document is updated, reset to `false` on the next inlay hints
159 /// update from the LSP
160 pub inlay_hints_oudated: bool,
161
162 path: Option<PathBuf>,
163 relative_path: OnceCell<Option<PathBuf>>,
164 /// Lazily-computed workspace root for this document (the ancestor that contains a `.git` /
165 /// `.svn` / `.jj` / `.helix`). Avoids per-call `find_workspace_in` ancestor walks for hot
166 /// consumers like the statusline trust indicator, LSP launch, and DAP launch. Taken in
167 /// `set_path` so save-as recomputes.
168 workspace_root: OnceCell<PathBuf>,
169 encoding: &'static encoding::Encoding,
170 has_bom: bool,
171
172 pub restore_cursor: bool,
173
174 /// Current indent style.
175 pub indent_style: IndentStyle,
176 editor_config: EditorConfig,
177
178 /// The document's default line ending.
179 pub line_ending: LineEnding,
180
181 pub syntax: Option<Syntax>,
182 /// Corresponding language scope name. Usually `source.<lang>`.
183 pub language: Option<Arc<LanguageConfiguration>>,
184
185 /// Pending changes since last history commit.
186 changes: ChangeSet,
187 /// State at last commit. Used for calculating reverts.
188 old_state: Option<State>,
189 /// Undo tree.
190 // It can be used as a cell where we will take it out to get some parts of the history and put
191 // it back as it separated from the edits. We could split out the parts manually but that will
192 // be more troublesome.
193 pub history: Cell<History>,
194 pub config: Arc<dyn DynAccess<Config>>,
195
196 savepoints: Vec<Weak<SavePoint>>,
197
198 // Last time we wrote to the file. This will carry the time the file was last opened if there
199 // were no saves.
200 last_saved_time: SystemTime,
201
202 last_saved_revision: usize,
203 version: i32, // should be usize?
204 pub(crate) modified_since_accessed: bool,
205
206 pub(crate) diagnostics: Vec<Diagnostic>,
207 pub(crate) language_servers: HashMap<LanguageServerName, Arc<Client>>,
208
209 diff_handle: Option<DiffHandle>,
210 version_control_head: Option<Arc<ArcSwap<Box<str>>>>,
211
212 // when document was used for most-recent-used buffer picker
213 pub focused_at: std::time::Instant,
214
215 pub readonly: bool,
216
217 pub previous_diagnostic_ids: HashMap<LanguageServerId, String>,
218
219 /// Annotations for LSP document color swatches
220 pub color_swatches: Option<DocumentColorSwatches>,
221 /// Cached LSP document links for navigation (e.g. goto_file).
222 pub document_links: Vec<DocumentLink>,
223 // NOTE: ideally this would live on the handler for color swatches. This is blocked on a
224 // large refactor that would make `&mut Editor` available on the `DocumentDidChange` event.
225 pub color_swatch_controller: TaskController,
226 /// Per-view task controllers for canceling in-flight document highlight requests.
227 pub document_highlight_controllers: HashMap<ViewId, TaskController>,
228 /// Per-view task controllers for canceling in-flight code action requests.
229 pub code_action_controllers: HashMap<ViewId, TaskController>,
230 pub pull_diagnostic_controller: TaskController,
231 pub document_link_controller: TaskController,
232
233 // NOTE: this field should eventually go away - we should use the Editor's syn_loader instead
234 // of storing a copy on every doc. Then we can remove the surrounding `Arc` and use the
235 // `ArcSwap` directly.
236 syn_loader: Arc<ArcSwap<syntax::Loader>>,
237 }
238
239 #[derive(Debug, Clone, Default)]
240 pub struct DocumentColorSwatches {
241 pub color_swatches: Vec<InlineAnnotation>,
242 pub colors: Vec<syntax::Highlight>,
243 pub color_swatches_padding: Vec<InlineAnnotation>,
244 }
245
246 /// Highlight ranges returned by LSP `textDocument/documentHighlight` for a view.
247 #[derive(Debug, Clone, Default)]
248 pub struct DocumentHighlights {
249 pub ranges: Vec<std::ops::Range<usize>>,
250 }
251
252 #[derive(Debug, Clone)]
253 pub struct DocumentLink {
254 /// Character offsets in the document for the link range.
255 pub start: usize,
256 pub end: usize,
257 pub link: lsp::DocumentLink,
258 pub language_server_id: LanguageServerId,
259 }
260
261 /// Inlay hints for a single `(Document, View)` combo.
262 ///
263 /// There are `*_inlay_hints` field for each kind of hints an LSP can send since we offer the
264 /// option to style theme differently in the theme according to the (currently supported) kinds
265 /// (`type`, `parameter` and the rest).
266 ///
267 /// Inlay hints are always `InlineAnnotation`s, not overlays or line-ones: LSP may choose to place
268 /// them anywhere in the text and will sometime offer config options to move them where the user
269 /// wants them but it shouldn't be Helix who decides that so we use the most precise positioning.
270 ///
271 /// The padding for inlay hints needs to be stored separately for before and after (the LSP spec
272 /// uses 'left' and 'right' but not all text is left to right so let's be correct) padding because
273 /// the 'before' padding must be added to a layer *before* the regular inlay hints and the 'after'
274 /// padding comes ... after.
275 #[derive(Debug, Clone)]
276 pub struct DocumentInlayHints {
277 /// Identifier for the inlay hints stored in this structure. To be checked to know if they have
278 /// to be recomputed on idle or not.
279 pub id: DocumentInlayHintsId,
280
281 /// Inlay hints of `TYPE` kind, if any.
282 pub type_inlay_hints: Vec<InlineAnnotation>,
283
284 /// Inlay hints of `PARAMETER` kind, if any.
285 pub parameter_inlay_hints: Vec<InlineAnnotation>,
286
287 /// Inlay hints that are neither `TYPE` nor `PARAMETER`.
288 ///
289 /// LSPs are not required to associate a kind to their inlay hints, for example Rust-Analyzer
290 /// currently never does (February 2023) and the LSP spec may add new kinds in the future that
291 /// we want to display even if we don't have some special highlighting for them.
292 pub other_inlay_hints: Vec<InlineAnnotation>,
293
294 /// Inlay hint padding. When creating the final `TextAnnotations`, the `before` padding must be
295 /// added first, then the regular inlay hints, then the `after` padding.
296 pub padding_before_inlay_hints: Vec<InlineAnnotation>,
297 pub padding_after_inlay_hints: Vec<InlineAnnotation>,
298 }
299
300 impl DocumentInlayHints {
301 /// Generate an empty list of inlay hints with the given ID.
302 pub fn empty_with_id(id: DocumentInlayHintsId) -> Self {
303 Self {
304 id,
305 type_inlay_hints: Vec::new(),
306 parameter_inlay_hints: Vec::new(),
307 other_inlay_hints: Vec::new(),
308 padding_before_inlay_hints: Vec::new(),
309 padding_after_inlay_hints: Vec::new(),
310 }
311 }
312 }
313
314 /// Associated with a [`Document`] and [`ViewId`], uniquely identifies the state of inlay hints for
315 /// for that document and view: if this changed since the last save, the inlay hints for the view
316 /// should be recomputed.
317 ///
318 /// We can't store the `ViewOffset` instead of the first and last asked-for lines because if
319 /// softwrapping changes, the `ViewOffset` may not change while the displayed lines will.
320 #[derive(Copy, Clone, PartialEq, Eq)]
321 pub struct DocumentInlayHintsId {
322 /// First line for which the inlay hints were requested.
323 pub first_line: usize,
324 /// Last line for which the inlay hints were requested.
325 pub last_line: usize,
326 }
327
328 use std::{fmt, mem};
329 impl fmt::Debug for Document {
330 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
331 f.debug_struct("Document")
332 .field("id", &self.id)
333 .field("text", &self.text)
334 .field("selections", &self.selections)
335 .field("inlay_hints_oudated", &self.inlay_hints_oudated)
336 .field("text_annotations", &self.inlay_hints)
337 .field("view_data", &self.view_data)
338 .field("path", &self.path)
339 .field("encoding", &self.encoding)
340 .field("restore_cursor", &self.restore_cursor)
341 .field("syntax", &self.syntax)
342 .field("language", &self.language)
343 .field("changes", &self.changes)
344 .field("old_state", &self.old_state)
345 // .field("history", &self.history)
346 .field("last_saved_time", &self.last_saved_time)
347 .field("last_saved_revision", &self.last_saved_revision)
348 .field("version", &self.version)
349 .field("modified_since_accessed", &self.modified_since_accessed)
350 .field("diagnostics", &self.diagnostics)
351 // .field("language_server", &self.language_server)
352 .finish()
353 }
354 }
355
356 impl fmt::Debug for DocumentInlayHintsId {
357 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
358 // Much more agreable to read when debugging
359 f.debug_struct("DocumentInlayHintsId")
360 .field("lines", &(self.first_line..self.last_line))
361 .finish()
362 }
363 }
364
365 impl Editor {
366 pub(crate) fn clear_doc_relative_paths(&mut self) {
367 for doc in self.documents_mut() {
368 doc.relative_path.take();
369 }
370 }
371 }
372
373 enum Encoder {
374 Utf16Be,
375 Utf16Le,
376 EncodingRs(encoding::Encoder),
377 }
378
379 impl Encoder {
380 fn from_encoding(encoding: &'static encoding::Encoding) -> Self {
381 if encoding == encoding::UTF_16BE {
382 Self::Utf16Be
383 } else if encoding == encoding::UTF_16LE {
384 Self::Utf16Le
385 } else {
386 Self::EncodingRs(encoding.new_encoder())
387 }
388 }
389
390 fn encode_from_utf8(
391 &mut self,
392 src: &str,
393 dst: &mut [u8],
394 is_empty: bool,
395 ) -> (encoding::CoderResult, usize, usize) {
396 if src.is_empty() {
397 return (encoding::CoderResult::InputEmpty, 0, 0);
398 }
399 let mut write_to_buf = |convert: fn(u16) -> [u8; 2]| {
400 let to_write = src.char_indices().map(|(indice, char)| {
401 let mut encoded: [u16; 2] = [0, 0];
402 (
403 indice,
404 char.encode_utf16(&mut encoded)
405 .iter_mut()
406 .flat_map(|char| convert(*char))
407 .collect::<Vec<u8>>(),
408 )
409 });
410
411 let mut total_written = 0usize;
412
413 for (indice, utf16_bytes) in to_write {
414 let character_size = utf16_bytes.len();
415
416 if dst.len() <= (total_written + character_size) {
417 return (encoding::CoderResult::OutputFull, indice, total_written);
418 }
419
420 for character in utf16_bytes {
421 dst[total_written] = character;
422 total_written += 1;
423 }
424 }
425
426 (encoding::CoderResult::InputEmpty, src.len(), total_written)
427 };
428
429 match self {
430 Self::Utf16Be => write_to_buf(u16::to_be_bytes),
431 Self::Utf16Le => write_to_buf(u16::to_le_bytes),
432 Self::EncodingRs(encoder) => {
433 let (code_result, read, written, ..) = encoder.encode_from_utf8(src, dst, is_empty);
434
435 (code_result, read, written)
436 }
437 }
438 }
439 }
440
441 // Apply BOM if encoding permit it, return the number of bytes written at the start of buf
442 fn apply_bom(encoding: &'static encoding::Encoding, buf: &mut [u8; BUF_SIZE]) -> usize {
443 if encoding == encoding::UTF_8 {
444 buf[0] = 0xef;
445 buf[1] = 0xbb;
446 buf[2] = 0xbf;
447 3
448 } else if encoding == encoding::UTF_16BE {
449 buf[0] = 0xfe;
450 buf[1] = 0xff;
451 2
452 } else if encoding == encoding::UTF_16LE {
453 buf[0] = 0xff;
454 buf[1] = 0xfe;
455 2
456 } else {
457 0
458 }
459 }
460
461 // The documentation and implementation of this function should be up-to-date with
462 // its sibling function, `to_writer()`.
463 //
464 /// Decodes a stream of bytes into UTF-8, returning a `Rope` and the
465 /// encoding it was decoded as with BOM information. The optional `encoding`
466 /// parameter can be used to override encoding auto-detection.
467 pub fn from_reader<R: std::io::Read + ?Sized>(
468 reader: &mut R,
469 encoding: Option<&'static Encoding>,
470 ) -> Result<(Rope, &'static Encoding, bool), io::Error> {
471 // These two buffers are 8192 bytes in size each and are used as
472 // intermediaries during the decoding process. Text read into `buf`
473 // from `reader` is decoded into `buf_out` as UTF-8. Once either
474 // `buf_out` is full or the end of the reader was reached, the
475 // contents are appended to `builder`.
476 let mut buf = [0u8; BUF_SIZE];
477 let mut buf_out = [0u8; BUF_SIZE];
478 let mut builder = RopeBuilder::new();
479
480 let (encoding, has_bom, mut decoder, read) =
481 read_and_detect_encoding(reader, encoding, &mut buf)?;
482
483 let mut slice = &buf[..read];
484 let mut is_empty = read == 0;
485
486 // `RopeBuilder::append()` expects a `&str`, so this is the "real"
487 // output buffer. When decoding, the number of bytes in the output
488 // buffer will often exceed the number of bytes in the input buffer.
489 // The `result` returned by `decode_to_str()` will state whether or
490 // not that happened. The contents of `buf_str` is appended to
491 // `builder` and it is reused for the next iteration of the decoding
492 // loop.
493 //
494 // As it is possible to read less than the buffer's maximum from `read()`
495 // even when the end of the reader has yet to be reached, the end of
496 // the reader is determined only when a `read()` call returns `0`.
497 //
498 // SAFETY: `buf_out` is a zero-initialized array, thus it will always
499 // contain valid UTF-8.
500 let buf_str = unsafe { std::str::from_utf8_unchecked_mut(&mut buf_out[..]) };
501 let mut total_written = 0usize;
502 loop {
503 let mut total_read = 0usize;
504
505 // An inner loop is necessary as it is possible that the input buffer
506 // may not be completely decoded on the first `decode_to_str()` call
507 // which would happen in cases where the output buffer is filled to
508 // capacity.
509 loop {
510 let (result, read, written, ..) = decoder.decode_to_str(
511 &slice[total_read..],
512 &mut buf_str[total_written..],
513 is_empty,
514 );
515
516 // These variables act as the read and write cursors of `buf` and `buf_str` respectively.
517 // They are necessary in case the output buffer fills before decoding of the entire input
518 // loop is complete. Otherwise, the loop would endlessly iterate over the same `buf` and
519 // the data inside the output buffer would be overwritten.
520 total_read += read;
521 total_written += written;
522 match result {
523 encoding::CoderResult::InputEmpty => {
524 debug_assert_eq!(slice.len(), total_read);
525 break;
526 }
527 encoding::CoderResult::OutputFull => {
528 debug_assert!(slice.len() > total_read);
529 builder.append(&buf_str[..total_written]);
530 total_written = 0;
531 }
532 }
533 }
534 // Once the end of the stream is reached, the output buffer is
535 // flushed and the loop terminates.
536 if is_empty {
537 debug_assert_eq!(reader.read(&mut buf)?, 0);
538 builder.append(&buf_str[..total_written]);
539 break;
540 }
541
542 // Once the previous input has been processed and decoded, the next set of
543 // data is fetched from the reader. The end of the reader is determined to
544 // be when exactly `0` bytes were read from the reader, as per the invariants
545 // of the `Read` trait.
546 let read = reader.read(&mut buf)?;
547 slice = &buf[..read];
548 is_empty = read == 0;
549 }
550 let rope = builder.finish();
551 Ok((rope, encoding, has_bom))
552 }
553
554 pub fn read_to_string<R: std::io::Read + ?Sized>(
555 reader: &mut R,
556 encoding: Option<&'static Encoding>,
557 ) -> Result<(String, &'static Encoding, bool), Error> {
558 let mut buf = [0u8; BUF_SIZE];
559
560 let (encoding, has_bom, mut decoder, read) =
561 read_and_detect_encoding(reader, encoding, &mut buf)?;
562
563 let mut slice = &buf[..read];
564 let mut is_empty = read == 0;
565 let mut buf_string = String::with_capacity(buf.len());
566
567 loop {
568 let mut total_read = 0usize;
569
570 loop {
571 let (result, read, ..) =
572 decoder.decode_to_string(&slice[total_read..], &mut buf_string, is_empty);
573
574 total_read += read;
575
576 match result {
577 encoding::CoderResult::InputEmpty => {
578 debug_assert_eq!(slice.len(), total_read);
579 break;
580 }
581 encoding::CoderResult::OutputFull => {
582 debug_assert!(slice.len() > total_read);
583 buf_string.reserve(buf.len())
584 }
585 }
586 }
587
588 if is_empty {
589 debug_assert_eq!(reader.read(&mut buf)?, 0);
590 break;
591 }
592
593 let read = reader.read(&mut buf)?;
594 slice = &buf[..read];
595 is_empty = read == 0;
596 }
597 Ok((buf_string, encoding, has_bom))
598 }
599
600 /// Reads the first chunk from a Reader into the given buffer
601 /// and detects the encoding.
602 ///
603 /// By default, the encoding of the text is auto-detected by
604 /// `encoding_rs` for_bom, and if it fails, from `chardetng`
605 /// crate which requires sample data from the reader.
606 /// As a manual override to this auto-detection is possible, the
607 /// same data is read into `buf` to ensure symmetry in the upcoming
608 /// loop.
609 fn read_and_detect_encoding<R: std::io::Read + ?Sized>(
610 reader: &mut R,
611 encoding: Option<&'static Encoding>,
612 buf: &mut [u8],
613 ) -> Result<(&'static Encoding, bool, encoding::Decoder, usize), io::Error> {
614 let read = reader.read(buf)?;
615 let is_empty = read == 0;
616 let (encoding, has_bom) = encoding
617 .map(|encoding| (encoding, false))
618 .or_else(|| encoding::Encoding::for_bom(buf).map(|(encoding, _bom_size)| (encoding, true)))
619 .unwrap_or_else(|| {
•620 let mut encoding_detector = chardetng::EncodingDetector::new();
621 encoding_detector.feed(buf, is_empty);
•622 (encoding_detector.guess(None, true), false)
623 });
624 let decoder = encoding.new_decoder();
625
626 Ok((encoding, has_bom, decoder, read))
627 }
628
629 // The documentation and implementation of this function should be up-to-date with
630 // its sibling function, `from_reader()`.
631 //
632 /// Encodes the text inside `rope` into the given `encoding` and writes the
633 /// encoded output into `writer.` As a `Rope` can only contain valid UTF-8,
634 /// replacement characters may appear in the encoded text.
635 pub async fn to_writer<'a, W: tokio::io::AsyncWriteExt + Unpin + ?Sized>(
636 writer: &'a mut W,
637 encoding_with_bom_info: (&'static Encoding, bool),
638 rope: &'a Rope,
639 ) -> Result<(), Error> {
640 // Text inside a `Rope` is stored as non-contiguous blocks of data called
641 // chunks. The absolute size of each chunk is unknown, thus it is impossible
642 // to predict the end of the chunk iterator ahead of time. Instead, it is
643 // determined by filtering the iterator to remove all empty chunks and then
644 // appending an empty chunk to it. This is valuable for detecting when all
645 // chunks in the `Rope` have been iterated over in the subsequent loop.
646 let (encoding, has_bom) = encoding_with_bom_info;
647
648 let iter = rope
649 .chunks()
650 .filter(|c| !c.is_empty())
651 .chain(std::iter::once(""));
652 let mut buf = [0u8; BUF_SIZE];
653
654 let mut total_written = if has_bom {
655 apply_bom(encoding, &mut buf)
656 } else {
657 0
658 };
659
660 let mut encoder = Encoder::from_encoding(encoding);
661
662 for chunk in iter {
663 let is_empty = chunk.is_empty();
664 let mut total_read = 0usize;
665
666 // An inner loop is necessary as it is possible that the input buffer
667 // may not be completely encoded on the first `encode_from_utf8()` call
668 // which would happen in cases where the output buffer is filled to
669 // capacity.
670 loop {
671 let (result, read, written, ..) =
672 encoder.encode_from_utf8(&chunk[total_read..], &mut buf[total_written..], is_empty);
673
674 // These variables act as the read and write cursors of `chunk` and `buf` respectively.
675 // They are necessary in case the output buffer fills before encoding of the entire input
676 // loop is complete. Otherwise, the loop would endlessly iterate over the same `chunk` and
677 // the data inside the output buffer would be overwritten.
678 total_read += read;
679 total_written += written;
680 match result {
681 encoding::CoderResult::InputEmpty => {
682 debug_assert_eq!(chunk.len(), total_read);
683 debug_assert!(buf.len() >= total_written);
684 break;
685 }
686 encoding::CoderResult::OutputFull => {
687 debug_assert!(chunk.len() > total_read);
688 writer.write_all(&buf[..total_written]).await?;
689 total_written = 0;
690 }
691 }
692 }
693
694 // Once the end of the iterator is reached, the output buffer is
695 // flushed and the outer loop terminates.
696 if is_empty {
697 writer.write_all(&buf[..total_written]).await?;
698 writer.flush().await?;
699 break;
700 }
701 }
702
703 Ok(())
704 }
705
706 fn take_with<T, F>(mut_ref: &mut T, f: F)
707 where
708 T: Default,
709 F: FnOnce(T) -> T,
710 {
711 *mut_ref = f(mem::take(mut_ref));
712 }
713
714 use helix_lsp::{lsp, Client, LanguageServerId, LanguageServerName};
715 use helix_stdx::Url;
716
717 impl Document {
718 pub fn from(
719 text: Rope,
720 encoding_with_bom_info: Option<(&'static Encoding, bool)>,
721 config: Arc<dyn DynAccess<Config>>,
722 syn_loader: Arc<ArcSwap<syntax::Loader>>,
723 ) -> Self {
724 let (encoding, has_bom) = encoding_with_bom_info.unwrap_or((encoding::UTF_8, false));
725 let line_ending = config.load().default_line_ending.into();
726 let changes = ChangeSet::new(text.slice(..));
727 let old_state = None;
728
729 Self {
730 id: DocumentId::default(),
731 active_snippet: None,
732 path: None,
733 relative_path: OnceCell::new(),
734 workspace_root: OnceCell::new(),
735 encoding,
736 has_bom,
737 text,
738 selections: HashMap::default(),
739 inlay_hints: HashMap::default(),
740 inlay_hints_oudated: false,
741 view_data: Default::default(),
742 indent_style: DEFAULT_INDENT,
743 editor_config: EditorConfig::default(),
744 line_ending,
745 restore_cursor: false,
746 syntax: None,
747 language: None,
748 changes,
749 old_state,
750 diagnostics: Vec::new(),
751 version: 0,
752 history: Cell::new(History::default()),
753 savepoints: Vec::new(),
754 last_saved_time: SystemTime::now(),
755 last_saved_revision: 0,
756 modified_since_accessed: false,
757 language_servers: HashMap::new(),
758 diff_handle: None,
759 config,
760 version_control_head: None,
761 focused_at: std::time::Instant::now(),
762 readonly: false,
763 jump_labels: HashMap::new(),
764 document_highlights: HashMap::new(),
765 code_action_hints: HashSet::new(),
766 color_swatches: None,
767 document_links: Vec::new(),
768 color_swatch_controller: TaskController::new(),
769 document_highlight_controllers: HashMap::new(),
770 code_action_controllers: HashMap::new(),
771 syn_loader,
772 previous_diagnostic_ids: HashMap::new(),
773 pull_diagnostic_controller: TaskController::new(),
774 document_link_controller: TaskController::new(),
775 }
776 }
777
778 pub fn default(
779 config: Arc<dyn DynAccess<Config>>,
780 syn_loader: Arc<ArcSwap<syntax::Loader>>,
781 ) -> Self {
782 let line_ending: LineEnding = config.load().default_line_ending.into();
783 let text = Rope::from(line_ending.as_str());
784 Self::from(text, None, config, syn_loader)
785 }
786
787 // TODO: async fn?
788 /// Create a new document from `path`. Encoding is auto-detected, but it can be manually
789 /// overwritten with the `encoding` parameter.
790 pub fn open(
791 path: &Path,
792 mut encoding: Option<&'static Encoding>,
793 detect_language: bool,
794 config: Arc<dyn DynAccess<Config>>,
795 syn_loader: Arc<ArcSwap<syntax::Loader>>,
796 ) -> Result<Self, DocumentOpenError> {
797 // If the path is not a regular file (e.g.: /dev/random) it should not be opened.
798 if path.metadata().is_ok_and(|metadata| !metadata.is_file()) {
799 return Err(DocumentOpenError::IrregularFile);
800 }
801
802 let editor_config = if config.load().editor_config {
803 EditorConfig::find(path)
804 } else {
805 EditorConfig::default()
806 };
807 encoding = encoding.or(editor_config.encoding);
808
809 // Open the file if it exists, otherwise assume it is a new file (and thus empty).
810 let (rope, encoding, has_bom) = if path.exists() {
811 let mut file = std::fs::File::open(path)?;
812 from_reader(&mut file, encoding)?
813 } else {
814 let line_ending = editor_config
815 .line_ending
816 .unwrap_or_else(|| config.load().default_line_ending.into());
817 let encoding = encoding.unwrap_or(encoding::UTF_8);
818 (Rope::from(line_ending.as_str()), encoding, false)
819 };
820
821 let loader = syn_loader.load();
822 let mut doc = Self::from(rope, Some((encoding, has_bom)), config, syn_loader);
823
824 // set the path and try detecting the language
825 doc.set_path(Some(path));
826 if detect_language {
827 doc.detect_language(&loader);
828 }
829
830 doc.editor_config = editor_config;
831 doc.detect_indent_and_line_ending();
832
833 Ok(doc)
834 }
835
836 /// The same as [`format`], but only returns formatting changes if auto-formatting
837 /// is configured.
838 pub fn auto_format(
839 &self,
840 editor: &Editor,
841 ) -> Option<BoxFuture<'static, Result<Transaction, FormatterError>>> {
842 if self.language_config()?.auto_format {
843 self.format(editor)
844 } else {
845 None
846 }
847 }
848
849 /// If supported, returns the changes that should be applied to this document in order
850 /// to format it nicely.
851 // We can't use anyhow::Result here since the output of the future has to be
852 // clonable to be used as shared future. So use a custom error type.
853 pub fn format(
854 &self,
855 editor: &Editor,
856 ) -> Option<BoxFuture<'static, Result<Transaction, FormatterError>>> {
857 if let Some((fmt_cmd, fmt_args)) = self
858 .language_config()
859 .and_then(|c| c.formatter.as_ref())
860 .and_then(|formatter| {
861 Some((
862 helix_stdx::env::which(&formatter.command).ok()?,
863 &formatter.args,
864 ))
865 })
866 {
867 log::debug!(
868 "formatting '{}' with command '{}', args {fmt_args:?}",
869 self.display_name(),
870 fmt_cmd.display(),
871 );
872 use std::process::Stdio;
873 let text = self.text().clone();
874
875 let mut process = tokio::process::Command::new(&fmt_cmd);
876
877 if let Some(doc_dir) = self.path.as_ref().and_then(|path| path.parent()) {
878 process.current_dir(doc_dir);
879 }
880
881 let args = match fmt_args
882 .iter()
883 .map(|content| expansion::expand(editor, Token::expand(content)))
884 .collect::<Result<Vec<_>, _>>()
885 {
886 Ok(args) => args,
887 Err(err) => {
888 log::error!("Failed to expand formatter arguments: {err}");
889 return None;
890 }
891 };
892
893 process
894 .args(args.iter().map(AsRef::as_ref))
895 .stdin(Stdio::piped())
896 .stdout(Stdio::piped())
897 .stderr(Stdio::piped());
898
899 let formatting_future = async move {
900 let mut process = process
901 .spawn()
902 .map_err(|e| FormatterError::SpawningFailed {
903 command: fmt_cmd.to_string_lossy().into(),
904 error: e.kind(),
905 })?;
906
907 let mut stdin = process.stdin.take().ok_or(FormatterError::BrokenStdin)?;
908 let input_text = text.clone();
909 let input_task = tokio::spawn(async move {
910 to_writer(&mut stdin, (encoding::UTF_8, false), &input_text).await
911 // Note that `stdin` is dropped here, causing the pipe to close. This can
912 // avoid a deadlock with `wait_with_output` below if the process is waiting on
913 // stdin to close before exiting.
914 });
915 let (input_result, output_result) = tokio::join! {
916 input_task,
917 process.wait_with_output(),
918 };
919 let _ = input_result.map_err(|_| FormatterError::BrokenStdin)?;
920 let output = output_result.map_err(|_| FormatterError::WaitForOutputFailed)?;
921
922 if !output.status.success() {
923 if !output.stderr.is_empty() {
924 let err = String::from_utf8_lossy(&output.stderr).to_string();
925 log::error!("Formatter error: {}", err);
926 return Err(FormatterError::NonZeroExitStatus(Some(err)));
927 }
928
929 return Err(FormatterError::NonZeroExitStatus(None));
930 } else if !output.stderr.is_empty() {
931 log::debug!(
932 "Formatter printed to stderr: {}",
933 String::from_utf8_lossy(&output.stderr)
934 );
935 }
936
937 let str = std::str::from_utf8(&output.stdout)
938 .map_err(|_| FormatterError::InvalidUtf8Output)?;
939
940 Ok(helix_core::diff::compare_ropes(&text, &Rope::from(str)))
941 };
942 return Some(formatting_future.boxed());
943 };
944
945 let text = self.text.clone();
946 // finds first language server that supports formatting and then formats
947 let language_server = self
948 .language_servers_with_feature(LanguageServerFeature::Format)
949 .next()?;
950 let offset_encoding = language_server.offset_encoding();
951 let request = language_server.text_document_formatting(
952 self.identifier(),
953 lsp::FormattingOptions {
954 tab_size: self.tab_width() as u32,
955 insert_spaces: matches!(self.indent_style, IndentStyle::Spaces(_)),
956 ..Default::default()
957 },
958 None,
959 )?;
960
961 let fut = async move {
962 let edits = request
963 .await
964 .unwrap_or_else(|e| {
965 log::warn!("LSP formatting failed: {}", e);
966 Default::default()
967 })
968 .unwrap_or_default();
969 Ok(helix_lsp::util::generate_transaction_from_edits(
970 &text,
971 edits,
972 offset_encoding,
973 ))
974 };
975 Some(fut.boxed())
976 }
977
978 pub fn save<P: Into<PathBuf>>(
979 &mut self,
980 path: Option<P>,
981 force: bool,
982 ) -> Result<
983 impl Future<Output = Result<DocumentSavedEvent, anyhow::Error>> + 'static + Send,
984 anyhow::Error,
985 > {
986 let path = path.map(|path| path.into());
987 self.save_impl(path, force)
988
989 // futures_util::future::Ready<_>,
990 }
991
992 /// The `Document`'s text is encoded according to its encoding and written to the file located
993 /// at its `path()`.
994 fn save_impl(
995 &mut self,
996 path: Option<PathBuf>,
997 force: bool,
998 ) -> Result<
999 impl Future<Output = Result<DocumentSavedEvent, anyhow::Error>> + 'static + Send,
1000 anyhow::Error,
1001 > {
1002 log::debug!(
1003 "submitting save of doc '{:?}'",
1004 self.path().map(|path| path.to_string_lossy())
1005 );
1006
1007 // we clone and move text + path into the future so that we asynchronously save the current
1008 // state without blocking any further edits.
1009 let text = self.text().clone();
1010
1011 let path = match path {
1012 Some(path) => helix_stdx::path::canonicalize(path),
1013 None => {
1014 if self.path.is_none() {
1015 bail!("Can't save with no path set!");
1016 }
1017 self.path.as_ref().unwrap().clone()
1018 }
1019 };
1020
1021 let identifier = self.path().map(|_| self.identifier());
1022 let language_servers: Vec<_> = self.language_servers.values().cloned().collect();
1023
1024 // mark changes up to now as saved
1025 let current_rev = self.get_current_revision();
1026 let doc_id = self.id();
1027 let atomic_save = self.config.load().atomic_save;
1028
1029 let encoding_with_bom_info = (self.encoding, self.has_bom);
1030 let last_saved_time = self.last_saved_time;
1031
1032 // We encode the file according to the `Document`'s encoding.
1033 let future = async move {
1034 use tokio::fs;
1035 if let Some(parent) = path.parent() {
1036 // TODO: display a prompt asking the user if the directories should be created
1037 if !parent.exists() {
1038 if force {
1039 std::fs::DirBuilder::new().recursive(true).create(parent)?;
1040 } else {
1041 bail!("can't save file, parent directory does not exist (use :w! to create it)");
1042 }
1043 }
1044 }
1045
1046 // Protect against overwriting changes made externally
1047 if !force {
1048 if let Ok(metadata) = fs::metadata(&path).await {
1049 if let Ok(mtime) = metadata.modified() {
1050 if last_saved_time < mtime {
1051 bail!("file modified by an external process, use :w! to overwrite");
1052 }
1053 }
1054 }
1055 }
1056 let write_path = tokio::fs::read_link(&path)
1057 .await
1058 .ok()
1059 .and_then(|p| {
1060 if p.is_relative() {
1061 path.parent().map(|parent| parent.join(p))
1062 } else {
1063 Some(p)
1064 }
1065 })
1066 .unwrap_or_else(|| path.clone());
1067
1068 if readonly(&write_path) {
1069 bail!(std::io::Error::new(
1070 std::io::ErrorKind::PermissionDenied,
1071 "Path is read only"
1072 ));
1073 }
1074
1075 // Assume it is a hardlink to prevent data loss if the metadata cant be read (e.g. on certain Windows configurations)
1076 let is_hardlink = helix_stdx::faccess::hardlink_count(&write_path).unwrap_or(2) > 1;
1077 let is_symlink = match tokio::fs::symlink_metadata(&write_path).await {
1078 Ok(meta) => meta.is_symlink(),
1079 Err(err) if err.kind() == std::io::ErrorKind::NotFound => false,
1080 Err(err) => return Err(err.into()),
1081 };
1082 let must_copy = is_hardlink || is_symlink;
1083 let backup = if path.exists() && atomic_save {
1084 let path_ = write_path.clone();
1085 // hacks: we use tempfile to handle the complex task of creating
1086 // non clobbered temporary path for us we don't want
1087 // the whole automatically delete path on drop thing
1088 // since the path doesn't exist yet, we just want
1089 // the path
1090 tokio::task::spawn_blocking(move || -> Option<PathBuf> {
1091 let mut builder = tempfile::Builder::new();
1092 builder.prefix(path_.file_name()?).suffix(".bck");
1093
1094 let backup_path = if must_copy {
1095 builder
1096 .make_in(path_.parent()?, |backup| std::fs::copy(&path_, backup))
1097 .ok()?
1098 .into_temp_path()
1099 } else {
1100 builder
1101 .make_in(path_.parent()?, |backup| std::fs::rename(&path_, backup))
1102 .ok()?
1103 .into_temp_path()
1104 };
1105
1106 backup_path.keep().ok()
1107 })
1108 .await
1109 .ok()
1110 .flatten()
1111 } else {
1112 None
1113 };
1114
1115 let write_result: anyhow::Result<_> = async {
1116 let mut dst = tokio::fs::File::create(&write_path).await?;
1117 to_writer(&mut dst, encoding_with_bom_info, &text).await?;
1118 // Ignore ENOTSUP/EOPNOTSUPP (Operation not supported) errors from sync_all()
1119 // This is known to occur on SMB filesystems on macOS where fsync is not supported
1120 match dst.sync_all().await {
1121 Ok(_) => (),
1122 Err(err) if err.kind() == io::ErrorKind::Unsupported => (),
1123 // Some extra OS errors are thrown on macOS for example if fsync is not
1124 // available for this filesystem. NOTE: on macOS, ENOTSUP and EOPNOTSUPP are
1125 // not the same code, so we need to suppress the unreachable_patterns lint on
1126 // Unix generally.
1127 #[allow(unreachable_patterns)]
1128 #[cfg(unix)]
1129 Err(err)
1130 if matches!(err.raw_os_error(), Some(libc::ENOTSUP | libc::EOPNOTSUPP)) => {
1131 }
1132 Err(err) => return Err(err.into()),
1133 }
1134 Ok(())
1135 }
1136 .await;
1137
1138 let save_time = match fs::metadata(&write_path).await {
1139 Ok(metadata) => metadata.modified().map_or(SystemTime::now(), |mtime| mtime),
1140 Err(_) => SystemTime::now(),
1141 };
1142
1143 if let Some(backup) = backup {
1144 if must_copy {
1145 let mut delete = true;
1146 if write_result.is_err() {
1147 // Restore backup
1148 let _ = tokio::fs::copy(&backup, &write_path).await.map_err(|e| {
1149 delete = false;
1150 log::error!("Failed to restore backup on write failure: {e}")
1151 });
1152 }
1153
1154 if delete {
1155 // Delete backup
1156 let _ = tokio::fs::remove_file(backup)
1157 .await
1158 .map_err(|e| log::error!("Failed to remove backup file on write: {e}"));
1159 }
1160 } else if write_result.is_err() {
1161 // restore backup
1162 let _ = tokio::fs::rename(&backup, &write_path)
1163 .await
1164 .map_err(|e| log::error!("Failed to restore backup on write failure: {e}"));
1165 } else {
1166 // copy metadata and delete backup
1167 let _ = tokio::task::spawn_blocking(move || {
1168 let _ = copy_metadata(&backup, &write_path)
1169 .map_err(|e| log::error!("Failed to copy metadata on write: {e}"));
1170 let _ = std::fs::remove_file(backup)
1171 .map_err(|e| log::error!("Failed to remove backup file on write: {e}"));
1172 })
1173 .await;
1174 }
1175 }
1176
1177 write_result?;
1178
1179 let event = DocumentSavedEvent {
1180 revision: current_rev,
1181 save_time,
1182 doc_id,
1183 path,
1184 text: text.clone(),
1185 };
1186
1187 for language_server in language_servers {
1188 if !language_server.is_initialized() {
1189 continue;
1190 }
1191 if let Some(id) = identifier.clone() {
1192 language_server.text_document_did_save(id, &text);
1193 }
1194 }
1195
1196 Ok(event)
1197 };
1198
1199 Ok(future)
1200 }
1201
1202 /// Detect the programming language based on the file type.
1203 pub fn detect_language(&mut self, loader: &syntax::Loader) {
1204 self.set_language(self.detect_language_config(loader), loader);
1205 }
1206
1207 /// Detect the programming language based on the file type.
1208 pub fn detect_language_config(
1209 &self,
1210 loader: &syntax::Loader,
1211 ) -> Option<Arc<syntax::config::LanguageConfiguration>> {
1212 let language = loader
1213 .language_for_filename(self.path.as_ref()?)
1214 .or_else(|| loader.language_for_shebang(self.text().slice(..)))?;
1215
1216 Some(loader.language(language).config().clone())
1217 }
1218
1219 /// Detect the indentation used in the file, or otherwise defaults to the language indentation
1220 /// configured in `languages.toml`, with a fallback to tabs if it isn't specified. Line ending
1221 /// is likewise auto-detected, and will remain unchanged if no line endings were detected.
1222 pub fn detect_indent_and_line_ending(&mut self) {
1223 self.indent_style = if let Some(indent_style) = self.editor_config.indent_style {
1224 indent_style
1225 } else {
1226 auto_detect_indent_style(&self.text).unwrap_or_else(|| {
1227 self.language_config()
1228 .and_then(|config| config.indent.as_ref())
1229 .map_or(DEFAULT_INDENT, |config| IndentStyle::from_str(&config.unit))
1230 })
1231 };
1232 if let Some(line_ending) = self
1233 .editor_config
1234 .line_ending
1235 .or_else(|| auto_detect_line_ending(&self.text))
1236 {
1237 self.line_ending = line_ending;
1238 }
1239 }
1240
1241 pub fn detect_editor_config(&mut self) {
1242 if self.config.load().editor_config {
1243 if let Some(path) = self.path.as_ref() {
1244 self.editor_config = EditorConfig::find(path);
1245 }
1246 }
1247 }
1248
1249 pub fn pickup_last_saved_time(&mut self) {
1250 self.last_saved_time = match self.path() {
1251 Some(path) => match path.metadata() {
1252 Ok(metadata) => match metadata.modified() {
1253 Ok(mtime) => mtime,
1254 Err(err) => {
1255 log::debug!("Could not fetch file system's mtime, falling back to current system time: {}", err);
1256 SystemTime::now()
1257 }
1258 },
1259 Err(err) => {
1260 log::debug!("Could not fetch file system's mtime, falling back to current system time: {}", err);
1261 SystemTime::now()
1262 }
1263 },
1264 None => SystemTime::now(),
1265 };
1266 }
1267
1268 // Detect if the file is readonly and change the readonly field if necessary (unix only)
1269 pub fn detect_readonly(&mut self) {
1270 // Allows setting the flag for files the user cannot modify, like root files
1271 self.readonly = match &self.path {
1272 None => false,
1273 Some(p) => readonly(p),
1274 };
1275 }
1276
1277 /// Reload the document from its path.
1278 pub fn reload(
1279 &mut self,
1280 view: &mut View,
1281 provider_registry: &DiffProviderRegistry,
1282 trust_full: bool,
1283 ) -> Result<(), Error> {
1284 let encoding = self.encoding;
1285 let path = match self.path() {
1286 None => return Ok(()),
1287 Some(path) => match path.exists() {
1288 true => path.to_owned(),
1289 false => bail!("can't find file to reload from {:?}", self.display_name()),
1290 },
1291 };
1292
1293 // Once we have a valid path we check if its readonly status has changed
1294 self.detect_readonly();
1295
1296 let mut file = std::fs::File::open(&path)?;
1297 let (rope, ..) = from_reader(&mut file, Some(encoding))?;
1298
1299 // Calculate the difference between the buffer and source text, and apply it.
1300 // This is not considered a modification of the contents of the file regardless
1301 // of the encoding.
1302 let transaction = helix_core::diff::compare_ropes(self.text(), &rope);
1303 self.apply(&transaction, view.id);
1304 self.append_changes_to_history(view);
1305 self.reset_modified();
1306 self.pickup_last_saved_time();
1307 self.detect_indent_and_line_ending();
1308
1309 match provider_registry.get_diff_base(&path, trust_full) {
1310 Some(diff_base) => self.set_diff_base(diff_base),
1311 None => self.diff_handle = None,
1312 }
1313
1314 self.version_control_head = provider_registry.get_current_head_name(&path, trust_full);
1315
1316 Ok(())
1317 }
1318
1319 /// Sets the [`Document`]'s encoding with the encoding correspondent to `label`.
1320 pub fn set_encoding(&mut self, label: &str) -> Result<(), Error> {
1321 let encoding =
1322 Encoding::for_label(label.as_bytes()).ok_or_else(|| anyhow!("unknown encoding"))?;
1323
1324 self.encoding = encoding;
1325
1326 Ok(())
1327 }
1328
1329 /// Returns the [`Document`]'s current encoding.
1330 pub fn encoding(&self) -> &'static Encoding {
1331 self.encoding
1332 }
1333
1334 /// sets the document path without sending events to various
1335 /// observers (like LSP), in most cases `Editor::set_doc_path`
1336 /// should be used instead
1337 pub fn set_path(&mut self, path: Option<&Path>) {
1338 let path = path.map(helix_stdx::path::canonicalize);
1339
1340 // `take` to remove any prior relative path that may have existed.
1341 // This will get set in `relative_path()`.
1342 self.relative_path.take();
1343 // Same story: invalidate so the next workspace_root() recomputes against the new path.
1344 self.workspace_root.take();
1345
1346 // if parent doesn't exist we still want to open the document
1347 // and error out when document is saved
1348 self.path = path;
1349
1350 self.detect_readonly();
1351 self.pickup_last_saved_time();
1352 }
1353
1354 /// Set the programming language for the file and load associated data (e.g. highlighting)
1355 /// if it exists.
1356 pub fn set_language(
1357 &mut self,
1358 language_config: Option<Arc<syntax::config::LanguageConfiguration>>,
1359 loader: &syntax::Loader,
1360 ) {
1361 self.language = language_config;
1362 self.syntax = self.language.as_ref().and_then(|config| {
1363 Syntax::new(self.text.slice(..), config.language(), loader)
1364 .map_err(|err| {
1365 // `NoRootConfig` means that there was an issue loading the language/syntax
1366 // config for the root language of the document. An error must have already
1367 // been logged by `LanguageData::syntax_config`.
1368 if err != syntax::HighlighterError::NoRootConfig {
1369 log::warn!("Error building syntax for '{}': {err}", self.display_name());
1370 }
1371 })
1372 .ok()
1373 });
1374 }
1375
1376 /// Set the programming language for the file if you know the language but don't have the
1377 /// [`syntax::config::LanguageConfiguration`] for it.
1378 pub fn set_language_by_language_id(
1379 &mut self,
1380 language_id: &str,
1381 loader: &syntax::Loader,
1382 ) -> anyhow::Result<()> {
1383 let language = loader
1384 .language_for_name(language_id)
1385 .ok_or_else(|| anyhow!("invalid language id: {}", language_id))?;
1386 let config = loader.language(language).config().clone();
1387 self.set_language(Some(config), loader);
1388 Ok(())
1389 }
1390
1391 /// Select text within the [`Document`].
1392 pub fn set_selection(&mut self, view_id: ViewId, selection: Selection) {
1393 // TODO: use a transaction?
1394 self.selections
1395 .insert(view_id, selection.ensure_invariants(self.text().slice(..)));
1396 helix_event::dispatch(SelectionDidChange {
1397 doc: self,
1398 view: view_id,
1399 })
1400 }
1401
1402 /// Find the origin selection of the text in a document, i.e. where
1403 /// a single cursor would go if it were on the first grapheme. If
1404 /// the text is empty, returns (0, 0).
1405 pub fn origin(&self) -> Range {
1406 if self.text().len_chars() == 0 {
1407 return Range::new(0, 0);
1408 }
1409
1410 Range::new(0, 1).grapheme_aligned(self.text().slice(..))
1411 }
1412
1413 /// Reset the view's selection on this document to the
1414 /// [origin](Document::origin) cursor.
1415 pub fn reset_selection(&mut self, view_id: ViewId) {
1416 let origin = self.origin();
1417 self.set_selection(view_id, Selection::single(origin.anchor, origin.head));
1418 }
1419
1420 /// Initializes a new selection and view_data for the given view
1421 /// if it does not already have them.
1422 pub fn ensure_view_init(&mut self, view_id: ViewId) {
1423 if !self.selections.contains_key(&view_id) {
1424 self.reset_selection(view_id);
1425 }
1426
1427 self.view_data_mut(view_id);
1428 }
1429
1430 /// Mark document as recent used for MRU sorting
1431 pub fn mark_as_focused(&mut self) {
1432 self.focused_at = std::time::Instant::now();
1433 }
1434
1435 /// Remove a view's selection and inlay hints from this document.
1436 pub fn remove_view(&mut self, view_id: ViewId) {
1437 self.selections.remove(&view_id);
1438 self.view_data.remove(&view_id);
1439 self.inlay_hints.remove(&view_id);
1440 self.jump_labels.remove(&view_id);
1441 self.document_highlights.remove(&view_id);
1442 self.document_highlight_controllers.remove(&view_id);
1443 self.code_action_hints.remove(&view_id);
1444 self.code_action_controllers.remove(&view_id);
1445 }
1446
1447 /// Apply a [`Transaction`] to the [`Document`] to change its text.
1448 fn apply_impl(
1449 &mut self,
1450 transaction: &Transaction,
1451 view_id: ViewId,
1452 emit_lsp_notification: bool,
1453 ) -> bool {
1454 use helix_core::Assoc;
1455
1456 let old_doc = self.text().clone();
1457 let changes = transaction.changes();
1458 if !changes.apply(&mut self.text) {
1459 return false;
1460 }
1461
1462 if changes.is_empty() {
1463 if let Some(selection) = transaction.selection() {
1464 self.selections.insert(
1465 view_id,
1466 selection.clone().ensure_invariants(self.text.slice(..)),
1467 );
1468 helix_event::dispatch(SelectionDidChange {
1469 doc: self,
1470 view: view_id,
1471 });
1472 }
1473 return true;
1474 }
1475
1476 self.modified_since_accessed = true;
1477 self.version += 1;
1478
1479 for selection in self.selections.values_mut() {
1480 *selection = selection
1481 .clone()
1482 // Map through changes
1483 .map(transaction.changes())
1484 // Ensure all selections across all views still adhere to invariants.
1485 .ensure_invariants(self.text.slice(..));
1486 }
1487
1488 for view_data in self.view_data.values_mut() {
1489 view_data.view_position.anchor = transaction
1490 .changes()
1491 .map_pos(view_data.view_position.anchor, Assoc::Before);
1492 }
1493
1494 // generate revert to savepoint
1495 if !self.savepoints.is_empty() {
1496 let revert = transaction.invert(&old_doc);
1497 self.savepoints
1498 .retain_mut(|save_point| match save_point.upgrade() {
1499 Some(savepoint) => {
1500 let mut revert_to_savepoint = savepoint.revert.lock();
1501 *revert_to_savepoint =
1502 revert.clone().compose(mem::take(&mut revert_to_savepoint));
1503 true
1504 }
1505 None => false,
1506 })
1507 }
1508
1509 // update tree-sitter syntax tree
1510 if let Some(syntax) = &mut self.syntax {
1511 let loader = self.syn_loader.load();
1512 if let Err(err) = syntax.update(
1513 old_doc.slice(..),
1514 self.text.slice(..),
1515 transaction.changes(),
1516 &loader,
1517 ) {
1518 log::error!("TS parser failed, disabling TS for the current buffer: {err}");
1519 self.syntax = None;
1520 }
1521 }
1522
1523 // TODO: all of that should likely just be hooks
1524 // start computing the diff in parallel
1525 if let Some(diff_handle) = &self.diff_handle {
1526 diff_handle.update_document(self.text.clone(), false);
1527 }
1528
1529 // map diagnostics over changes too
1530 changes.update_positions(self.diagnostics.iter_mut().map(|diagnostic| {
1531 let assoc = if diagnostic.starts_at_word {
1532 Assoc::BeforeWord
1533 } else {
1534 Assoc::After
1535 };
1536 (&mut diagnostic.range.start, assoc)
1537 }));
1538 changes.update_positions(self.diagnostics.iter_mut().filter_map(|diagnostic| {
1539 if diagnostic.zero_width {
1540 // for zero width diagnostics treat the diagnostic as a point
1541 // rather than a range
1542 return None;
1543 }
1544 let assoc = if diagnostic.ends_at_word {
1545 Assoc::AfterWord
1546 } else {
1547 Assoc::Before
1548 };
1549 Some((&mut diagnostic.range.end, assoc))
1550 }));
1551 self.diagnostics.retain_mut(|diagnostic| {
1552 if diagnostic.zero_width {
1553 diagnostic.range.end = diagnostic.range.start
1554 } else if diagnostic.range.start >= diagnostic.range.end {
1555 return false;
1556 }
1557 diagnostic.line = self.text.char_to_line(diagnostic.range.start);
1558 true
1559 });
1560
1561 self.diagnostics.sort_by_key(|diagnostic| {
1562 (
1563 diagnostic.range,
1564 diagnostic.severity,
1565 diagnostic.provider.clone(),
1566 )
1567 });
1568
1569 // Update the inlay hint annotations' positions, helping ensure they are displayed in the proper place
1570 let apply_inlay_hint_changes = |annotations: &mut Vec<InlineAnnotation>| {
1571 changes.update_positions(
1572 annotations
1573 .iter_mut()
1574 .map(|annotation| (&mut annotation.char_idx, Assoc::After)),
1575 );
1576 };
1577
1578 self.inlay_hints_oudated = true;
1579 for text_annotation in self.inlay_hints.values_mut() {
1580 let DocumentInlayHints {
1581 id: _,
1582 type_inlay_hints,
1583 parameter_inlay_hints,
1584 other_inlay_hints,
1585 padding_before_inlay_hints,
1586 padding_after_inlay_hints,
1587 } = text_annotation;
1588
1589 apply_inlay_hint_changes(padding_before_inlay_hints);
1590 apply_inlay_hint_changes(type_inlay_hints);
1591 apply_inlay_hint_changes(parameter_inlay_hints);
1592 apply_inlay_hint_changes(other_inlay_hints);
1593 apply_inlay_hint_changes(padding_after_inlay_hints);
1594 }
1595
1596 for highlights in self.document_highlights.values_mut() {
1597 let text_len = self.text.len_chars();
1598 let mut updated = Vec::with_capacity(highlights.ranges.len());
1599 for mut range in highlights.ranges.drain(..) {
1600 changes.update_positions(
1601 [
1602 (&mut range.start, Assoc::After),
1603 (&mut range.end, Assoc::After),
1604 ]
1605 .into_iter(),
1606 );
1607 if range.start >= text_len {
1608 continue;
1609 }
1610 let end = range.end.min(text_len);
1611 if range.start < end {
1612 updated.push(range.start..end);
1613 }
1614 }
1615 highlights.ranges = updated;
1616 }
1617
1618 helix_event::dispatch(DocumentDidChange {
1619 doc: self,
1620 view: view_id,
1621 old_text: &old_doc,
1622 changes,
1623 ghost_transaction: !emit_lsp_notification,
1624 });
1625
1626 // if specified, the current selection should instead be replaced by transaction.selection
1627 if let Some(selection) = transaction.selection() {
1628 self.selections.insert(
1629 view_id,
1630 selection.clone().ensure_invariants(self.text.slice(..)),
1631 );
1632 helix_event::dispatch(SelectionDidChange {
1633 doc: self,
1634 view: view_id,
1635 });
1636 }
1637
1638 true
1639 }
1640
1641 fn apply_inner(
1642 &mut self,
1643 transaction: &Transaction,
1644 view_id: ViewId,
1645 emit_lsp_notification: bool,
1646 ) -> bool {
1647 // store the state just before any changes are made. This allows us to undo to the
1648 // state just before a transaction was applied.
1649 if self.changes.is_empty() && !transaction.changes().is_empty() {
1650 self.old_state = Some(State {
1651 doc: self.text.clone(),
1652 selection: self.selection(view_id).clone(),
1653 });
1654 }
1655
1656 let success = self.apply_impl(transaction, view_id, emit_lsp_notification);
1657
1658 if !transaction.changes().is_empty() {
1659 // Compose this transaction with the previous one
1660 take_with(&mut self.changes, |changes| {
1661 changes.compose(transaction.changes().clone())
1662 });
1663 }
1664 success
1665 }
1666 /// Apply a [`Transaction`] to the [`Document`] to change its text.
1667 pub fn apply(&mut self, transaction: &Transaction, view_id: ViewId) -> bool {
1668 self.apply_inner(transaction, view_id, true)
1669 }
1670
1671 /// Apply a [`Transaction`] to the [`Document`] to change its text
1672 /// without notifying the language servers. This is useful for temporary transactions
1673 /// that must not influence the server.
1674 pub fn apply_temporary(&mut self, transaction: &Transaction, view_id: ViewId) -> bool {
1675 self.apply_inner(transaction, view_id, false)
1676 }
1677
1678 fn undo_redo_impl(&mut self, view: &mut View, undo: bool) -> bool {
1679 if undo {
1680 self.append_changes_to_history(view);
1681 } else if !self.changes.is_empty() {
1682 return false;
1683 }
1684 let mut history = self.history.take();
1685 let txn = if undo { history.undo() } else { history.redo() };
1686 let success = if let Some(txn) = txn {
1687 self.apply_impl(txn, view.id, true)
1688 } else {
1689 false
1690 };
1691 self.history.set(history);
1692
1693 if success {
1694 // reset changeset to fix len
1695 self.changes = ChangeSet::new(self.text().slice(..));
1696 // Sync with changes with the jumplist selections.
1697 view.sync_changes(self);
1698 }
1699 success
1700 }
1701
1702 /// Undo the last modification to the [`Document`]. Returns whether the undo was successful.
1703 pub fn undo(&mut self, view: &mut View) -> bool {
1704 self.undo_redo_impl(view, true)
1705 }
1706
1707 /// Redo the last modification to the [`Document`]. Returns whether the redo was successful.
1708 pub fn redo(&mut self, view: &mut View) -> bool {
1709 self.undo_redo_impl(view, false)
1710 }
1711
1712 /// Creates a reference counted snapshot (called savpepoint) of the document.
1713 ///
1714 /// The snapshot will remain valid (and updated) idenfinitly as long as ereferences to it exist.
1715 /// Restoring the snapshot will restore the selection and the contents of the document to
1716 /// the state it had when this function was called.
1717 pub fn savepoint(&mut self, view: &View) -> Arc<SavePoint> {
1718 let revert = Transaction::new(self.text()).with_selection(self.selection(view.id).clone());
1719 // check if there is already an existing (identical) savepoint around
1720 if let Some(savepoint) = self
1721 .savepoints
1722 .iter()
1723 .rev()
1724 .find_map(|savepoint| savepoint.upgrade())
1725 {
1726 let transaction = savepoint.revert.lock();
1727 if savepoint.view == view.id
1728 && transaction.changes().is_empty()
1729 && transaction.selection() == revert.selection()
1730 {
1731 drop(transaction);
1732 return savepoint;
1733 }
1734 }
1735 let savepoint = Arc::new(SavePoint {
1736 view: view.id,
1737 revert: Mutex::new(revert),
1738 });
1739 self.savepoints.push(Arc::downgrade(&savepoint));
1740 savepoint
1741 }
1742
1743 pub fn restore(&mut self, view: &mut View, savepoint: &SavePoint, emit_lsp_notification: bool) {
1744 assert_eq!(
1745 savepoint.view, view.id,
1746 "Savepoint must not be used with a different view!"
1747 );
1748 // search and remove savepoint using a ptr comparison
1749 // this avoids a deadlock as we need to lock the mutex
1750 let savepoint_idx = self
1751 .savepoints
1752 .iter()
1753 .position(|savepoint_ref| std::ptr::eq(savepoint_ref.as_ptr(), savepoint))
1754 .expect("Savepoint must belong to this document");
1755
1756 let savepoint_ref = self.savepoints.remove(savepoint_idx);
1757 let mut revert = savepoint.revert.lock();
1758 self.apply_inner(&revert, view.id, emit_lsp_notification);
1759 *revert = Transaction::new(self.text()).with_selection(self.selection(view.id).clone());
1760 self.savepoints.push(savepoint_ref)
1761 }
1762
1763 fn earlier_later_impl(&mut self, view: &mut View, uk: UndoKind, earlier: bool) -> bool {
1764 if earlier {
1765 self.append_changes_to_history(view);
1766 } else if !self.changes.is_empty() {
1767 return false;
1768 }
1769 let txns = if earlier {
1770 self.history.get_mut().earlier(uk)
1771 } else {
1772 self.history.get_mut().later(uk)
1773 };
1774 let mut success = false;
1775 for txn in txns {
1776 if self.apply_impl(&txn, view.id, true) {
1777 success = true;
1778 }
1779 }
1780 if success {
1781 // reset changeset to fix len
1782 self.changes = ChangeSet::new(self.text().slice(..));
1783 // Sync with changes with the jumplist selections.
1784 view.sync_changes(self);
1785 }
1786 success
1787 }
1788
1789 /// Undo modifications to the [`Document`] according to `uk`.
1790 pub fn earlier(&mut self, view: &mut View, uk: UndoKind) -> bool {
1791 self.earlier_later_impl(view, uk, true)
1792 }
1793
1794 /// Redo modifications to the [`Document`] according to `uk`.
1795 pub fn later(&mut self, view: &mut View, uk: UndoKind) -> bool {
1796 self.earlier_later_impl(view, uk, false)
1797 }
1798
1799 /// Commit pending changes to history
1800 pub fn append_changes_to_history(&mut self, view: &mut View) {
1801 if self.changes.is_empty() {
1802 return;
1803 }
1804
1805 let new_changeset = ChangeSet::new(self.text().slice(..));
1806 let changes = std::mem::replace(&mut self.changes, new_changeset);
1807 // Instead of doing this messy merge we could always commit, and based on transaction
1808 // annotations either add a new layer or compose into the previous one.
1809 let transaction =
1810 Transaction::from(changes).with_selection(self.selection(view.id).clone());
1811
1812 // HAXX: we need to reconstruct the state as it was before the changes..
1813 let old_state = self.old_state.take().expect("no old_state available");
1814
1815 let mut history = self.history.take();
1816 history.commit_revision(&transaction, &old_state);
1817 self.history.set(history);
1818
1819 // Update jumplist entries in the view.
1820 view.apply(&transaction, self);
1821 }
1822
1823 pub fn id(&self) -> DocumentId {
1824 self.id
1825 }
1826
1827 /// If there are unsaved modifications.
1828 pub fn is_modified(&self) -> bool {
1829 let history = self.history.take();
1830 let current_revision = history.current_revision();
1831 self.history.set(history);
1832 log::debug!(
1833 "id {} modified - last saved: {}, current: {}",
1834 self.id,
1835 self.last_saved_revision,
1836 current_revision
1837 );
1838 current_revision != self.last_saved_revision || !self.changes.is_empty()
1839 }
1840
1841 /// Save modifications to history, and so [`Self::is_modified`] will return false.
1842 pub fn reset_modified(&mut self) {
1843 let history = self.history.take();
1844 let current_revision = history.current_revision();
1845 self.history.set(history);
1846 self.last_saved_revision = current_revision;
1847 }
1848
1849 /// Set the document's latest saved revision to the given one.
1850 pub fn set_last_saved_revision(&mut self, rev: usize, save_time: SystemTime) {
1851 log::debug!(
1852 "doc {} revision updated {} -> {}",
1853 self.id,
1854 self.last_saved_revision,
1855 rev
1856 );
1857 self.last_saved_revision = rev;
1858 self.last_saved_time = save_time;
1859 }
1860
1861 /// Get the document's latest saved revision.
1862 pub fn get_last_saved_revision(&mut self) -> usize {
1863 self.last_saved_revision
1864 }
1865
1866 /// Get the current revision number
1867 pub fn get_current_revision(&mut self) -> usize {
1868 let history = self.history.take();
1869 let current_revision = history.current_revision();
1870 self.history.set(history);
1871 current_revision
1872 }
1873
1874 /// Corresponding language scope name. Usually `source.<lang>`.
1875 pub fn language_scope(&self) -> Option<&str> {
1876 self.language
1877 .as_ref()
1878 .map(|language| language.scope.as_str())
1879 }
1880
1881 /// Language name for the document. Corresponds to the `name` key in
1882 /// `languages.toml` configuration.
1883 pub fn language_name(&self) -> Option<&str> {
1884 self.language
1885 .as_ref()
1886 .map(|language| language.language_id.as_str())
1887 }
1888
1889 /// Language ID for the document. Either the `language-id`,
1890 /// or the document language name if no `language-id` has been specified.
1891 pub fn language_id(&self) -> Option<&str> {
1892 self.language_config()?
1893 .language_server_language_id
1894 .as_deref()
1895 .or_else(|| self.language_name())
1896 }
1897
1898 /// Corresponding [`LanguageConfiguration`].
1899 pub fn language_config(&self) -> Option<&LanguageConfiguration> {
1900 self.language.as_deref()
1901 }
1902
1903 /// The language configuration of the injection layer at `byte_pos`,
1904 /// so language-specific behavior follows embedded languages. Falls back to the
1905 /// document's root language config when there is no syntax tree.
1906 pub fn language_config_at<'a>(
1907 &'a self,
1908 loader: &'a syntax::Loader,
1909 byte_pos: usize,
1910 ) -> Option<&'a LanguageConfiguration> {
1911 match self.syntax() {
1912 Some(syntax) => {
1913 let layer = syntax.layer_for_byte_range(byte_pos as u32, byte_pos as u32);
1914 Some(&**loader.language(syntax.layer(layer).language).config())
1915 }
1916 None => self.language_config(),
1917 }
1918 }
1919
1920 /// Current document version, incremented at each change.
1921 pub fn version(&self) -> i32 {
1922 self.version
1923 }
1924
1925 pub fn word_completion_enabled(&self) -> bool {
1926 self.language_config()
1927 .and_then(|lang_config| lang_config.word_completion.and_then(|c| c.enable))
1928 .unwrap_or_else(|| self.config.load().word_completion.enable)
1929 }
1930
1931 pub fn path_completion_enabled(&self) -> bool {
1932 self.language_config()
1933 .and_then(|lang_config| lang_config.path_completion)
1934 .unwrap_or_else(|| self.config.load().path_completion)
1935 }
1936
1937 /// maintains the order as configured in the language_servers TOML array
1938 pub fn language_servers(&self) -> impl Iterator<Item = &helix_lsp::Client> {
1939 self.language_config().into_iter().flat_map(move |config| {
1940 config.language_servers.iter().filter_map(move |features| {
1941 let ls = &**self.language_servers.get(&features.name)?;
1942 if ls.is_initialized() {
1943 Some(ls)
1944 } else {
1945 None
1946 }
1947 })
1948 })
1949 }
1950
1951 pub fn remove_language_server_by_name(&mut self, name: &str) -> Option<Arc<Client>> {
1952 self.language_servers.remove(name)
1953 }
1954
1955 pub fn language_servers_with_feature(
1956 &self,
1957 feature: LanguageServerFeature,
1958 ) -> impl Iterator<Item = &helix_lsp::Client> {
1959 self.language_config().into_iter().flat_map(move |config| {
1960 config.language_servers.iter().filter_map(move |features| {
1961 let ls = &**self.language_servers.get(&features.name)?;
1962 if ls.is_initialized()
1963 && ls.supports_feature(feature)
1964 && features.has_feature(feature)
1965 {
1966 Some(ls)
1967 } else {
1968 None
1969 }
1970 })
1971 })
1972 }
1973
1974 pub fn supports_language_server(&self, id: LanguageServerId) -> bool {
1975 self.language_servers().any(|l| l.id() == id)
1976 }
1977
1978 pub fn servers_to_load(&self) -> bool {
1979 self.language_config()
1980 .map(|lang| !lang.language_servers.is_empty() || lang.debugger.is_some())
1981 .unwrap_or(false)
1982 }
1983
1984 pub fn diff_handle(&self) -> Option<&DiffHandle> {
1985 self.diff_handle.as_ref()
1986 }
1987
1988 /// Intialize/updates the differ for this document with a new base.
1989 pub fn set_diff_base(&mut self, diff_base: Vec<u8>) {
1990 if let Ok((diff_base, ..)) = from_reader(&mut diff_base.as_slice(), Some(self.encoding)) {
1991 if let Some(differ) = &self.diff_handle {
1992 differ.update_diff_base(diff_base);
1993 return;
1994 }
1995 self.diff_handle = Some(DiffHandle::new(diff_base, self.text.clone()))
1996 } else {
1997 self.diff_handle = None;
1998 }
1999 }
2000
2001 pub fn version_control_head(&self) -> Option<Arc<Box<str>>> {
2002 self.version_control_head.as_ref().map(|a| a.load_full())
2003 }
2004
2005 pub fn set_version_control_head(
2006 &mut self,
2007 version_control_head: Option<Arc<ArcSwap<Box<str>>>>,
2008 ) {
2009 self.version_control_head = version_control_head;
2010 }
2011
2012 #[inline]
2013 /// Tree-sitter AST tree
2014 pub fn syntax(&self) -> Option<&Syntax> {
2015 self.syntax.as_ref()
2016 }
2017
2018 /// The width that the tab character is rendered at
2019 pub fn tab_width(&self) -> usize {
2020 self.editor_config
2021 .tab_width
2022 .map(|n| n.get() as usize)
2023 .unwrap_or_else(|| {
2024 self.language_config()
2025 .and_then(|config| config.indent.as_ref())
2026 .map_or(DEFAULT_TAB_WIDTH, |config| config.tab_width)
2027 })
2028 }
2029
2030 // The width (in spaces) of a level of indentation.
2031 pub fn indent_width(&self) -> usize {
2032 self.indent_style.indent_width(self.tab_width())
2033 }
2034
2035 /// Whether the document should have a trailing line ending appended on save.
2036 pub fn insert_final_newline(&self) -> bool {
2037 self.editor_config
2038 .insert_final_newline
2039 .unwrap_or_else(|| self.config.load().insert_final_newline)
2040 }
2041
2042 /// Whether the document should trim whitespace preceding line endings on save.
2043 pub fn trim_trailing_whitespace(&self) -> bool {
2044 self.editor_config
2045 .trim_trailing_whitespace
2046 .unwrap_or_else(|| self.config.load().trim_trailing_whitespace)
2047 }
2048
2049 pub fn changes(&self) -> &ChangeSet {
2050 &self.changes
2051 }
2052
2053 #[inline]
2054 /// File path on disk.
2055 pub fn path(&self) -> Option<&Path> {
2056 self.path.as_deref()
2057 }
2058
2059 /// File path as a URL.
2060 pub fn url(&self) -> Option<Url> {
2061 Url::from_file_path(self.path()?).ok()
2062 }
2063
2064 pub fn uri(&self) -> Option<helix_core::Uri> {
2065 Some(self.path()?.into())
2066 }
2067
2068 #[inline]
2069 pub fn text(&self) -> &Rope {
2070 &self.text
2071 }
2072
2073 #[inline]
2074 pub fn selection(&self, view_id: ViewId) -> &Selection {
2075 &self.selections[&view_id]
2076 }
2077
2078 #[inline]
2079 pub fn selections(&self) -> &HashMap<ViewId, Selection> {
2080 &self.selections
2081 }
2082
2083 fn view_data(&self, view_id: ViewId) -> &ViewData {
2084 self.view_data
2085 .get(&view_id)
2086 .expect("This should only be called after ensure_view_init")
2087 }
2088
2089 fn view_data_mut(&mut self, view_id: ViewId) -> &mut ViewData {
2090 self.view_data.entry(view_id).or_default()
2091 }
2092
2093 pub(crate) fn get_view_offset(&self, view_id: ViewId) -> Option<ViewPosition> {
2094 Some(self.view_data.get(&view_id)?.view_position)
2095 }
2096
2097 pub fn view_offset(&self, view_id: ViewId) -> ViewPosition {
2098 self.view_data(view_id).view_position
2099 }
2100
2101 pub fn set_view_offset(&mut self, view_id: ViewId, new_offset: ViewPosition) {
2102 self.view_data_mut(view_id).view_position = new_offset;
2103 }
2104
2105 pub fn relative_path(&self) -> Option<&Path> {
2106 self.relative_path
2107 .get_or_init(|| {
2108 self.path
2109 .as_ref()
2110 .map(|path| helix_stdx::path::get_relative_path(path).to_path_buf())
2111 })
2112 .as_deref()
2113 }
2114
2115 /// The workspace root for this document — the nearest ancestor that contains a `.git`, `.svn`,
2116 /// `.jj`, or `.helix`. Falls back to the current working directory's workspace when the
2117 /// document has no path (scratch buffers). Lazily memoised on first call.
2118 pub fn workspace_root(&self) -> &Path {
2119 self.workspace_root
2120 .get_or_init(|| match self.path.as_deref() {
2121 Some(p) => p
2122 .parent()
2123 .map(|dir| helix_loader::find_workspace_in(dir).0)
2124 .unwrap_or_else(|| helix_loader::find_workspace().0),
2125 None => helix_loader::find_workspace().0,
2126 })
2127 }
2128
2129 pub fn display_name(&self) -> Cow<'_, str> {
2130 self.relative_path()
2131 .map_or_else(|| SCRATCH_BUFFER_NAME.into(), |path| path.to_string_lossy())
2132 }
2133
2134 // transact(Fn) ?
2135
2136 // -- LSP methods
2137
2138 #[inline]
2139 pub fn identifier(&self) -> lsp::TextDocumentIdentifier {
2140 lsp::TextDocumentIdentifier::new(self.url().unwrap())
2141 }
2142
2143 pub fn versioned_identifier(&self) -> lsp::VersionedTextDocumentIdentifier {
2144 lsp::VersionedTextDocumentIdentifier::new(self.url().unwrap(), self.version)
2145 }
2146
2147 pub fn position(
2148 &self,
2149 view_id: ViewId,
2150 offset_encoding: helix_lsp::OffsetEncoding,
2151 ) -> lsp::Position {
2152 let text = self.text();
2153
2154 helix_lsp::util::pos_to_lsp_pos(
2155 text,
2156 self.selection(view_id).primary().cursor(text.slice(..)),
2157 offset_encoding,
2158 )
2159 }
2160
2161 pub fn lsp_diagnostic_to_diagnostic(
2162 text: &Rope,
2163 language_config: Option<&LanguageConfiguration>,
2164 diagnostic: &helix_lsp::lsp::Diagnostic,
2165 provider: DiagnosticProvider,
2166 offset_encoding: helix_lsp::OffsetEncoding,
2167 ) -> Option<Diagnostic> {
2168 use helix_core::diagnostic::{Range, Severity::*};
2169
2170 // TODO: convert inside server
2171 let start =
2172 if let Some(start) = lsp_pos_to_pos(text, diagnostic.range.start, offset_encoding) {
2173 start
2174 } else {
2175 log::warn!("lsp position out of bounds - {:?}", diagnostic);
2176 return None;
2177 };
2178
2179 let end = if let Some(end) = lsp_pos_to_pos(text, diagnostic.range.end, offset_encoding) {
2180 end
2181 } else {
2182 log::warn!("lsp position out of bounds - {:?}", diagnostic);
2183 return None;
2184 };
2185
2186 let severity = diagnostic.severity.and_then(|severity| match severity {
2187 lsp::DiagnosticSeverity::ERROR => Some(Error),
2188 lsp::DiagnosticSeverity::WARNING => Some(Warning),
2189 lsp::DiagnosticSeverity::INFORMATION => Some(Info),
2190 lsp::DiagnosticSeverity::HINT => Some(Hint),
2191 severity => {
2192 log::error!("unrecognized diagnostic severity: {:?}", severity);
2193 None
2194 }
2195 });
2196
2197 if let Some(lang_conf) = language_config {
2198 if let Some(severity) = severity {
2199 if severity < lang_conf.diagnostic_severity {
2200 return None;
2201 }
2202 }
2203 };
2204 use helix_core::diagnostic::{DiagnosticTag, NumberOrString};
2205
2206 let code = match diagnostic.code.clone() {
2207 Some(x) => match x {
2208 lsp::NumberOrString::Number(x) => Some(NumberOrString::Number(x)),
2209 lsp::NumberOrString::String(x) => Some(NumberOrString::String(x)),
2210 },
2211 None => None,
2212 };
2213
2214 let tags = if let Some(tags) = &diagnostic.tags {
2215 let new_tags = tags
2216 .iter()
2217 .filter_map(|tag| match *tag {
2218 lsp::DiagnosticTag::DEPRECATED => Some(DiagnosticTag::Deprecated),
2219 lsp::DiagnosticTag::UNNECESSARY => Some(DiagnosticTag::Unnecessary),
2220 _ => None,
2221 })
2222 .collect();
2223
2224 new_tags
2225 } else {
2226 Vec::new()
2227 };
2228
2229 let ends_at_word =
2230 start != end && end != 0 && text.get_char(end - 1).is_some_and(char_is_word);
2231 let starts_at_word = start != end && text.get_char(start).is_some_and(char_is_word);
2232
2233 Some(Diagnostic {
2234 range: Range { start, end },
2235 ends_at_word,
2236 starts_at_word,
2237 zero_width: start == end,
2238 line: diagnostic.range.start.line as usize,
2239 message: diagnostic.message.clone(),
2240 severity,
2241 code,
2242 tags,
2243 source: diagnostic.source.clone(),
2244 data: diagnostic.data.clone(),
2245 provider,
2246 })
2247 }
2248
2249 #[inline]
2250 pub fn diagnostics(&self) -> &[Diagnostic] {
2251 &self.diagnostics
2252 }
2253
2254 pub fn replace_diagnostics(
2255 &mut self,
2256 diagnostics: impl IntoIterator<Item = Diagnostic>,
2257 unchanged_sources: &[String],
2258 provider: Option<&DiagnosticProvider>,
2259 ) {
2260 if unchanged_sources.is_empty() {
2261 if let Some(provider) = provider {
2262 self.diagnostics
2263 .retain(|diagnostic| &diagnostic.provider != provider);
2264 } else {
2265 self.diagnostics.clear();
2266 }
2267 } else {
2268 self.diagnostics.retain(|d| {
2269 if provider.is_some_and(|provider| provider != &d.provider) {
2270 return true;
2271 }
2272
2273 if let Some(source) = &d.source {
2274 unchanged_sources.contains(source)
2275 } else {
2276 false
2277 }
2278 });
2279 }
2280 self.diagnostics.extend(diagnostics);
2281 self.diagnostics.sort_by_key(|diagnostic| {
2282 (
2283 diagnostic.range,
2284 diagnostic.severity,
2285 diagnostic.provider.clone(),
2286 )
2287 });
2288 }
2289
2290 /// clears diagnostics for a given language server id if set, otherwise all diagnostics are cleared
2291 pub fn clear_diagnostics_for_language_server(&mut self, id: LanguageServerId) {
2292 self.diagnostics
2293 .retain(|d| d.provider.language_server_id() != Some(id));
2294 }
2295
2296 /// Get the document's auto pairs. If the document has a recognized
2297 /// language config with auto pairs configured, returns that;
2298 /// otherwise, falls back to the global auto pairs config. If the global
2299 /// config is false, then ignore language settings.
2300 pub fn auto_pairs<'a>(
2301 &'a self,
2302 editor: &'a Editor,
2303 loader: &'a syntax::Loader,
2304 view: &View,
2305 ) -> Option<&'a AutoPairs> {
2306 let global_config = (editor.auto_pairs).as_ref();
2307
2308 // NOTE: If the user specifies the global auto pairs config as false, then
2309 // we want to disable it globally regardless of language settings
2310 #[allow(clippy::question_mark)]
2311 {
2312 if global_config.is_none() {
2313 return None;
2314 }
2315 }
2316
2317 self.syntax
2318 .as_ref()
2319 .and_then(|syntax| {
2320 let selection = self.selection(view.id).primary();
2321 let (start, end) = selection.into_byte_range(self.text().slice(..));
2322 let layer = syntax.layer_for_byte_range(start as u32, end as u32);
2323
2324 let lang_config = loader.language(syntax.layer(layer).language).config();
2325 lang_config.auto_pairs.as_ref()
2326 })
2327 .or(global_config)
2328 }
2329
2330 pub fn snippet_ctx(&self) -> SnippetRenderCtx {
2331 SnippetRenderCtx {
2332 // TODO snippet variable resolution
2333 resolve_var: Box::new(|_| None),
2334 tab_width: self.tab_width(),
2335 indent_style: self.indent_style,
2336 line_ending: self.line_ending.as_str(),
2337 }
2338 }
2339
2340 pub fn text_width(&self) -> usize {
2341 self.editor_config
2342 .max_line_length
2343 .map(|n| n.get() as usize)
2344 .or_else(|| self.language_config().and_then(|config| config.text_width))
2345 .unwrap_or_else(|| self.config.load().text_width)
2346 }
2347
2348 pub fn text_format(&self, mut viewport_width: u16, theme: Option<&Theme>) -> TextFormat {
2349 let config = self.config.load();
2350 let text_width = self.text_width();
2351 let mut soft_wrap_at_text_width = self
2352 .language_config()
2353 .and_then(|config| {
2354 config
2355 .soft_wrap
2356 .as_ref()
2357 .and_then(|soft_wrap| soft_wrap.wrap_at_text_width)
2358 })
2359 .or(config.soft_wrap.wrap_at_text_width)
2360 .unwrap_or(false);
2361 if soft_wrap_at_text_width {
2362 // if the viewport is smaller than the specified
2363 // width then this setting has no effcet
2364 if text_width >= viewport_width as usize {
2365 soft_wrap_at_text_width = false;
2366 } else {
2367 viewport_width = text_width as u16;
2368 }
2369 }
2370 let config = self.config.load();
2371 let editor_soft_wrap = &config.soft_wrap;
2372 let language_soft_wrap = self
2373 .language
2374 .as_ref()
2375 .and_then(|config| config.soft_wrap.as_ref());
2376 let enable_soft_wrap = language_soft_wrap
2377 .and_then(|soft_wrap| soft_wrap.enable)
2378 .or(editor_soft_wrap.enable)
2379 .unwrap_or(false);
2380 let max_wrap = language_soft_wrap
2381 .and_then(|soft_wrap| soft_wrap.max_wrap)
2382 .or(config.soft_wrap.max_wrap)
2383 .unwrap_or(20);
2384 let max_indent_retain = language_soft_wrap
2385 .and_then(|soft_wrap| soft_wrap.max_indent_retain)
2386 .or(editor_soft_wrap.max_indent_retain)
2387 .unwrap_or(40);
2388 let wrap_indicator = language_soft_wrap
2389 .and_then(|soft_wrap| soft_wrap.wrap_indicator.clone())
2390 .or_else(|| config.soft_wrap.wrap_indicator.clone())
2391 .unwrap_or_else(|| "↪ ".into());
2392 let tab_width = self.tab_width() as u16;
2393 TextFormat {
2394 soft_wrap: enable_soft_wrap && viewport_width > 10,
2395 tab_width,
2396 max_wrap: max_wrap.min(viewport_width / 4),
2397 max_indent_retain: max_indent_retain.min(viewport_width * 2 / 5),
2398 // avoid spinning forever when the window manager
2399 // sets the size to something tiny
2400 viewport_width,
2401 wrap_indicator: wrap_indicator.into_boxed_str(),
2402 wrap_indicator_highlight: theme
2403 .and_then(|theme| theme.find_highlight("ui.virtual.wrap")),
2404 soft_wrap_at_text_width,
2405 }
2406 }
2407
2408 /// Set the inlay hints for this document and `view_id`.
2409 pub fn set_inlay_hints(&mut self, view_id: ViewId, inlay_hints: DocumentInlayHints) {
2410 self.inlay_hints.insert(view_id, inlay_hints);
2411 }
2412
2413 pub fn set_jump_labels(&mut self, view_id: ViewId, labels: Vec<Overlay>) {
2414 self.jump_labels.insert(view_id, labels);
2415 }
2416
2417 pub fn remove_jump_labels(&mut self, view_id: ViewId) {
2418 self.jump_labels.remove(&view_id);
2419 }
2420
2421 pub fn set_document_highlights(
2422 &mut self,
2423 view_id: ViewId,
2424 ranges: Vec<std::ops::Range<usize>>,
2425 ) {
2426 if ranges.is_empty() {
2427 self.document_highlights.remove(&view_id);
2428 } else {
2429 self.document_highlights
2430 .insert(view_id, DocumentHighlights { ranges });
2431 }
2432 }
2433
2434 pub fn clear_document_highlights(&mut self, view_id: ViewId) {
2435 self.document_highlights.remove(&view_id);
2436 }
2437
2438 pub fn clear_all_document_highlights(&mut self) {
2439 self.document_highlights.clear();
2440 self.document_highlight_controllers.clear();
2441 }
2442
2443 pub fn document_highlights(&self, view_id: ViewId) -> Option<&[std::ops::Range<usize>]> {
2444 self.document_highlights
2445 .get(&view_id)
2446 .map(|highlights| highlights.ranges.as_slice())
2447 }
2448
2449 pub fn document_highlight_controller(&mut self, view_id: ViewId) -> &mut TaskController {
2450 self.document_highlight_controllers
2451 .entry(view_id)
2452 .or_default()
2453 }
2454
2455 pub fn set_code_action_hints(&mut self, view_id: ViewId) {
2456 self.code_action_hints.insert(view_id);
2457 }
2458
2459 pub fn clear_code_action_hints(&mut self, view_id: ViewId) {
2460 self.code_action_hints.remove(&view_id);
2461 }
2462
2463 pub fn clear_all_code_action_hints(&mut self) {
2464 self.code_action_hints.clear();
2465 self.code_action_controllers.clear();
2466 }
2467
2468 pub fn code_action_hints(&self, view_id: ViewId) -> bool {
2469 self.code_action_hints.contains(&view_id)
2470 }
2471
2472 pub fn code_action_controller(&mut self, view_id: ViewId) -> &mut TaskController {
2473 self.code_action_controllers.entry(view_id).or_default()
2474 }
2475
2476 /// Get the inlay hints for this document and `view_id`.
2477 pub fn inlay_hints(&self, view_id: ViewId) -> Option<&DocumentInlayHints> {
2478 self.inlay_hints.get(&view_id)
2479 }
2480
2481 /// Completely removes all the inlay hints saved for the document, dropping them to free memory
2482 /// (since it often means inlay hints have been fully deactivated).
2483 pub fn reset_all_inlay_hints(&mut self) {
2484 self.inlay_hints = Default::default();
2485 }
2486
2487 pub fn has_language_server_with_feature(&self, feature: LanguageServerFeature) -> bool {
2488 self.language_servers_with_feature(feature).next().is_some()
2489 }
2490 }
2491
2492 #[derive(Debug, Default)]
2493 pub struct ViewData {
2494 view_position: ViewPosition,
2495 }
2496
2497 #[derive(Clone, Debug)]
2498 pub enum FormatterError {
2499 SpawningFailed {
2500 command: String,
2501 error: std::io::ErrorKind,
2502 },
2503 BrokenStdin,
2504 WaitForOutputFailed,
2505 InvalidUtf8Output,
2506 NonZeroExitStatus(Option<String>),
2507 }
2508
2509 impl std::error::Error for FormatterError {}
2510
2511 impl Display for FormatterError {
2512 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
2513 match self {
2514 Self::SpawningFailed { command, error } => {
2515 write!(f, "Failed to spawn formatter {}: {:?}", command, error)
2516 }
2517 Self::BrokenStdin => write!(f, "Could not write to formatter stdin"),
2518 Self::WaitForOutputFailed => write!(f, "Waiting for formatter output failed"),
2519 Self::InvalidUtf8Output => write!(f, "Invalid UTF-8 formatter output"),
2520 Self::NonZeroExitStatus(Some(output)) => write!(f, "Formatter error: {}", output),
2521 Self::NonZeroExitStatus(None) => {
2522 write!(f, "Formatter exited with non zero exit status")
2523 }
2524 }
2525 }
2526 }
2527
2528 #[cfg(test)]
2529 mod test {
2530 use arc_swap::ArcSwap;
2531
2532 use super::*;
2533
2534 #[test]
2535 fn changeset_to_changes_ignore_line_endings() {
2536 use helix_lsp::{lsp, Client, OffsetEncoding};
2537 let text = Rope::from("hello\r\nworld");
2538 let mut doc = Document::from(
2539 text,
2540 None,
2541 Arc::new(ArcSwap::new(Arc::new(Config::default()))),
2542 Arc::new(ArcSwap::from_pointee(syntax::Loader::default())),
2543 );
2544 let view = ViewId::default();
2545 doc.set_selection(view, Selection::single(0, 0));
2546
2547 let transaction =
2548 Transaction::change(doc.text(), vec![(5, 7, Some("\n".into()))].into_iter());
2549 let old_doc = doc.text().clone();
2550 doc.apply(&transaction, view);
2551 let changes = Client::changeset_to_changes(
2552 &old_doc,
2553 doc.text(),
2554 transaction.changes(),
2555 OffsetEncoding::Utf8,
2556 );
2557
2558 assert_eq!(doc.text(), "hello\nworld");
2559
2560 assert_eq!(
2561 changes,
2562 &[lsp::TextDocumentContentChangeEvent {
2563 range: Some(lsp::Range::new(
2564 lsp::Position::new(0, 5),
2565 lsp::Position::new(1, 0)
2566 )),
2567 text: "\n".into(),
2568 range_length: None,
2569 }]
2570 );
2571 }
2572
2573 #[test]
2574 fn changeset_to_changes() {
2575 use helix_lsp::{lsp, Client, OffsetEncoding};
2576 let text = Rope::from("hello");
2577 let mut doc = Document::from(
2578 text,
2579 None,
2580 Arc::new(ArcSwap::new(Arc::new(Config::default()))),
2581 Arc::new(ArcSwap::from_pointee(syntax::Loader::default())),
2582 );
2583 let view = ViewId::default();
2584 doc.set_selection(view, Selection::single(5, 5));
2585
2586 // insert
2587
2588 let transaction = Transaction::insert(doc.text(), doc.selection(view), " world".into());
2589 let old_doc = doc.text().clone();
2590 doc.apply(&transaction, view);
2591 let changes = Client::changeset_to_changes(
2592 &old_doc,
2593 doc.text(),
2594 transaction.changes(),
2595 OffsetEncoding::Utf8,
2596 );
2597
2598 assert_eq!(
2599 changes,
2600 &[lsp::TextDocumentContentChangeEvent {
2601 range: Some(lsp::Range::new(
2602 lsp::Position::new(0, 5),
2603 lsp::Position::new(0, 5)
2604 )),
2605 text: " world".into(),
2606 range_length: None,
2607 }]
2608 );
2609
2610 // delete
2611
2612 let transaction = transaction.invert(&old_doc);
2613 let old_doc = doc.text().clone();
2614 doc.apply(&transaction, view);
2615 let changes = Client::changeset_to_changes(
2616 &old_doc,
2617 doc.text(),
2618 transaction.changes(),
2619 OffsetEncoding::Utf8,
2620 );
2621
2622 // line: 0-based.
2623 // col: 0-based, gaps between chars.
2624 // 0 1 2 3 4 5 6 7 8 9 0 1
2625 // |h|e|l|l|o| |w|o|r|l|d|
2626 // -------------
2627 // (0, 5)-(0, 11)
2628 assert_eq!(
2629 changes,
2630 &[lsp::TextDocumentContentChangeEvent {
2631 range: Some(lsp::Range::new(
2632 lsp::Position::new(0, 5),
2633 lsp::Position::new(0, 11)
2634 )),
2635 text: "".into(),
2636 range_length: None,
2637 }]
2638 );
2639
2640 // replace
2641
2642 // also tests that changes are layered, positions depend on previous changes.
2643
2644 doc.set_selection(view, Selection::single(0, 5));
2645 let transaction = Transaction::change(
2646 doc.text(),
2647 vec![(0, 2, Some("aei".into())), (3, 5, Some("ou".into()))].into_iter(),
2648 );
2649 // aeilou
2650 let old_doc = doc.text().clone();
2651 doc.apply(&transaction, view);
2652 let changes = Client::changeset_to_changes(
2653 &old_doc,
2654 doc.text(),
2655 transaction.changes(),
2656 OffsetEncoding::Utf8,
2657 );
2658
2659 assert_eq!(
2660 changes,
2661 &[
2662 // 0 1 2 3 4 5
2663 // |h|e|l|l|o|
2664 // ----
2665 //
2666 // aeillo
2667 lsp::TextDocumentContentChangeEvent {
2668 range: Some(lsp::Range::new(
2669 lsp::Position::new(0, 0),
2670 lsp::Position::new(0, 2)
2671 )),
2672 text: "aei".into(),
2673 range_length: None,
2674 },
2675 // 0 1 2 3 4 5 6
2676 // |a|e|i|l|l|o|
2677 // -----
2678 //
2679 // aeilou
2680 lsp::TextDocumentContentChangeEvent {
2681 range: Some(lsp::Range::new(
2682 lsp::Position::new(0, 4),
2683 lsp::Position::new(0, 6)
2684 )),
2685 text: "ou".into(),
2686 range_length: None,
2687 }
2688 ]
2689 );
2690 }
2691
2692 #[test]
2693 fn test_line_ending() {
2694 assert_eq!(
2695 Document::default(
2696 Arc::new(ArcSwap::new(Arc::new(Config::default()))),
2697 Arc::new(ArcSwap::from_pointee(syntax::Loader::default()))
2698 )
2699 .text()
2700 .to_string(),
2701 helix_core::NATIVE_LINE_ENDING.as_str()
2702 );
2703 }
2704
2705 macro_rules! decode {
2706 ($name:ident, $label:expr, $label_override:expr) => {
2707 #[test]
2708 fn $name() {
2709 let encoding = encoding::Encoding::for_label($label_override.as_bytes()).unwrap();
2710 let base_path = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("tests/encoding");
2711 let path = base_path.join(format!("{}_in.txt", $label));
2712 let ref_path = base_path.join(format!("{}_in_ref.txt", $label));
2713 assert!(path.exists());
2714 assert!(ref_path.exists());
2715
2716 let mut file = std::fs::File::open(path).unwrap();
2717 let text = from_reader(&mut file, Some(encoding.into()))
2718 .unwrap()
2719 .0
2720 .to_string();
2721 let expectation = std::fs::read_to_string(ref_path).unwrap();
2722 assert_eq!(text[..], expectation[..]);
2723 }
2724 };
2725 ($name:ident, $label:expr) => {
2726 decode!($name, $label, $label);
2727 };
2728 }
2729
2730 macro_rules! encode {
2731 ($name:ident, $label:expr, $label_override:expr) => {
2732 #[test]
2733 fn $name() {
2734 let encoding = encoding::Encoding::for_label($label_override.as_bytes()).unwrap();
2735 let base_path = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("tests/encoding");
2736 let path = base_path.join(format!("{}_out.txt", $label));
2737 let ref_path = base_path.join(format!("{}_out_ref.txt", $label));
2738 assert!(path.exists());
2739 assert!(ref_path.exists());
2740
2741 let text = Rope::from_str(&std::fs::read_to_string(path).unwrap());
2742 let mut buf: Vec<u8> = Vec::new();
2743 helix_lsp::block_on(to_writer(&mut buf, (encoding, false), &text)).unwrap();
2744
2745 let expectation = std::fs::read(ref_path).unwrap();
2746 assert_eq!(buf, expectation);
2747 }
2748 };
2749 ($name:ident, $label:expr) => {
2750 encode!($name, $label, $label);
2751 };
2752 }
2753
2754 decode!(big5_decode, "big5");
2755 encode!(big5_encode, "big5");
2756 decode!(euc_kr_decode, "euc_kr", "EUC-KR");
2757 encode!(euc_kr_encode, "euc_kr", "EUC-KR");
2758 decode!(gb18030_decode, "gb18030");
2759 encode!(gb18030_encode, "gb18030");
2760 decode!(iso_2022_jp_decode, "iso_2022_jp", "ISO-2022-JP");
2761 encode!(iso_2022_jp_encode, "iso_2022_jp", "ISO-2022-JP");
2762 decode!(jis0208_decode, "jis0208", "EUC-JP");
2763 encode!(jis0208_encode, "jis0208", "EUC-JP");
2764 decode!(jis0212_decode, "jis0212", "EUC-JP");
2765 decode!(shift_jis_decode, "shift_jis");
2766 encode!(shift_jis_encode, "shift_jis");
2767 }