Debian Codegraph @

helix-view/src/document.rs

raw symbols ◀ ▶
Source reconstructed at patch state 0 of 1 — not the installed (fully patched) source.
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 =
621 chardetng::EncodingDetector::new(chardetng::Iso2022JpDetection::Allow);
622 encoding_detector.feed(buf, is_empty);
623 (
624 encoding_detector.guess(None, chardetng::Utf8Detection::Allow),
625 false,
626 )
627 });
628 let decoder = encoding.new_decoder();
629
630 Ok((encoding, has_bom, decoder, read))
631 }
632
633 // The documentation and implementation of this function should be up-to-date with
634 // its sibling function, `from_reader()`.
635 //
636 /// Encodes the text inside `rope` into the given `encoding` and writes the
637 /// encoded output into `writer.` As a `Rope` can only contain valid UTF-8,
638 /// replacement characters may appear in the encoded text.
639 pub async fn to_writer<'a, W: tokio::io::AsyncWriteExt + Unpin + ?Sized>(
640 writer: &'a mut W,
641 encoding_with_bom_info: (&'static Encoding, bool),
642 rope: &'a Rope,
643 ) -> Result<(), Error> {
644 // Text inside a `Rope` is stored as non-contiguous blocks of data called
645 // chunks. The absolute size of each chunk is unknown, thus it is impossible
646 // to predict the end of the chunk iterator ahead of time. Instead, it is
647 // determined by filtering the iterator to remove all empty chunks and then
648 // appending an empty chunk to it. This is valuable for detecting when all
649 // chunks in the `Rope` have been iterated over in the subsequent loop.
650 let (encoding, has_bom) = encoding_with_bom_info;
651
652 let iter = rope
653 .chunks()
654 .filter(|c| !c.is_empty())
655 .chain(std::iter::once(""));
656 let mut buf = [0u8; BUF_SIZE];
657
658 let mut total_written = if has_bom {
659 apply_bom(encoding, &mut buf)
660 } else {
661 0
662 };
663
664 let mut encoder = Encoder::from_encoding(encoding);
665
666 for chunk in iter {
667 let is_empty = chunk.is_empty();
668 let mut total_read = 0usize;
669
670 // An inner loop is necessary as it is possible that the input buffer
671 // may not be completely encoded on the first `encode_from_utf8()` call
672 // which would happen in cases where the output buffer is filled to
673 // capacity.
674 loop {
675 let (result, read, written, ..) =
676 encoder.encode_from_utf8(&chunk[total_read..], &mut buf[total_written..], is_empty);
677
678 // These variables act as the read and write cursors of `chunk` and `buf` respectively.
679 // They are necessary in case the output buffer fills before encoding of the entire input
680 // loop is complete. Otherwise, the loop would endlessly iterate over the same `chunk` and
681 // the data inside the output buffer would be overwritten.
682 total_read += read;
683 total_written += written;
684 match result {
685 encoding::CoderResult::InputEmpty => {
686 debug_assert_eq!(chunk.len(), total_read);
687 debug_assert!(buf.len() >= total_written);
688 break;
689 }
690 encoding::CoderResult::OutputFull => {
691 debug_assert!(chunk.len() > total_read);
692 writer.write_all(&buf[..total_written]).await?;
693 total_written = 0;
694 }
695 }
696 }
697
698 // Once the end of the iterator is reached, the output buffer is
699 // flushed and the outer loop terminates.
700 if is_empty {
701 writer.write_all(&buf[..total_written]).await?;
702 writer.flush().await?;
703 break;
704 }
705 }
706
707 Ok(())
708 }
709
710 fn take_with<T, F>(mut_ref: &mut T, f: F)
711 where
712 T: Default,
713 F: FnOnce(T) -> T,
714 {
715 *mut_ref = f(mem::take(mut_ref));
716 }
717
718 use helix_lsp::{lsp, Client, LanguageServerId, LanguageServerName};
719 use helix_stdx::Url;
720
721 impl Document {
722 pub fn from(
723 text: Rope,
724 encoding_with_bom_info: Option<(&'static Encoding, bool)>,
725 config: Arc<dyn DynAccess<Config>>,
726 syn_loader: Arc<ArcSwap<syntax::Loader>>,
727 ) -> Self {
728 let (encoding, has_bom) = encoding_with_bom_info.unwrap_or((encoding::UTF_8, false));
729 let line_ending = config.load().default_line_ending.into();
730 let changes = ChangeSet::new(text.slice(..));
731 let old_state = None;
732
733 Self {
734 id: DocumentId::default(),
735 active_snippet: None,
736 path: None,
737 relative_path: OnceCell::new(),
738 workspace_root: OnceCell::new(),
739 encoding,
740 has_bom,
741 text,
742 selections: HashMap::default(),
743 inlay_hints: HashMap::default(),
744 inlay_hints_oudated: false,
745 view_data: Default::default(),
746 indent_style: DEFAULT_INDENT,
747 editor_config: EditorConfig::default(),
748 line_ending,
749 restore_cursor: false,
750 syntax: None,
751 language: None,
752 changes,
753 old_state,
754 diagnostics: Vec::new(),
755 version: 0,
756 history: Cell::new(History::default()),
757 savepoints: Vec::new(),
758 last_saved_time: SystemTime::now(),
759 last_saved_revision: 0,
760 modified_since_accessed: false,
761 language_servers: HashMap::new(),
762 diff_handle: None,
763 config,
764 version_control_head: None,
765 focused_at: std::time::Instant::now(),
766 readonly: false,
767 jump_labels: HashMap::new(),
768 document_highlights: HashMap::new(),
769 code_action_hints: HashSet::new(),
770 color_swatches: None,
771 document_links: Vec::new(),
772 color_swatch_controller: TaskController::new(),
773 document_highlight_controllers: HashMap::new(),
774 code_action_controllers: HashMap::new(),
775 syn_loader,
776 previous_diagnostic_ids: HashMap::new(),
777 pull_diagnostic_controller: TaskController::new(),
778 document_link_controller: TaskController::new(),
779 }
780 }
781
782 pub fn default(
783 config: Arc<dyn DynAccess<Config>>,
784 syn_loader: Arc<ArcSwap<syntax::Loader>>,
785 ) -> Self {
786 let line_ending: LineEnding = config.load().default_line_ending.into();
787 let text = Rope::from(line_ending.as_str());
788 Self::from(text, None, config, syn_loader)
789 }
790
791 // TODO: async fn?
792 /// Create a new document from `path`. Encoding is auto-detected, but it can be manually
793 /// overwritten with the `encoding` parameter.
794 pub fn open(
795 path: &Path,
796 mut encoding: Option<&'static Encoding>,
797 detect_language: bool,
798 config: Arc<dyn DynAccess<Config>>,
799 syn_loader: Arc<ArcSwap<syntax::Loader>>,
800 ) -> Result<Self, DocumentOpenError> {
801 // If the path is not a regular file (e.g.: /dev/random) it should not be opened.
802 if path.metadata().is_ok_and(|metadata| !metadata.is_file()) {
803 return Err(DocumentOpenError::IrregularFile);
804 }
805
806 let editor_config = if config.load().editor_config {
807 EditorConfig::find(path)
808 } else {
809 EditorConfig::default()
810 };
811 encoding = encoding.or(editor_config.encoding);
812
813 // Open the file if it exists, otherwise assume it is a new file (and thus empty).
814 let (rope, encoding, has_bom) = if path.exists() {
815 let mut file = std::fs::File::open(path)?;
816 from_reader(&mut file, encoding)?
817 } else {
818 let line_ending = editor_config
819 .line_ending
820 .unwrap_or_else(|| config.load().default_line_ending.into());
821 let encoding = encoding.unwrap_or(encoding::UTF_8);
822 (Rope::from(line_ending.as_str()), encoding, false)
823 };
824
825 let loader = syn_loader.load();
826 let mut doc = Self::from(rope, Some((encoding, has_bom)), config, syn_loader);
827
828 // set the path and try detecting the language
829 doc.set_path(Some(path));
830 if detect_language {
831 doc.detect_language(&loader);
832 }
833
834 doc.editor_config = editor_config;
835 doc.detect_indent_and_line_ending();
836
837 Ok(doc)
838 }
839
840 /// The same as [`format`], but only returns formatting changes if auto-formatting
841 /// is configured.
842 pub fn auto_format(
843 &self,
844 editor: &Editor,
845 ) -> Option<BoxFuture<'static, Result<Transaction, FormatterError>>> {
846 if self.language_config()?.auto_format {
847 self.format(editor)
848 } else {
849 None
850 }
851 }
852
853 /// If supported, returns the changes that should be applied to this document in order
854 /// to format it nicely.
855 // We can't use anyhow::Result here since the output of the future has to be
856 // clonable to be used as shared future. So use a custom error type.
857 pub fn format(
858 &self,
859 editor: &Editor,
860 ) -> Option<BoxFuture<'static, Result<Transaction, FormatterError>>> {
861 if let Some((fmt_cmd, fmt_args)) = self
862 .language_config()
863 .and_then(|c| c.formatter.as_ref())
864 .and_then(|formatter| {
865 Some((
866 helix_stdx::env::which(&formatter.command).ok()?,
867 &formatter.args,
868 ))
869 })
870 {
871 log::debug!(
872 "formatting '{}' with command '{}', args {fmt_args:?}",
873 self.display_name(),
874 fmt_cmd.display(),
875 );
876 use std::process::Stdio;
877 let text = self.text().clone();
878
879 let mut process = tokio::process::Command::new(&fmt_cmd);
880
881 if let Some(doc_dir) = self.path.as_ref().and_then(|path| path.parent()) {
882 process.current_dir(doc_dir);
883 }
884
885 let args = match fmt_args
886 .iter()
887 .map(|content| expansion::expand(editor, Token::expand(content)))
888 .collect::<Result<Vec<_>, _>>()
889 {
890 Ok(args) => args,
891 Err(err) => {
892 log::error!("Failed to expand formatter arguments: {err}");
893 return None;
894 }
895 };
896
897 process
898 .args(args.iter().map(AsRef::as_ref))
899 .stdin(Stdio::piped())
900 .stdout(Stdio::piped())
901 .stderr(Stdio::piped());
902
903 let formatting_future = async move {
904 let mut process = process
905 .spawn()
906 .map_err(|e| FormatterError::SpawningFailed {
907 command: fmt_cmd.to_string_lossy().into(),
908 error: e.kind(),
909 })?;
910
911 let mut stdin = process.stdin.take().ok_or(FormatterError::BrokenStdin)?;
912 let input_text = text.clone();
913 let input_task = tokio::spawn(async move {
914 to_writer(&mut stdin, (encoding::UTF_8, false), &input_text).await
915 // Note that `stdin` is dropped here, causing the pipe to close. This can
916 // avoid a deadlock with `wait_with_output` below if the process is waiting on
917 // stdin to close before exiting.
918 });
919 let (input_result, output_result) = tokio::join! {
920 input_task,
921 process.wait_with_output(),
922 };
923 let _ = input_result.map_err(|_| FormatterError::BrokenStdin)?;
924 let output = output_result.map_err(|_| FormatterError::WaitForOutputFailed)?;
925
926 if !output.status.success() {
927 if !output.stderr.is_empty() {
928 let err = String::from_utf8_lossy(&output.stderr).to_string();
929 log::error!("Formatter error: {}", err);
930 return Err(FormatterError::NonZeroExitStatus(Some(err)));
931 }
932
933 return Err(FormatterError::NonZeroExitStatus(None));
934 } else if !output.stderr.is_empty() {
935 log::debug!(
936 "Formatter printed to stderr: {}",
937 String::from_utf8_lossy(&output.stderr)
938 );
939 }
940
941 let str = std::str::from_utf8(&output.stdout)
942 .map_err(|_| FormatterError::InvalidUtf8Output)?;
943
944 Ok(helix_core::diff::compare_ropes(&text, &Rope::from(str)))
945 };
946 return Some(formatting_future.boxed());
947 };
948
949 let text = self.text.clone();
950 // finds first language server that supports formatting and then formats
951 let language_server = self
952 .language_servers_with_feature(LanguageServerFeature::Format)
953 .next()?;
954 let offset_encoding = language_server.offset_encoding();
955 let request = language_server.text_document_formatting(
956 self.identifier(),
957 lsp::FormattingOptions {
958 tab_size: self.tab_width() as u32,
959 insert_spaces: matches!(self.indent_style, IndentStyle::Spaces(_)),
960 ..Default::default()
961 },
962 None,
963 )?;
964
965 let fut = async move {
966 let edits = request
967 .await
968 .unwrap_or_else(|e| {
969 log::warn!("LSP formatting failed: {}", e);
970 Default::default()
971 })
972 .unwrap_or_default();
973 Ok(helix_lsp::util::generate_transaction_from_edits(
974 &text,
975 edits,
976 offset_encoding,
977 ))
978 };
979 Some(fut.boxed())
980 }
981
982 pub fn save<P: Into<PathBuf>>(
983 &mut self,
984 path: Option<P>,
985 force: bool,
986 ) -> Result<
987 impl Future<Output = Result<DocumentSavedEvent, anyhow::Error>> + 'static + Send,
988 anyhow::Error,
989 > {
990 let path = path.map(|path| path.into());
991 self.save_impl(path, force)
992
993 // futures_util::future::Ready<_>,
994 }
995
996 /// The `Document`'s text is encoded according to its encoding and written to the file located
997 /// at its `path()`.
998 fn save_impl(
999 &mut self,
1000 path: Option<PathBuf>,
1001 force: bool,
1002 ) -> Result<
1003 impl Future<Output = Result<DocumentSavedEvent, anyhow::Error>> + 'static + Send,
1004 anyhow::Error,
1005 > {
1006 log::debug!(
1007 "submitting save of doc '{:?}'",
1008 self.path().map(|path| path.to_string_lossy())
1009 );
1010
1011 // we clone and move text + path into the future so that we asynchronously save the current
1012 // state without blocking any further edits.
1013 let text = self.text().clone();
1014
1015 let path = match path {
1016 Some(path) => helix_stdx::path::canonicalize(path),
1017 None => {
1018 if self.path.is_none() {
1019 bail!("Can't save with no path set!");
1020 }
1021 self.path.as_ref().unwrap().clone()
1022 }
1023 };
1024
1025 let identifier = self.path().map(|_| self.identifier());
1026 let language_servers: Vec<_> = self.language_servers.values().cloned().collect();
1027
1028 // mark changes up to now as saved
1029 let current_rev = self.get_current_revision();
1030 let doc_id = self.id();
1031 let atomic_save = self.config.load().atomic_save;
1032
1033 let encoding_with_bom_info = (self.encoding, self.has_bom);
1034 let last_saved_time = self.last_saved_time;
1035
1036 // We encode the file according to the `Document`'s encoding.
1037 let future = async move {
1038 use tokio::fs;
1039 if let Some(parent) = path.parent() {
1040 // TODO: display a prompt asking the user if the directories should be created
1041 if !parent.exists() {
1042 if force {
1043 std::fs::DirBuilder::new().recursive(true).create(parent)?;
1044 } else {
1045 bail!("can't save file, parent directory does not exist (use :w! to create it)");
1046 }
1047 }
1048 }
1049
1050 // Protect against overwriting changes made externally
1051 if !force {
1052 if let Ok(metadata) = fs::metadata(&path).await {
1053 if let Ok(mtime) = metadata.modified() {
1054 if last_saved_time < mtime {
1055 bail!("file modified by an external process, use :w! to overwrite");
1056 }
1057 }
1058 }
1059 }
1060 let write_path = tokio::fs::read_link(&path)
1061 .await
1062 .ok()
1063 .and_then(|p| {
1064 if p.is_relative() {
1065 path.parent().map(|parent| parent.join(p))
1066 } else {
1067 Some(p)
1068 }
1069 })
1070 .unwrap_or_else(|| path.clone());
1071
1072 if readonly(&write_path) {
1073 bail!(std::io::Error::new(
1074 std::io::ErrorKind::PermissionDenied,
1075 "Path is read only"
1076 ));
1077 }
1078
1079 // Assume it is a hardlink to prevent data loss if the metadata cant be read (e.g. on certain Windows configurations)
1080 let is_hardlink = helix_stdx::faccess::hardlink_count(&write_path).unwrap_or(2) > 1;
1081 let is_symlink = match tokio::fs::symlink_metadata(&write_path).await {
1082 Ok(meta) => meta.is_symlink(),
1083 Err(err) if err.kind() == std::io::ErrorKind::NotFound => false,
1084 Err(err) => return Err(err.into()),
1085 };
1086 let must_copy = is_hardlink || is_symlink;
1087 let backup = if path.exists() && atomic_save {
1088 let path_ = write_path.clone();
1089 // hacks: we use tempfile to handle the complex task of creating
1090 // non clobbered temporary path for us we don't want
1091 // the whole automatically delete path on drop thing
1092 // since the path doesn't exist yet, we just want
1093 // the path
1094 tokio::task::spawn_blocking(move || -> Option<PathBuf> {
1095 let mut builder = tempfile::Builder::new();
1096 builder.prefix(path_.file_name()?).suffix(".bck");
1097
1098 let backup_path = if must_copy {
1099 builder
1100 .make_in(path_.parent()?, |backup| std::fs::copy(&path_, backup))
1101 .ok()?
1102 .into_temp_path()
1103 } else {
1104 builder
1105 .make_in(path_.parent()?, |backup| std::fs::rename(&path_, backup))
1106 .ok()?
1107 .into_temp_path()
1108 };
1109
1110 backup_path.keep().ok()
1111 })
1112 .await
1113 .ok()
1114 .flatten()
1115 } else {
1116 None
1117 };
1118
1119 let write_result: anyhow::Result<_> = async {
1120 let mut dst = tokio::fs::File::create(&write_path).await?;
1121 to_writer(&mut dst, encoding_with_bom_info, &text).await?;
1122 // Ignore ENOTSUP/EOPNOTSUPP (Operation not supported) errors from sync_all()
1123 // This is known to occur on SMB filesystems on macOS where fsync is not supported
1124 match dst.sync_all().await {
1125 Ok(_) => (),
1126 Err(err) if err.kind() == io::ErrorKind::Unsupported => (),
1127 // Some extra OS errors are thrown on macOS for example if fsync is not
1128 // available for this filesystem. NOTE: on macOS, ENOTSUP and EOPNOTSUPP are
1129 // not the same code, so we need to suppress the unreachable_patterns lint on
1130 // Unix generally.
1131 #[allow(unreachable_patterns)]
1132 #[cfg(unix)]
1133 Err(err)
1134 if matches!(err.raw_os_error(), Some(libc::ENOTSUP | libc::EOPNOTSUPP)) => {
1135 }
1136 Err(err) => return Err(err.into()),
1137 }
1138 Ok(())
1139 }
1140 .await;
1141
1142 let save_time = match fs::metadata(&write_path).await {
1143 Ok(metadata) => metadata.modified().map_or(SystemTime::now(), |mtime| mtime),
1144 Err(_) => SystemTime::now(),
1145 };
1146
1147 if let Some(backup) = backup {
1148 if must_copy {
1149 let mut delete = true;
1150 if write_result.is_err() {
1151 // Restore backup
1152 let _ = tokio::fs::copy(&backup, &write_path).await.map_err(|e| {
1153 delete = false;
1154 log::error!("Failed to restore backup on write failure: {e}")
1155 });
1156 }
1157
1158 if delete {
1159 // Delete backup
1160 let _ = tokio::fs::remove_file(backup)
1161 .await
1162 .map_err(|e| log::error!("Failed to remove backup file on write: {e}"));
1163 }
1164 } else if write_result.is_err() {
1165 // restore backup
1166 let _ = tokio::fs::rename(&backup, &write_path)
1167 .await
1168 .map_err(|e| log::error!("Failed to restore backup on write failure: {e}"));
1169 } else {
1170 // copy metadata and delete backup
1171 let _ = tokio::task::spawn_blocking(move || {
1172 let _ = copy_metadata(&backup, &write_path)
1173 .map_err(|e| log::error!("Failed to copy metadata on write: {e}"));
1174 let _ = std::fs::remove_file(backup)
1175 .map_err(|e| log::error!("Failed to remove backup file on write: {e}"));
1176 })
1177 .await;
1178 }
1179 }
1180
1181 write_result?;
1182
1183 let event = DocumentSavedEvent {
1184 revision: current_rev,
1185 save_time,
1186 doc_id,
1187 path,
1188 text: text.clone(),
1189 };
1190
1191 for language_server in language_servers {
1192 if !language_server.is_initialized() {
1193 continue;
1194 }
1195 if let Some(id) = identifier.clone() {
1196 language_server.text_document_did_save(id, &text);
1197 }
1198 }
1199
1200 Ok(event)
1201 };
1202
1203 Ok(future)
1204 }
1205
1206 /// Detect the programming language based on the file type.
1207 pub fn detect_language(&mut self, loader: &syntax::Loader) {
1208 self.set_language(self.detect_language_config(loader), loader);
1209 }
1210
1211 /// Detect the programming language based on the file type.
1212 pub fn detect_language_config(
1213 &self,
1214 loader: &syntax::Loader,
1215 ) -> Option<Arc<syntax::config::LanguageConfiguration>> {
1216 let language = loader
1217 .language_for_filename(self.path.as_ref()?)
1218 .or_else(|| loader.language_for_shebang(self.text().slice(..)))?;
1219
1220 Some(loader.language(language).config().clone())
1221 }
1222
1223 /// Detect the indentation used in the file, or otherwise defaults to the language indentation
1224 /// configured in `languages.toml`, with a fallback to tabs if it isn't specified. Line ending
1225 /// is likewise auto-detected, and will remain unchanged if no line endings were detected.
1226 pub fn detect_indent_and_line_ending(&mut self) {
1227 self.indent_style = if let Some(indent_style) = self.editor_config.indent_style {
1228 indent_style
1229 } else {
1230 auto_detect_indent_style(&self.text).unwrap_or_else(|| {
1231 self.language_config()
1232 .and_then(|config| config.indent.as_ref())
1233 .map_or(DEFAULT_INDENT, |config| IndentStyle::from_str(&config.unit))
1234 })
1235 };
1236 if let Some(line_ending) = self
1237 .editor_config
1238 .line_ending
1239 .or_else(|| auto_detect_line_ending(&self.text))
1240 {
1241 self.line_ending = line_ending;
1242 }
1243 }
1244
1245 pub fn detect_editor_config(&mut self) {
1246 if self.config.load().editor_config {
1247 if let Some(path) = self.path.as_ref() {
1248 self.editor_config = EditorConfig::find(path);
1249 }
1250 }
1251 }
1252
1253 pub fn pickup_last_saved_time(&mut self) {
1254 self.last_saved_time = match self.path() {
1255 Some(path) => match path.metadata() {
1256 Ok(metadata) => match metadata.modified() {
1257 Ok(mtime) => mtime,
1258 Err(err) => {
1259 log::debug!("Could not fetch file system's mtime, falling back to current system time: {}", err);
1260 SystemTime::now()
1261 }
1262 },
1263 Err(err) => {
1264 log::debug!("Could not fetch file system's mtime, falling back to current system time: {}", err);
1265 SystemTime::now()
1266 }
1267 },
1268 None => SystemTime::now(),
1269 };
1270 }
1271
1272 // Detect if the file is readonly and change the readonly field if necessary (unix only)
1273 pub fn detect_readonly(&mut self) {
1274 // Allows setting the flag for files the user cannot modify, like root files
1275 self.readonly = match &self.path {
1276 None => false,
1277 Some(p) => readonly(p),
1278 };
1279 }
1280
1281 /// Reload the document from its path.
1282 pub fn reload(
1283 &mut self,
1284 view: &mut View,
1285 provider_registry: &DiffProviderRegistry,
1286 trust_full: bool,
1287 ) -> Result<(), Error> {
1288 let encoding = self.encoding;
1289 let path = match self.path() {
1290 None => return Ok(()),
1291 Some(path) => match path.exists() {
1292 true => path.to_owned(),
1293 false => bail!("can't find file to reload from {:?}", self.display_name()),
1294 },
1295 };
1296
1297 // Once we have a valid path we check if its readonly status has changed
1298 self.detect_readonly();
1299
1300 let mut file = std::fs::File::open(&path)?;
1301 let (rope, ..) = from_reader(&mut file, Some(encoding))?;
1302
1303 // Calculate the difference between the buffer and source text, and apply it.
1304 // This is not considered a modification of the contents of the file regardless
1305 // of the encoding.
1306 let transaction = helix_core::diff::compare_ropes(self.text(), &rope);
1307 self.apply(&transaction, view.id);
1308 self.append_changes_to_history(view);
1309 self.reset_modified();
1310 self.pickup_last_saved_time();
1311 self.detect_indent_and_line_ending();
1312
1313 match provider_registry.get_diff_base(&path, trust_full) {
1314 Some(diff_base) => self.set_diff_base(diff_base),
1315 None => self.diff_handle = None,
1316 }
1317
1318 self.version_control_head = provider_registry.get_current_head_name(&path, trust_full);
1319
1320 Ok(())
1321 }
1322
1323 /// Sets the [`Document`]'s encoding with the encoding correspondent to `label`.
1324 pub fn set_encoding(&mut self, label: &str) -> Result<(), Error> {
1325 let encoding =
1326 Encoding::for_label(label.as_bytes()).ok_or_else(|| anyhow!("unknown encoding"))?;
1327
1328 self.encoding = encoding;
1329
1330 Ok(())
1331 }
1332
1333 /// Returns the [`Document`]'s current encoding.
1334 pub fn encoding(&self) -> &'static Encoding {
1335 self.encoding
1336 }
1337
1338 /// sets the document path without sending events to various
1339 /// observers (like LSP), in most cases `Editor::set_doc_path`
1340 /// should be used instead
1341 pub fn set_path(&mut self, path: Option<&Path>) {
1342 let path = path.map(helix_stdx::path::canonicalize);
1343
1344 // `take` to remove any prior relative path that may have existed.
1345 // This will get set in `relative_path()`.
1346 self.relative_path.take();
1347 // Same story: invalidate so the next workspace_root() recomputes against the new path.
1348 self.workspace_root.take();
1349
1350 // if parent doesn't exist we still want to open the document
1351 // and error out when document is saved
1352 self.path = path;
1353
1354 self.detect_readonly();
1355 self.pickup_last_saved_time();
1356 }
1357
1358 /// Set the programming language for the file and load associated data (e.g. highlighting)
1359 /// if it exists.
1360 pub fn set_language(
1361 &mut self,
1362 language_config: Option<Arc<syntax::config::LanguageConfiguration>>,
1363 loader: &syntax::Loader,
1364 ) {
1365 self.language = language_config;
1366 self.syntax = self.language.as_ref().and_then(|config| {
1367 Syntax::new(self.text.slice(..), config.language(), loader)
1368 .map_err(|err| {
1369 // `NoRootConfig` means that there was an issue loading the language/syntax
1370 // config for the root language of the document. An error must have already
1371 // been logged by `LanguageData::syntax_config`.
1372 if err != syntax::HighlighterError::NoRootConfig {
1373 log::warn!("Error building syntax for '{}': {err}", self.display_name());
1374 }
1375 })
1376 .ok()
1377 });
1378 }
1379
1380 /// Set the programming language for the file if you know the language but don't have the
1381 /// [`syntax::config::LanguageConfiguration`] for it.
1382 pub fn set_language_by_language_id(
1383 &mut self,
1384 language_id: &str,
1385 loader: &syntax::Loader,
1386 ) -> anyhow::Result<()> {
1387 let language = loader
1388 .language_for_name(language_id)
1389 .ok_or_else(|| anyhow!("invalid language id: {}", language_id))?;
1390 let config = loader.language(language).config().clone();
1391 self.set_language(Some(config), loader);
1392 Ok(())
1393 }
1394
1395 /// Select text within the [`Document`].
1396 pub fn set_selection(&mut self, view_id: ViewId, selection: Selection) {
1397 // TODO: use a transaction?
1398 self.selections
1399 .insert(view_id, selection.ensure_invariants(self.text().slice(..)));
1400 helix_event::dispatch(SelectionDidChange {
1401 doc: self,
1402 view: view_id,
1403 })
1404 }
1405
1406 /// Find the origin selection of the text in a document, i.e. where
1407 /// a single cursor would go if it were on the first grapheme. If
1408 /// the text is empty, returns (0, 0).
1409 pub fn origin(&self) -> Range {
1410 if self.text().len_chars() == 0 {
1411 return Range::new(0, 0);
1412 }
1413
1414 Range::new(0, 1).grapheme_aligned(self.text().slice(..))
1415 }
1416
1417 /// Reset the view's selection on this document to the
1418 /// [origin](Document::origin) cursor.
1419 pub fn reset_selection(&mut self, view_id: ViewId) {
1420 let origin = self.origin();
1421 self.set_selection(view_id, Selection::single(origin.anchor, origin.head));
1422 }
1423
1424 /// Initializes a new selection and view_data for the given view
1425 /// if it does not already have them.
1426 pub fn ensure_view_init(&mut self, view_id: ViewId) {
1427 if !self.selections.contains_key(&view_id) {
1428 self.reset_selection(view_id);
1429 }
1430
1431 self.view_data_mut(view_id);
1432 }
1433
1434 /// Mark document as recent used for MRU sorting
1435 pub fn mark_as_focused(&mut self) {
1436 self.focused_at = std::time::Instant::now();
1437 }
1438
1439 /// Remove a view's selection and inlay hints from this document.
1440 pub fn remove_view(&mut self, view_id: ViewId) {
1441 self.selections.remove(&view_id);
1442 self.view_data.remove(&view_id);
1443 self.inlay_hints.remove(&view_id);
1444 self.jump_labels.remove(&view_id);
1445 self.document_highlights.remove(&view_id);
1446 self.document_highlight_controllers.remove(&view_id);
1447 self.code_action_hints.remove(&view_id);
1448 self.code_action_controllers.remove(&view_id);
1449 }
1450
1451 /// Apply a [`Transaction`] to the [`Document`] to change its text.
1452 fn apply_impl(
1453 &mut self,
1454 transaction: &Transaction,
1455 view_id: ViewId,
1456 emit_lsp_notification: bool,
1457 ) -> bool {
1458 use helix_core::Assoc;
1459
1460 let old_doc = self.text().clone();
1461 let changes = transaction.changes();
1462 if !changes.apply(&mut self.text) {
1463 return false;
1464 }
1465
1466 if changes.is_empty() {
1467 if let Some(selection) = transaction.selection() {
1468 self.selections.insert(
1469 view_id,
1470 selection.clone().ensure_invariants(self.text.slice(..)),
1471 );
1472 helix_event::dispatch(SelectionDidChange {
1473 doc: self,
1474 view: view_id,
1475 });
1476 }
1477 return true;
1478 }
1479
1480 self.modified_since_accessed = true;
1481 self.version += 1;
1482
1483 for selection in self.selections.values_mut() {
1484 *selection = selection
1485 .clone()
1486 // Map through changes
1487 .map(transaction.changes())
1488 // Ensure all selections across all views still adhere to invariants.
1489 .ensure_invariants(self.text.slice(..));
1490 }
1491
1492 for view_data in self.view_data.values_mut() {
1493 view_data.view_position.anchor = transaction
1494 .changes()
1495 .map_pos(view_data.view_position.anchor, Assoc::Before);
1496 }
1497
1498 // generate revert to savepoint
1499 if !self.savepoints.is_empty() {
1500 let revert = transaction.invert(&old_doc);
1501 self.savepoints
1502 .retain_mut(|save_point| match save_point.upgrade() {
1503 Some(savepoint) => {
1504 let mut revert_to_savepoint = savepoint.revert.lock();
1505 *revert_to_savepoint =
1506 revert.clone().compose(mem::take(&mut revert_to_savepoint));
1507 true
1508 }
1509 None => false,
1510 })
1511 }
1512
1513 // update tree-sitter syntax tree
1514 if let Some(syntax) = &mut self.syntax {
1515 let loader = self.syn_loader.load();
1516 if let Err(err) = syntax.update(
1517 old_doc.slice(..),
1518 self.text.slice(..),
1519 transaction.changes(),
1520 &loader,
1521 ) {
1522 log::error!("TS parser failed, disabling TS for the current buffer: {err}");
1523 self.syntax = None;
1524 }
1525 }
1526
1527 // TODO: all of that should likely just be hooks
1528 // start computing the diff in parallel
1529 if let Some(diff_handle) = &self.diff_handle {
1530 diff_handle.update_document(self.text.clone(), false);
1531 }
1532
1533 // map diagnostics over changes too
1534 changes.update_positions(self.diagnostics.iter_mut().map(|diagnostic| {
1535 let assoc = if diagnostic.starts_at_word {
1536 Assoc::BeforeWord
1537 } else {
1538 Assoc::After
1539 };
1540 (&mut diagnostic.range.start, assoc)
1541 }));
1542 changes.update_positions(self.diagnostics.iter_mut().filter_map(|diagnostic| {
1543 if diagnostic.zero_width {
1544 // for zero width diagnostics treat the diagnostic as a point
1545 // rather than a range
1546 return None;
1547 }
1548 let assoc = if diagnostic.ends_at_word {
1549 Assoc::AfterWord
1550 } else {
1551 Assoc::Before
1552 };
1553 Some((&mut diagnostic.range.end, assoc))
1554 }));
1555 self.diagnostics.retain_mut(|diagnostic| {
1556 if diagnostic.zero_width {
1557 diagnostic.range.end = diagnostic.range.start
1558 } else if diagnostic.range.start >= diagnostic.range.end {
1559 return false;
1560 }
1561 diagnostic.line = self.text.char_to_line(diagnostic.range.start);
1562 true
1563 });
1564
1565 self.diagnostics.sort_by_key(|diagnostic| {
1566 (
1567 diagnostic.range,
1568 diagnostic.severity,
1569 diagnostic.provider.clone(),
1570 )
1571 });
1572
1573 // Update the inlay hint annotations' positions, helping ensure they are displayed in the proper place
1574 let apply_inlay_hint_changes = |annotations: &mut Vec<InlineAnnotation>| {
1575 changes.update_positions(
1576 annotations
1577 .iter_mut()
1578 .map(|annotation| (&mut annotation.char_idx, Assoc::After)),
1579 );
1580 };
1581
1582 self.inlay_hints_oudated = true;
1583 for text_annotation in self.inlay_hints.values_mut() {
1584 let DocumentInlayHints {
1585 id: _,
1586 type_inlay_hints,
1587 parameter_inlay_hints,
1588 other_inlay_hints,
1589 padding_before_inlay_hints,
1590 padding_after_inlay_hints,
1591 } = text_annotation;
1592
1593 apply_inlay_hint_changes(padding_before_inlay_hints);
1594 apply_inlay_hint_changes(type_inlay_hints);
1595 apply_inlay_hint_changes(parameter_inlay_hints);
1596 apply_inlay_hint_changes(other_inlay_hints);
1597 apply_inlay_hint_changes(padding_after_inlay_hints);
1598 }
1599
1600 for highlights in self.document_highlights.values_mut() {
1601 let text_len = self.text.len_chars();
1602 let mut updated = Vec::with_capacity(highlights.ranges.len());
1603 for mut range in highlights.ranges.drain(..) {
1604 changes.update_positions(
1605 [
1606 (&mut range.start, Assoc::After),
1607 (&mut range.end, Assoc::After),
1608 ]
1609 .into_iter(),
1610 );
1611 if range.start >= text_len {
1612 continue;
1613 }
1614 let end = range.end.min(text_len);
1615 if range.start < end {
1616 updated.push(range.start..end);
1617 }
1618 }
1619 highlights.ranges = updated;
1620 }
1621
1622 helix_event::dispatch(DocumentDidChange {
1623 doc: self,
1624 view: view_id,
1625 old_text: &old_doc,
1626 changes,
1627 ghost_transaction: !emit_lsp_notification,
1628 });
1629
1630 // if specified, the current selection should instead be replaced by transaction.selection
1631 if let Some(selection) = transaction.selection() {
1632 self.selections.insert(
1633 view_id,
1634 selection.clone().ensure_invariants(self.text.slice(..)),
1635 );
1636 helix_event::dispatch(SelectionDidChange {
1637 doc: self,
1638 view: view_id,
1639 });
1640 }
1641
1642 true
1643 }
1644
1645 fn apply_inner(
1646 &mut self,
1647 transaction: &Transaction,
1648 view_id: ViewId,
1649 emit_lsp_notification: bool,
1650 ) -> bool {
1651 // store the state just before any changes are made. This allows us to undo to the
1652 // state just before a transaction was applied.
1653 if self.changes.is_empty() && !transaction.changes().is_empty() {
1654 self.old_state = Some(State {
1655 doc: self.text.clone(),
1656 selection: self.selection(view_id).clone(),
1657 });
1658 }
1659
1660 let success = self.apply_impl(transaction, view_id, emit_lsp_notification);
1661
1662 if !transaction.changes().is_empty() {
1663 // Compose this transaction with the previous one
1664 take_with(&mut self.changes, |changes| {
1665 changes.compose(transaction.changes().clone())
1666 });
1667 }
1668 success
1669 }
1670 /// Apply a [`Transaction`] to the [`Document`] to change its text.
1671 pub fn apply(&mut self, transaction: &Transaction, view_id: ViewId) -> bool {
1672 self.apply_inner(transaction, view_id, true)
1673 }
1674
1675 /// Apply a [`Transaction`] to the [`Document`] to change its text
1676 /// without notifying the language servers. This is useful for temporary transactions
1677 /// that must not influence the server.
1678 pub fn apply_temporary(&mut self, transaction: &Transaction, view_id: ViewId) -> bool {
1679 self.apply_inner(transaction, view_id, false)
1680 }
1681
1682 fn undo_redo_impl(&mut self, view: &mut View, undo: bool) -> bool {
1683 if undo {
1684 self.append_changes_to_history(view);
1685 } else if !self.changes.is_empty() {
1686 return false;
1687 }
1688 let mut history = self.history.take();
1689 let txn = if undo { history.undo() } else { history.redo() };
1690 let success = if let Some(txn) = txn {
1691 self.apply_impl(txn, view.id, true)
1692 } else {
1693 false
1694 };
1695 self.history.set(history);
1696
1697 if success {
1698 // reset changeset to fix len
1699 self.changes = ChangeSet::new(self.text().slice(..));
1700 // Sync with changes with the jumplist selections.
1701 view.sync_changes(self);
1702 }
1703 success
1704 }
1705
1706 /// Undo the last modification to the [`Document`]. Returns whether the undo was successful.
1707 pub fn undo(&mut self, view: &mut View) -> bool {
1708 self.undo_redo_impl(view, true)
1709 }
1710
1711 /// Redo the last modification to the [`Document`]. Returns whether the redo was successful.
1712 pub fn redo(&mut self, view: &mut View) -> bool {
1713 self.undo_redo_impl(view, false)
1714 }
1715
1716 /// Creates a reference counted snapshot (called savpepoint) of the document.
1717 ///
1718 /// The snapshot will remain valid (and updated) idenfinitly as long as ereferences to it exist.
1719 /// Restoring the snapshot will restore the selection and the contents of the document to
1720 /// the state it had when this function was called.
1721 pub fn savepoint(&mut self, view: &View) -> Arc<SavePoint> {
1722 let revert = Transaction::new(self.text()).with_selection(self.selection(view.id).clone());
1723 // check if there is already an existing (identical) savepoint around
1724 if let Some(savepoint) = self
1725 .savepoints
1726 .iter()
1727 .rev()
1728 .find_map(|savepoint| savepoint.upgrade())
1729 {
1730 let transaction = savepoint.revert.lock();
1731 if savepoint.view == view.id
1732 && transaction.changes().is_empty()
1733 && transaction.selection() == revert.selection()
1734 {
1735 drop(transaction);
1736 return savepoint;
1737 }
1738 }
1739 let savepoint = Arc::new(SavePoint {
1740 view: view.id,
1741 revert: Mutex::new(revert),
1742 });
1743 self.savepoints.push(Arc::downgrade(&savepoint));
1744 savepoint
1745 }
1746
1747 pub fn restore(&mut self, view: &mut View, savepoint: &SavePoint, emit_lsp_notification: bool) {
1748 assert_eq!(
1749 savepoint.view, view.id,
1750 "Savepoint must not be used with a different view!"
1751 );
1752 // search and remove savepoint using a ptr comparison
1753 // this avoids a deadlock as we need to lock the mutex
1754 let savepoint_idx = self
1755 .savepoints
1756 .iter()
1757 .position(|savepoint_ref| std::ptr::eq(savepoint_ref.as_ptr(), savepoint))
1758 .expect("Savepoint must belong to this document");
1759
1760 let savepoint_ref = self.savepoints.remove(savepoint_idx);
1761 let mut revert = savepoint.revert.lock();
1762 self.apply_inner(&revert, view.id, emit_lsp_notification);
1763 *revert = Transaction::new(self.text()).with_selection(self.selection(view.id).clone());
1764 self.savepoints.push(savepoint_ref)
1765 }
1766
1767 fn earlier_later_impl(&mut self, view: &mut View, uk: UndoKind, earlier: bool) -> bool {
1768 if earlier {
1769 self.append_changes_to_history(view);
1770 } else if !self.changes.is_empty() {
1771 return false;
1772 }
1773 let txns = if earlier {
1774 self.history.get_mut().earlier(uk)
1775 } else {
1776 self.history.get_mut().later(uk)
1777 };
1778 let mut success = false;
1779 for txn in txns {
1780 if self.apply_impl(&txn, view.id, true) {
1781 success = true;
1782 }
1783 }
1784 if success {
1785 // reset changeset to fix len
1786 self.changes = ChangeSet::new(self.text().slice(..));
1787 // Sync with changes with the jumplist selections.
1788 view.sync_changes(self);
1789 }
1790 success
1791 }
1792
1793 /// Undo modifications to the [`Document`] according to `uk`.
1794 pub fn earlier(&mut self, view: &mut View, uk: UndoKind) -> bool {
1795 self.earlier_later_impl(view, uk, true)
1796 }
1797
1798 /// Redo modifications to the [`Document`] according to `uk`.
1799 pub fn later(&mut self, view: &mut View, uk: UndoKind) -> bool {
1800 self.earlier_later_impl(view, uk, false)
1801 }
1802
1803 /// Commit pending changes to history
1804 pub fn append_changes_to_history(&mut self, view: &mut View) {
1805 if self.changes.is_empty() {
1806 return;
1807 }
1808
1809 let new_changeset = ChangeSet::new(self.text().slice(..));
1810 let changes = std::mem::replace(&mut self.changes, new_changeset);
1811 // Instead of doing this messy merge we could always commit, and based on transaction
1812 // annotations either add a new layer or compose into the previous one.
1813 let transaction =
1814 Transaction::from(changes).with_selection(self.selection(view.id).clone());
1815
1816 // HAXX: we need to reconstruct the state as it was before the changes..
1817 let old_state = self.old_state.take().expect("no old_state available");
1818
1819 let mut history = self.history.take();
1820 history.commit_revision(&transaction, &old_state);
1821 self.history.set(history);
1822
1823 // Update jumplist entries in the view.
1824 view.apply(&transaction, self);
1825 }
1826
1827 pub fn id(&self) -> DocumentId {
1828 self.id
1829 }
1830
1831 /// If there are unsaved modifications.
1832 pub fn is_modified(&self) -> bool {
1833 let history = self.history.take();
1834 let current_revision = history.current_revision();
1835 self.history.set(history);
1836 log::debug!(
1837 "id {} modified - last saved: {}, current: {}",
1838 self.id,
1839 self.last_saved_revision,
1840 current_revision
1841 );
1842 current_revision != self.last_saved_revision || !self.changes.is_empty()
1843 }
1844
1845 /// Save modifications to history, and so [`Self::is_modified`] will return false.
1846 pub fn reset_modified(&mut self) {
1847 let history = self.history.take();
1848 let current_revision = history.current_revision();
1849 self.history.set(history);
1850 self.last_saved_revision = current_revision;
1851 }
1852
1853 /// Set the document's latest saved revision to the given one.
1854 pub fn set_last_saved_revision(&mut self, rev: usize, save_time: SystemTime) {
1855 log::debug!(
1856 "doc {} revision updated {} -> {}",
1857 self.id,
1858 self.last_saved_revision,
1859 rev
1860 );
1861 self.last_saved_revision = rev;
1862 self.last_saved_time = save_time;
1863 }
1864
1865 /// Get the document's latest saved revision.
1866 pub fn get_last_saved_revision(&mut self) -> usize {
1867 self.last_saved_revision
1868 }
1869
1870 /// Get the current revision number
1871 pub fn get_current_revision(&mut self) -> usize {
1872 let history = self.history.take();
1873 let current_revision = history.current_revision();
1874 self.history.set(history);
1875 current_revision
1876 }
1877
1878 /// Corresponding language scope name. Usually `source.<lang>`.
1879 pub fn language_scope(&self) -> Option<&str> {
1880 self.language
1881 .as_ref()
1882 .map(|language| language.scope.as_str())
1883 }
1884
1885 /// Language name for the document. Corresponds to the `name` key in
1886 /// `languages.toml` configuration.
1887 pub fn language_name(&self) -> Option<&str> {
1888 self.language
1889 .as_ref()
1890 .map(|language| language.language_id.as_str())
1891 }
1892
1893 /// Language ID for the document. Either the `language-id`,
1894 /// or the document language name if no `language-id` has been specified.
1895 pub fn language_id(&self) -> Option<&str> {
1896 self.language_config()?
1897 .language_server_language_id
1898 .as_deref()
1899 .or_else(|| self.language_name())
1900 }
1901
1902 /// Corresponding [`LanguageConfiguration`].
1903 pub fn language_config(&self) -> Option<&LanguageConfiguration> {
1904 self.language.as_deref()
1905 }
1906
1907 /// The language configuration of the injection layer at `byte_pos`,
1908 /// so language-specific behavior follows embedded languages. Falls back to the
1909 /// document's root language config when there is no syntax tree.
1910 pub fn language_config_at<'a>(
1911 &'a self,
1912 loader: &'a syntax::Loader,
1913 byte_pos: usize,
1914 ) -> Option<&'a LanguageConfiguration> {
1915 match self.syntax() {
1916 Some(syntax) => {
1917 let layer = syntax.layer_for_byte_range(byte_pos as u32, byte_pos as u32);
1918 Some(&**loader.language(syntax.layer(layer).language).config())
1919 }
1920 None => self.language_config(),
1921 }
1922 }
1923
1924 /// Current document version, incremented at each change.
1925 pub fn version(&self) -> i32 {
1926 self.version
1927 }
1928
1929 pub fn word_completion_enabled(&self) -> bool {
1930 self.language_config()
1931 .and_then(|lang_config| lang_config.word_completion.and_then(|c| c.enable))
1932 .unwrap_or_else(|| self.config.load().word_completion.enable)
1933 }
1934
1935 pub fn path_completion_enabled(&self) -> bool {
1936 self.language_config()
1937 .and_then(|lang_config| lang_config.path_completion)
1938 .unwrap_or_else(|| self.config.load().path_completion)
1939 }
1940
1941 /// maintains the order as configured in the language_servers TOML array
1942 pub fn language_servers(&self) -> impl Iterator<Item = &helix_lsp::Client> {
1943 self.language_config().into_iter().flat_map(move |config| {
1944 config.language_servers.iter().filter_map(move |features| {
1945 let ls = &**self.language_servers.get(&features.name)?;
1946 if ls.is_initialized() {
1947 Some(ls)
1948 } else {
1949 None
1950 }
1951 })
1952 })
1953 }
1954
1955 pub fn remove_language_server_by_name(&mut self, name: &str) -> Option<Arc<Client>> {
1956 self.language_servers.remove(name)
1957 }
1958
1959 pub fn language_servers_with_feature(
1960 &self,
1961 feature: LanguageServerFeature,
1962 ) -> impl Iterator<Item = &helix_lsp::Client> {
1963 self.language_config().into_iter().flat_map(move |config| {
1964 config.language_servers.iter().filter_map(move |features| {
1965 let ls = &**self.language_servers.get(&features.name)?;
1966 if ls.is_initialized()
1967 && ls.supports_feature(feature)
1968 && features.has_feature(feature)
1969 {
1970 Some(ls)
1971 } else {
1972 None
1973 }
1974 })
1975 })
1976 }
1977
1978 pub fn supports_language_server(&self, id: LanguageServerId) -> bool {
1979 self.language_servers().any(|l| l.id() == id)
1980 }
1981
1982 pub fn servers_to_load(&self) -> bool {
1983 self.language_config()
1984 .map(|lang| !lang.language_servers.is_empty() || lang.debugger.is_some())
1985 .unwrap_or(false)
1986 }
1987
1988 pub fn diff_handle(&self) -> Option<&DiffHandle> {
1989 self.diff_handle.as_ref()
1990 }
1991
1992 /// Intialize/updates the differ for this document with a new base.
1993 pub fn set_diff_base(&mut self, diff_base: Vec<u8>) {
1994 if let Ok((diff_base, ..)) = from_reader(&mut diff_base.as_slice(), Some(self.encoding)) {
1995 if let Some(differ) = &self.diff_handle {
1996 differ.update_diff_base(diff_base);
1997 return;
1998 }
1999 self.diff_handle = Some(DiffHandle::new(diff_base, self.text.clone()))
2000 } else {
2001 self.diff_handle = None;
2002 }
2003 }
2004
2005 pub fn version_control_head(&self) -> Option<Arc<Box<str>>> {
2006 self.version_control_head.as_ref().map(|a| a.load_full())
2007 }
2008
2009 pub fn set_version_control_head(
2010 &mut self,
2011 version_control_head: Option<Arc<ArcSwap<Box<str>>>>,
2012 ) {
2013 self.version_control_head = version_control_head;
2014 }
2015
2016 #[inline]
2017 /// Tree-sitter AST tree
2018 pub fn syntax(&self) -> Option<&Syntax> {
2019 self.syntax.as_ref()
2020 }
2021
2022 /// The width that the tab character is rendered at
2023 pub fn tab_width(&self) -> usize {
2024 self.editor_config
2025 .tab_width
2026 .map(|n| n.get() as usize)
2027 .unwrap_or_else(|| {
2028 self.language_config()
2029 .and_then(|config| config.indent.as_ref())
2030 .map_or(DEFAULT_TAB_WIDTH, |config| config.tab_width)
2031 })
2032 }
2033
2034 // The width (in spaces) of a level of indentation.
2035 pub fn indent_width(&self) -> usize {
2036 self.indent_style.indent_width(self.tab_width())
2037 }
2038
2039 /// Whether the document should have a trailing line ending appended on save.
2040 pub fn insert_final_newline(&self) -> bool {
2041 self.editor_config
2042 .insert_final_newline
2043 .unwrap_or_else(|| self.config.load().insert_final_newline)
2044 }
2045
2046 /// Whether the document should trim whitespace preceding line endings on save.
2047 pub fn trim_trailing_whitespace(&self) -> bool {
2048 self.editor_config
2049 .trim_trailing_whitespace
2050 .unwrap_or_else(|| self.config.load().trim_trailing_whitespace)
2051 }
2052
2053 pub fn changes(&self) -> &ChangeSet {
2054 &self.changes
2055 }
2056
2057 #[inline]
2058 /// File path on disk.
2059 pub fn path(&self) -> Option<&Path> {
2060 self.path.as_deref()
2061 }
2062
2063 /// File path as a URL.
2064 pub fn url(&self) -> Option<Url> {
2065 Url::from_file_path(self.path()?).ok()
2066 }
2067
2068 pub fn uri(&self) -> Option<helix_core::Uri> {
2069 Some(self.path()?.into())
2070 }
2071
2072 #[inline]
2073 pub fn text(&self) -> &Rope {
2074 &self.text
2075 }
2076
2077 #[inline]
2078 pub fn selection(&self, view_id: ViewId) -> &Selection {
2079 &self.selections[&view_id]
2080 }
2081
2082 #[inline]
2083 pub fn selections(&self) -> &HashMap<ViewId, Selection> {
2084 &self.selections
2085 }
2086
2087 fn view_data(&self, view_id: ViewId) -> &ViewData {
2088 self.view_data
2089 .get(&view_id)
2090 .expect("This should only be called after ensure_view_init")
2091 }
2092
2093 fn view_data_mut(&mut self, view_id: ViewId) -> &mut ViewData {
2094 self.view_data.entry(view_id).or_default()
2095 }
2096
2097 pub(crate) fn get_view_offset(&self, view_id: ViewId) -> Option<ViewPosition> {
2098 Some(self.view_data.get(&view_id)?.view_position)
2099 }
2100
2101 pub fn view_offset(&self, view_id: ViewId) -> ViewPosition {
2102 self.view_data(view_id).view_position
2103 }
2104
2105 pub fn set_view_offset(&mut self, view_id: ViewId, new_offset: ViewPosition) {
2106 self.view_data_mut(view_id).view_position = new_offset;
2107 }
2108
2109 pub fn relative_path(&self) -> Option<&Path> {
2110 self.relative_path
2111 .get_or_init(|| {
2112 self.path
2113 .as_ref()
2114 .map(|path| helix_stdx::path::get_relative_path(path).to_path_buf())
2115 })
2116 .as_deref()
2117 }
2118
2119 /// The workspace root for this document — the nearest ancestor that contains a `.git`, `.svn`,
2120 /// `.jj`, or `.helix`. Falls back to the current working directory's workspace when the
2121 /// document has no path (scratch buffers). Lazily memoised on first call.
2122 pub fn workspace_root(&self) -> &Path {
2123 self.workspace_root
2124 .get_or_init(|| match self.path.as_deref() {
2125 Some(p) => p
2126 .parent()
2127 .map(|dir| helix_loader::find_workspace_in(dir).0)
2128 .unwrap_or_else(|| helix_loader::find_workspace().0),
2129 None => helix_loader::find_workspace().0,
2130 })
2131 }
2132
2133 pub fn display_name(&self) -> Cow<'_, str> {
2134 self.relative_path()
2135 .map_or_else(|| SCRATCH_BUFFER_NAME.into(), |path| path.to_string_lossy())
2136 }
2137
2138 // transact(Fn) ?
2139
2140 // -- LSP methods
2141
2142 #[inline]
2143 pub fn identifier(&self) -> lsp::TextDocumentIdentifier {
2144 lsp::TextDocumentIdentifier::new(self.url().unwrap())
2145 }
2146
2147 pub fn versioned_identifier(&self) -> lsp::VersionedTextDocumentIdentifier {
2148 lsp::VersionedTextDocumentIdentifier::new(self.url().unwrap(), self.version)
2149 }
2150
2151 pub fn position(
2152 &self,
2153 view_id: ViewId,
2154 offset_encoding: helix_lsp::OffsetEncoding,
2155 ) -> lsp::Position {
2156 let text = self.text();
2157
2158 helix_lsp::util::pos_to_lsp_pos(
2159 text,
2160 self.selection(view_id).primary().cursor(text.slice(..)),
2161 offset_encoding,
2162 )
2163 }
2164
2165 pub fn lsp_diagnostic_to_diagnostic(
2166 text: &Rope,
2167 language_config: Option<&LanguageConfiguration>,
2168 diagnostic: &helix_lsp::lsp::Diagnostic,
2169 provider: DiagnosticProvider,
2170 offset_encoding: helix_lsp::OffsetEncoding,
2171 ) -> Option<Diagnostic> {
2172 use helix_core::diagnostic::{Range, Severity::*};
2173
2174 // TODO: convert inside server
2175 let start =
2176 if let Some(start) = lsp_pos_to_pos(text, diagnostic.range.start, offset_encoding) {
2177 start
2178 } else {
2179 log::warn!("lsp position out of bounds - {:?}", diagnostic);
2180 return None;
2181 };
2182
2183 let end = if let Some(end) = lsp_pos_to_pos(text, diagnostic.range.end, offset_encoding) {
2184 end
2185 } else {
2186 log::warn!("lsp position out of bounds - {:?}", diagnostic);
2187 return None;
2188 };
2189
2190 let severity = diagnostic.severity.and_then(|severity| match severity {
2191 lsp::DiagnosticSeverity::ERROR => Some(Error),
2192 lsp::DiagnosticSeverity::WARNING => Some(Warning),
2193 lsp::DiagnosticSeverity::INFORMATION => Some(Info),
2194 lsp::DiagnosticSeverity::HINT => Some(Hint),
2195 severity => {
2196 log::error!("unrecognized diagnostic severity: {:?}", severity);
2197 None
2198 }
2199 });
2200
2201 if let Some(lang_conf) = language_config {
2202 if let Some(severity) = severity {
2203 if severity < lang_conf.diagnostic_severity {
2204 return None;
2205 }
2206 }
2207 };
2208 use helix_core::diagnostic::{DiagnosticTag, NumberOrString};
2209
2210 let code = match diagnostic.code.clone() {
2211 Some(x) => match x {
2212 lsp::NumberOrString::Number(x) => Some(NumberOrString::Number(x)),
2213 lsp::NumberOrString::String(x) => Some(NumberOrString::String(x)),
2214 },
2215 None => None,
2216 };
2217
2218 let tags = if let Some(tags) = &diagnostic.tags {
2219 let new_tags = tags
2220 .iter()
2221 .filter_map(|tag| match *tag {
2222 lsp::DiagnosticTag::DEPRECATED => Some(DiagnosticTag::Deprecated),
2223 lsp::DiagnosticTag::UNNECESSARY => Some(DiagnosticTag::Unnecessary),
2224 _ => None,
2225 })
2226 .collect();
2227
2228 new_tags
2229 } else {
2230 Vec::new()
2231 };
2232
2233 let ends_at_word =
2234 start != end && end != 0 && text.get_char(end - 1).is_some_and(char_is_word);
2235 let starts_at_word = start != end && text.get_char(start).is_some_and(char_is_word);
2236
2237 Some(Diagnostic {
2238 range: Range { start, end },
2239 ends_at_word,
2240 starts_at_word,
2241 zero_width: start == end,
2242 line: diagnostic.range.start.line as usize,
2243 message: diagnostic.message.clone(),
2244 severity,
2245 code,
2246 tags,
2247 source: diagnostic.source.clone(),
2248 data: diagnostic.data.clone(),
2249 provider,
2250 })
2251 }
2252
2253 #[inline]
2254 pub fn diagnostics(&self) -> &[Diagnostic] {
2255 &self.diagnostics
2256 }
2257
2258 pub fn replace_diagnostics(
2259 &mut self,
2260 diagnostics: impl IntoIterator<Item = Diagnostic>,
2261 unchanged_sources: &[String],
2262 provider: Option<&DiagnosticProvider>,
2263 ) {
2264 if unchanged_sources.is_empty() {
2265 if let Some(provider) = provider {
2266 self.diagnostics
2267 .retain(|diagnostic| &diagnostic.provider != provider);
2268 } else {
2269 self.diagnostics.clear();
2270 }
2271 } else {
2272 self.diagnostics.retain(|d| {
2273 if provider.is_some_and(|provider| provider != &d.provider) {
2274 return true;
2275 }
2276
2277 if let Some(source) = &d.source {
2278 unchanged_sources.contains(source)
2279 } else {
2280 false
2281 }
2282 });
2283 }
2284 self.diagnostics.extend(diagnostics);
2285 self.diagnostics.sort_by_key(|diagnostic| {
2286 (
2287 diagnostic.range,
2288 diagnostic.severity,
2289 diagnostic.provider.clone(),
2290 )
2291 });
2292 }
2293
2294 /// clears diagnostics for a given language server id if set, otherwise all diagnostics are cleared
2295 pub fn clear_diagnostics_for_language_server(&mut self, id: LanguageServerId) {
2296 self.diagnostics
2297 .retain(|d| d.provider.language_server_id() != Some(id));
2298 }
2299
2300 /// Get the document's auto pairs. If the document has a recognized
2301 /// language config with auto pairs configured, returns that;
2302 /// otherwise, falls back to the global auto pairs config. If the global
2303 /// config is false, then ignore language settings.
2304 pub fn auto_pairs<'a>(
2305 &'a self,
2306 editor: &'a Editor,
2307 loader: &'a syntax::Loader,
2308 view: &View,
2309 ) -> Option<&'a AutoPairs> {
2310 let global_config = (editor.auto_pairs).as_ref();
2311
2312 // NOTE: If the user specifies the global auto pairs config as false, then
2313 // we want to disable it globally regardless of language settings
2314 #[allow(clippy::question_mark)]
2315 {
2316 if global_config.is_none() {
2317 return None;
2318 }
2319 }
2320
2321 self.syntax
2322 .as_ref()
2323 .and_then(|syntax| {
2324 let selection = self.selection(view.id).primary();
2325 let (start, end) = selection.into_byte_range(self.text().slice(..));
2326 let layer = syntax.layer_for_byte_range(start as u32, end as u32);
2327
2328 let lang_config = loader.language(syntax.layer(layer).language).config();
2329 lang_config.auto_pairs.as_ref()
2330 })
2331 .or(global_config)
2332 }
2333
2334 pub fn snippet_ctx(&self) -> SnippetRenderCtx {
2335 SnippetRenderCtx {
2336 // TODO snippet variable resolution
2337 resolve_var: Box::new(|_| None),
2338 tab_width: self.tab_width(),
2339 indent_style: self.indent_style,
2340 line_ending: self.line_ending.as_str(),
2341 }
2342 }
2343
2344 pub fn text_width(&self) -> usize {
2345 self.editor_config
2346 .max_line_length
2347 .map(|n| n.get() as usize)
2348 .or_else(|| self.language_config().and_then(|config| config.text_width))
2349 .unwrap_or_else(|| self.config.load().text_width)
2350 }
2351
2352 pub fn text_format(&self, mut viewport_width: u16, theme: Option<&Theme>) -> TextFormat {
2353 let config = self.config.load();
2354 let text_width = self.text_width();
2355 let mut soft_wrap_at_text_width = self
2356 .language_config()
2357 .and_then(|config| {
2358 config
2359 .soft_wrap
2360 .as_ref()
2361 .and_then(|soft_wrap| soft_wrap.wrap_at_text_width)
2362 })
2363 .or(config.soft_wrap.wrap_at_text_width)
2364 .unwrap_or(false);
2365 if soft_wrap_at_text_width {
2366 // if the viewport is smaller than the specified
2367 // width then this setting has no effcet
2368 if text_width >= viewport_width as usize {
2369 soft_wrap_at_text_width = false;
2370 } else {
2371 viewport_width = text_width as u16;
2372 }
2373 }
2374 let config = self.config.load();
2375 let editor_soft_wrap = &config.soft_wrap;
2376 let language_soft_wrap = self
2377 .language
2378 .as_ref()
2379 .and_then(|config| config.soft_wrap.as_ref());
2380 let enable_soft_wrap = language_soft_wrap
2381 .and_then(|soft_wrap| soft_wrap.enable)
2382 .or(editor_soft_wrap.enable)
2383 .unwrap_or(false);
2384 let max_wrap = language_soft_wrap
2385 .and_then(|soft_wrap| soft_wrap.max_wrap)
2386 .or(config.soft_wrap.max_wrap)
2387 .unwrap_or(20);
2388 let max_indent_retain = language_soft_wrap
2389 .and_then(|soft_wrap| soft_wrap.max_indent_retain)
2390 .or(editor_soft_wrap.max_indent_retain)
2391 .unwrap_or(40);
2392 let wrap_indicator = language_soft_wrap
2393 .and_then(|soft_wrap| soft_wrap.wrap_indicator.clone())
2394 .or_else(|| config.soft_wrap.wrap_indicator.clone())
2395 .unwrap_or_else(|| "↪ ".into());
2396 let tab_width = self.tab_width() as u16;
2397 TextFormat {
2398 soft_wrap: enable_soft_wrap && viewport_width > 10,
2399 tab_width,
2400 max_wrap: max_wrap.min(viewport_width / 4),
2401 max_indent_retain: max_indent_retain.min(viewport_width * 2 / 5),
2402 // avoid spinning forever when the window manager
2403 // sets the size to something tiny
2404 viewport_width,
2405 wrap_indicator: wrap_indicator.into_boxed_str(),
2406 wrap_indicator_highlight: theme
2407 .and_then(|theme| theme.find_highlight("ui.virtual.wrap")),
2408 soft_wrap_at_text_width,
2409 }
2410 }
2411
2412 /// Set the inlay hints for this document and `view_id`.
2413 pub fn set_inlay_hints(&mut self, view_id: ViewId, inlay_hints: DocumentInlayHints) {
2414 self.inlay_hints.insert(view_id, inlay_hints);
2415 }
2416
2417 pub fn set_jump_labels(&mut self, view_id: ViewId, labels: Vec<Overlay>) {
2418 self.jump_labels.insert(view_id, labels);
2419 }
2420
2421 pub fn remove_jump_labels(&mut self, view_id: ViewId) {
2422 self.jump_labels.remove(&view_id);
2423 }
2424
2425 pub fn set_document_highlights(
2426 &mut self,
2427 view_id: ViewId,
2428 ranges: Vec<std::ops::Range<usize>>,
2429 ) {
2430 if ranges.is_empty() {
2431 self.document_highlights.remove(&view_id);
2432 } else {
2433 self.document_highlights
2434 .insert(view_id, DocumentHighlights { ranges });
2435 }
2436 }
2437
2438 pub fn clear_document_highlights(&mut self, view_id: ViewId) {
2439 self.document_highlights.remove(&view_id);
2440 }
2441
2442 pub fn clear_all_document_highlights(&mut self) {
2443 self.document_highlights.clear();
2444 self.document_highlight_controllers.clear();
2445 }
2446
2447 pub fn document_highlights(&self, view_id: ViewId) -> Option<&[std::ops::Range<usize>]> {
2448 self.document_highlights
2449 .get(&view_id)
2450 .map(|highlights| highlights.ranges.as_slice())
2451 }
2452
2453 pub fn document_highlight_controller(&mut self, view_id: ViewId) -> &mut TaskController {
2454 self.document_highlight_controllers
2455 .entry(view_id)
2456 .or_default()
2457 }
2458
2459 pub fn set_code_action_hints(&mut self, view_id: ViewId) {
2460 self.code_action_hints.insert(view_id);
2461 }
2462
2463 pub fn clear_code_action_hints(&mut self, view_id: ViewId) {
2464 self.code_action_hints.remove(&view_id);
2465 }
2466
2467 pub fn clear_all_code_action_hints(&mut self) {
2468 self.code_action_hints.clear();
2469 self.code_action_controllers.clear();
2470 }
2471
2472 pub fn code_action_hints(&self, view_id: ViewId) -> bool {
2473 self.code_action_hints.contains(&view_id)
2474 }
2475
2476 pub fn code_action_controller(&mut self, view_id: ViewId) -> &mut TaskController {
2477 self.code_action_controllers.entry(view_id).or_default()
2478 }
2479
2480 /// Get the inlay hints for this document and `view_id`.
2481 pub fn inlay_hints(&self, view_id: ViewId) -> Option<&DocumentInlayHints> {
2482 self.inlay_hints.get(&view_id)
2483 }
2484
2485 /// Completely removes all the inlay hints saved for the document, dropping them to free memory
2486 /// (since it often means inlay hints have been fully deactivated).
2487 pub fn reset_all_inlay_hints(&mut self) {
2488 self.inlay_hints = Default::default();
2489 }
2490
2491 pub fn has_language_server_with_feature(&self, feature: LanguageServerFeature) -> bool {
2492 self.language_servers_with_feature(feature).next().is_some()
2493 }
2494 }
2495
2496 #[derive(Debug, Default)]
2497 pub struct ViewData {
2498 view_position: ViewPosition,
2499 }
2500
2501 #[derive(Clone, Debug)]
2502 pub enum FormatterError {
2503 SpawningFailed {
2504 command: String,
2505 error: std::io::ErrorKind,
2506 },
2507 BrokenStdin,
2508 WaitForOutputFailed,
2509 InvalidUtf8Output,
2510 NonZeroExitStatus(Option<String>),
2511 }
2512
2513 impl std::error::Error for FormatterError {}
2514
2515 impl Display for FormatterError {
2516 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
2517 match self {
2518 Self::SpawningFailed { command, error } => {
2519 write!(f, "Failed to spawn formatter {}: {:?}", command, error)
2520 }
2521 Self::BrokenStdin => write!(f, "Could not write to formatter stdin"),
2522 Self::WaitForOutputFailed => write!(f, "Waiting for formatter output failed"),
2523 Self::InvalidUtf8Output => write!(f, "Invalid UTF-8 formatter output"),
2524 Self::NonZeroExitStatus(Some(output)) => write!(f, "Formatter error: {}", output),
2525 Self::NonZeroExitStatus(None) => {
2526 write!(f, "Formatter exited with non zero exit status")
2527 }
2528 }
2529 }
2530 }
2531
2532 #[cfg(test)]
2533 mod test {
2534 use arc_swap::ArcSwap;
2535
2536 use super::*;
2537
2538 #[test]
2539 fn changeset_to_changes_ignore_line_endings() {
2540 use helix_lsp::{lsp, Client, OffsetEncoding};
2541 let text = Rope::from("hello\r\nworld");
2542 let mut doc = Document::from(
2543 text,
2544 None,
2545 Arc::new(ArcSwap::new(Arc::new(Config::default()))),
2546 Arc::new(ArcSwap::from_pointee(syntax::Loader::default())),
2547 );
2548 let view = ViewId::default();
2549 doc.set_selection(view, Selection::single(0, 0));
2550
2551 let transaction =
2552 Transaction::change(doc.text(), vec![(5, 7, Some("\n".into()))].into_iter());
2553 let old_doc = doc.text().clone();
2554 doc.apply(&transaction, view);
2555 let changes = Client::changeset_to_changes(
2556 &old_doc,
2557 doc.text(),
2558 transaction.changes(),
2559 OffsetEncoding::Utf8,
2560 );
2561
2562 assert_eq!(doc.text(), "hello\nworld");
2563
2564 assert_eq!(
2565 changes,
2566 &[lsp::TextDocumentContentChangeEvent {
2567 range: Some(lsp::Range::new(
2568 lsp::Position::new(0, 5),
2569 lsp::Position::new(1, 0)
2570 )),
2571 text: "\n".into(),
2572 range_length: None,
2573 }]
2574 );
2575 }
2576
2577 #[test]
2578 fn changeset_to_changes() {
2579 use helix_lsp::{lsp, Client, OffsetEncoding};
2580 let text = Rope::from("hello");
2581 let mut doc = Document::from(
2582 text,
2583 None,
2584 Arc::new(ArcSwap::new(Arc::new(Config::default()))),
2585 Arc::new(ArcSwap::from_pointee(syntax::Loader::default())),
2586 );
2587 let view = ViewId::default();
2588 doc.set_selection(view, Selection::single(5, 5));
2589
2590 // insert
2591
2592 let transaction = Transaction::insert(doc.text(), doc.selection(view), " world".into());
2593 let old_doc = doc.text().clone();
2594 doc.apply(&transaction, view);
2595 let changes = Client::changeset_to_changes(
2596 &old_doc,
2597 doc.text(),
2598 transaction.changes(),
2599 OffsetEncoding::Utf8,
2600 );
2601
2602 assert_eq!(
2603 changes,
2604 &[lsp::TextDocumentContentChangeEvent {
2605 range: Some(lsp::Range::new(
2606 lsp::Position::new(0, 5),
2607 lsp::Position::new(0, 5)
2608 )),
2609 text: " world".into(),
2610 range_length: None,
2611 }]
2612 );
2613
2614 // delete
2615
2616 let transaction = transaction.invert(&old_doc);
2617 let old_doc = doc.text().clone();
2618 doc.apply(&transaction, view);
2619 let changes = Client::changeset_to_changes(
2620 &old_doc,
2621 doc.text(),
2622 transaction.changes(),
2623 OffsetEncoding::Utf8,
2624 );
2625
2626 // line: 0-based.
2627 // col: 0-based, gaps between chars.
2628 // 0 1 2 3 4 5 6 7 8 9 0 1
2629 // |h|e|l|l|o| |w|o|r|l|d|
2630 // -------------
2631 // (0, 5)-(0, 11)
2632 assert_eq!(
2633 changes,
2634 &[lsp::TextDocumentContentChangeEvent {
2635 range: Some(lsp::Range::new(
2636 lsp::Position::new(0, 5),
2637 lsp::Position::new(0, 11)
2638 )),
2639 text: "".into(),
2640 range_length: None,
2641 }]
2642 );
2643
2644 // replace
2645
2646 // also tests that changes are layered, positions depend on previous changes.
2647
2648 doc.set_selection(view, Selection::single(0, 5));
2649 let transaction = Transaction::change(
2650 doc.text(),
2651 vec![(0, 2, Some("aei".into())), (3, 5, Some("ou".into()))].into_iter(),
2652 );
2653 // aeilou
2654 let old_doc = doc.text().clone();
2655 doc.apply(&transaction, view);
2656 let changes = Client::changeset_to_changes(
2657 &old_doc,
2658 doc.text(),
2659 transaction.changes(),
2660 OffsetEncoding::Utf8,
2661 );
2662
2663 assert_eq!(
2664 changes,
2665 &[
2666 // 0 1 2 3 4 5
2667 // |h|e|l|l|o|
2668 // ----
2669 //
2670 // aeillo
2671 lsp::TextDocumentContentChangeEvent {
2672 range: Some(lsp::Range::new(
2673 lsp::Position::new(0, 0),
2674 lsp::Position::new(0, 2)
2675 )),
2676 text: "aei".into(),
2677 range_length: None,
2678 },
2679 // 0 1 2 3 4 5 6
2680 // |a|e|i|l|l|o|
2681 // -----
2682 //
2683 // aeilou
2684 lsp::TextDocumentContentChangeEvent {
2685 range: Some(lsp::Range::new(
2686 lsp::Position::new(0, 4),
2687 lsp::Position::new(0, 6)
2688 )),
2689 text: "ou".into(),
2690 range_length: None,
2691 }
2692 ]
2693 );
2694 }
2695
2696 #[test]
2697 fn test_line_ending() {
2698 assert_eq!(
2699 Document::default(
2700 Arc::new(ArcSwap::new(Arc::new(Config::default()))),
2701 Arc::new(ArcSwap::from_pointee(syntax::Loader::default()))
2702 )
2703 .text()
2704 .to_string(),
2705 helix_core::NATIVE_LINE_ENDING.as_str()
2706 );
2707 }
2708
2709 macro_rules! decode {
2710 ($name:ident, $label:expr, $label_override:expr) => {
2711 #[test]
2712 fn $name() {
2713 let encoding = encoding::Encoding::for_label($label_override.as_bytes()).unwrap();
2714 let base_path = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("tests/encoding");
2715 let path = base_path.join(format!("{}_in.txt", $label));
2716 let ref_path = base_path.join(format!("{}_in_ref.txt", $label));
2717 assert!(path.exists());
2718 assert!(ref_path.exists());
2719
2720 let mut file = std::fs::File::open(path).unwrap();
2721 let text = from_reader(&mut file, Some(encoding.into()))
2722 .unwrap()
2723 .0
2724 .to_string();
2725 let expectation = std::fs::read_to_string(ref_path).unwrap();
2726 assert_eq!(text[..], expectation[..]);
2727 }
2728 };
2729 ($name:ident, $label:expr) => {
2730 decode!($name, $label, $label);
2731 };
2732 }
2733
2734 macro_rules! encode {
2735 ($name:ident, $label:expr, $label_override:expr) => {
2736 #[test]
2737 fn $name() {
2738 let encoding = encoding::Encoding::for_label($label_override.as_bytes()).unwrap();
2739 let base_path = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("tests/encoding");
2740 let path = base_path.join(format!("{}_out.txt", $label));
2741 let ref_path = base_path.join(format!("{}_out_ref.txt", $label));
2742 assert!(path.exists());
2743 assert!(ref_path.exists());
2744
2745 let text = Rope::from_str(&std::fs::read_to_string(path).unwrap());
2746 let mut buf: Vec<u8> = Vec::new();
2747 helix_lsp::block_on(to_writer(&mut buf, (encoding, false), &text)).unwrap();
2748
2749 let expectation = std::fs::read(ref_path).unwrap();
2750 assert_eq!(buf, expectation);
2751 }
2752 };
2753 ($name:ident, $label:expr) => {
2754 encode!($name, $label, $label);
2755 };
2756 }
2757
2758 decode!(big5_decode, "big5");
2759 encode!(big5_encode, "big5");
2760 decode!(euc_kr_decode, "euc_kr", "EUC-KR");
2761 encode!(euc_kr_encode, "euc_kr", "EUC-KR");
2762 decode!(gb18030_decode, "gb18030");
2763 encode!(gb18030_encode, "gb18030");
2764 decode!(iso_2022_jp_decode, "iso_2022_jp", "ISO-2022-JP");
2765 encode!(iso_2022_jp_encode, "iso_2022_jp", "ISO-2022-JP");
2766 decode!(jis0208_decode, "jis0208", "EUC-JP");
2767 encode!(jis0208_encode, "jis0208", "EUC-JP");
2768 decode!(jis0212_decode, "jis0212", "EUC-JP");
2769 decode!(shift_jis_decode, "shift_jis");
2770 encode!(shift_jis_encode, "shift_jis");
2771 }