on master help sign in
Handle non-UTF8 files
commitfd98e743e888e8fbddf4987213afbb19dd148fd7 authorShafkath Shuhan <shafkathshuhannyc@gmail.com> dateWed 23 Jun 2021, 02:03 (5 years ago) parent9706f11
7 files changed+352−59
.gitattributes+1 Cargo.lock+35−7 helix-core/src/lib.rs+1−1 helix-term/src/commands.rs+2−12 helix-view/Cargo.toml+3−1 helix-view/src/document.rs+307−34 helix-view/src/editor.rs+3−4
.gitattributesnew file+1
@@ -0,0 +1 @@
1+helix-view/tests/* linguist-generated
Cargo.lock+35−7
@@ -65,12 +65,29 @@ dependencies = [
6565 "jobserver",
6666]
6767
68+[[package]]
69+name = "cfg-if"
70+version = "0.1.10"
71+source = "registry+https://github.com/rust-lang/crates.io-index"
72+checksum = "4785bdd1c96b2a846b2bd7cc02e86b6b3dbf14e7e53446c4f54c92a361040822"
73+
6874[[package]]
6975name = "cfg-if"
7076version = "1.0.0"
7177source = "registry+https://github.com/rust-lang/crates.io-index"
7278checksum = "baf1de4339761588bc0619e3cbc0120ee582ebb74b53b4efbf79117bd2da40fd"
7379
80+[[package]]
81+name = "chardetng"
82+version = "0.1.13"
83+source = "registry+https://github.com/rust-lang/crates.io-index"
84+checksum = "81a81b0d8f8ee23417182818b4f06312c5f535c2b04eef1773f7c24bbdf8c500"
85+dependencies = [
86+ "cfg-if 0.1.10",
87+ "encoding_rs",
88+ "memchr",
89+]
90+
7491[[package]]
7592name = "chrono"
7693version = "0.4.19"
@@ -89,7 +106,7 @@ version = "0.8.5"
89106source = "registry+https://github.com/rust-lang/crates.io-index"
90107checksum = "d82cfc11ce7f2c3faef78d8a684447b40d503d9681acebed6cb728d45940c4db"
91108dependencies = [
92− "cfg-if",
109+ "cfg-if 1.0.0",
93110 "lazy_static",
94111]
95112
@@ -125,7 +142,7 @@ version = "2.0.0"
125142source = "registry+https://github.com/rust-lang/crates.io-index"
126143checksum = "b98cf8ebf19c3d1b223e151f99a4f9f0690dca41414773390fc824184ac833e1"
127144dependencies = [
128− "cfg-if",
145+ "cfg-if 1.0.0",
129146 "dirs-sys-next",
130147]
131148
@@ -146,13 +163,22 @@ version = "1.6.1"
146163source = "registry+https://github.com/rust-lang/crates.io-index"
147164checksum = "e78d4f1cc4ae33bbfc157ed5d5a5ef3bc29227303d595861deb238fcec4e9457"
148165
166+[[package]]
167+name = "encoding_rs"
168+version = "0.8.28"
169+source = "registry+https://github.com/rust-lang/crates.io-index"
170+checksum = "80df024fbc5ac80f87dfef0d9f5209a252f2a497f7f42944cff24d8253cac065"
171+dependencies = [
172+ "cfg-if 1.0.0",
173+]
174+
149175[[package]]
150176name = "etcetera"
151177version = "0.3.2"
152178source = "registry+https://github.com/rust-lang/crates.io-index"
153179checksum = "016b04fd1e94fb833d432634245c9bb61cf1c7409668a0e7d4c3ab00c5172dec"
154180dependencies = [
155− "cfg-if",
181+ "cfg-if 1.0.0",
156182 "dirs-next",
157183 "thiserror",
158184]
@@ -244,7 +270,7 @@ version = "0.2.3"
244270source = "registry+https://github.com/rust-lang/crates.io-index"
245271checksum = "7fcd999463524c52659517fe2cea98493cfe485d10565e7b0fb07dbba7ad2753"
246272dependencies = [
247− "cfg-if",
273+ "cfg-if 1.0.0",
248274 "libc",
249275 "wasi",
250276]
@@ -355,7 +381,9 @@ name = "helix-view"
355381version = "0.2.0"
356382dependencies = [
357383 "anyhow",
384+ "chardetng",
358385 "crossterm",
386+ "encoding_rs",
359387 "futures-util",
360388 "helix-core",
361389 "helix-lsp",
@@ -414,7 +442,7 @@ version = "0.1.9"
414442source = "registry+https://github.com/rust-lang/crates.io-index"
415443checksum = "61124eeebbd69b8190558df225adf7e4caafce0d743919e5d6b19652314ec5ec"
416444dependencies = [
417− "cfg-if",
445+ "cfg-if 1.0.0",
418446]
419447
420448[[package]]
@@ -472,7 +500,7 @@ version = "0.4.14"
472500source = "registry+https://github.com/rust-lang/crates.io-index"
473501checksum = "51b9bbe6c47d51fc3e1a9b945965946b4c44142ab8792c50835a980d362c2710"
474502dependencies = [
475− "cfg-if",
503+ "cfg-if 1.0.0",
476504]
477505
478506[[package]]
@@ -595,7 +623,7 @@ version = "0.8.3"
595623source = "registry+https://github.com/rust-lang/crates.io-index"
596624checksum = "fa7a782938e745763fe6907fc6ba86946d72f49fe7e21de074e08128a99fb018"
597625dependencies = [
598− "cfg-if",
626+ "cfg-if 1.0.0",
599627 "instant",
600628 "libc",
601629 "redox_syscall",
helix-core/src/lib.rs+1−1
@@ -101,7 +101,7 @@ pub use etcetera::home_dir;
101101
102102use etcetera::base_strategy::{choose_base_strategy, BaseStrategy};
103103
104−pub use ropey::{Rope, RopeSlice};
104+pub use ropey::{Rope, RopeBuilder, RopeSlice};
105105
106106pub use tendril::StrTendril as Tendril;
107107
helix-term/src/commands.rs+2−12
@@ -239,7 +239,6 @@ impl Command {
239239 join_selections,
240240 keep_selections,
241241 keep_primary_selection,
242− save,
243242 completion,
244243 hover,
245244 toggle_comments,
@@ -1080,7 +1079,7 @@ mod cmd {
10801079 if autofmt {
10811080 doc.format(view.id); // TODO: merge into save
10821081 }
1083− helix_lsp::block_on(doc.save());
1082+ helix_lsp::block_on(tokio::spawn(doc.save()));
10841083 Ok(())
10851084 }
10861085
@@ -1256,7 +1255,7 @@ mod cmd {
12561255 errors.push_str("cannot write a buffer without a filename\n");
12571256 continue;
12581257 }
1259− helix_lsp::block_on(doc.save());
1258+ helix_lsp::block_on(tokio::spawn(doc.save()));
12601259 }
12611260 editor.set_error(errors);
12621261
@@ -2950,15 +2949,6 @@ fn keep_primary_selection(cx: &mut Context) {
29502949 doc.set_selection(view.id, selection);
29512950}
29522951
2953−//
2954−
2955−fn save(cx: &mut Context) {
2956− // Spawns an async task to actually do the saving. This way we prevent blocking.
2957−
2958− // TODO: handle save errors somehow?
2959− tokio::spawn(doc_mut!(cx.editor).save());
2960−}
2961−
29622952fn completion(cx: &mut Context) {
29632953 // trigger on trigger char, or if user calls it
29642954 // (or on word char typing??)
helix-view/Cargo.toml+3−1
@@ -31,9 +31,11 @@ futures-util = { version = "0.3", features = ["std", "async-await"], default-fea
3131
3232slotmap = "1"
3333
34+encoding_rs = "0.8"
35+chardetng = "0.1"
36+
3437serde = { version = "1.0", features = ["derive"] }
3538toml = "0.5"
3639log = "~0.4"
3740
3841which = "4.1"
39−
helix-view/src/document.rs+307−34
@@ -11,7 +11,7 @@ use helix_core::{
1111 history::History,
1212 line_ending::auto_detect_line_ending,
1313 syntax::{self, LanguageConfiguration},
14− ChangeSet, Diagnostic, LineEnding, Rope, Selection, State, Syntax, Transaction,
14+ ChangeSet, Diagnostic, LineEnding, Rope, RopeBuilder, Selection, State, Syntax, Transaction,
1515 DEFAULT_LINE_ENDING,
1616};
1717
@@ -19,6 +19,8 @@ use crate::{DocumentId, Theme, ViewId};
1919
2020use std::collections::HashMap;
2121
22+const BUF_SIZE: usize = 8192;
23+
2224#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
2325pub enum Mode {
2426 Normal,
@@ -39,6 +41,7 @@ pub struct Document {
3941 pub(crate) selections: HashMap<ViewId, Selection>,
4042
4143 path: Option<PathBuf>,
44+ encoding: &'static encoding_rs::Encoding,
4245
4346 /// Current editing mode.
4447 pub mode: Mode,
@@ -78,6 +81,7 @@ impl fmt::Debug for Document {
7881 .field("text", &self.text)
7982 .field("selections", &self.selections)
8083 .field("path", &self.path)
84+ .field("encoding", &self.encoding)
8185 .field("mode", &self.mode)
8286 .field("restore_cursor", &self.restore_cursor)
8387 .field("syntax", &self.syntax)
@@ -116,6 +120,173 @@ impl FromStr for Mode {
116120 }
117121}
118122
123+// The documentation and implementation of this function should be up-to-date with
124+// its sibling function, `to_writer()`.
125+//
126+/// Decodes a stream of bytes into UTF-8, returning a `Rope` and the
127+/// encoding it was decoded as. The optional `encoding` parameter can
128+/// be used to override encoding auto-detection.
129+pub fn from_reader<R: std::io::Read + ?Sized>(
130+ reader: &mut R,
131+ encoding: Option<&'static encoding_rs::Encoding>,
132+) -> Result<(Rope, &'static encoding_rs::Encoding), Error> {
133+ // These two buffers are 8192 bytes in size each and are used as
134+ // intermediaries during the decoding process. Text read into `buf`
135+ // from `reader` is decoded into `buf_out` as UTF-8. Once either
136+ // `buf_out` is full or the end of the reader was reached, the
137+ // contents are appended to `builder`.
138+ let mut buf = [0u8; BUF_SIZE];
139+ let mut buf_out = [0u8; BUF_SIZE];
140+ let mut builder = RopeBuilder::new();
141+
142+ // By default, the encoding of the text is auto-detected via the
143+ // `chardetng` crate which requires sample data from the reader.
144+ // As a manual override to this auto-detection is possible, the
145+ // same data is read into `buf` to ensure symmetry in the upcoming
146+ // loop.
147+ let (encoding, mut decoder, mut slice, mut is_empty) = {
148+ let read = reader.read(&mut buf)?;
149+ let is_empty = read == 0;
150+ let encoding = encoding.unwrap_or_else(|| {
151+ let mut encoding_detector = chardetng::EncodingDetector::new();
152+ encoding_detector.feed(&buf, is_empty);
153+ encoding_detector.guess(None, true)
154+ });
155+ let decoder = encoding.new_decoder();
156+
157+ // If the amount of bytes read from the reader is less than
158+ // `buf.len()`, it is undesirable to read the bytes afterwards.
159+ let slice = &buf[..read];
160+ (encoding, decoder, slice, is_empty)
161+ };
162+
163+ // `RopeBuilder::append()` expects a `&str`, so this is the "real"
164+ // output buffer. When decoding, the number of bytes in the output
165+ // buffer will often exceed the number of bytes in the input buffer.
166+ // The `result` returned by `decode_to_str()` will state whether or
167+ // not that happened. The contents of `buf_str` is appended to
168+ // `builder` and it is reused for the next iteration of the decoding
169+ // loop.
170+ //
171+ // As it is possible to read less than the buffer's maximum from `read()`
172+ // even when the end of the reader has yet to be reached, the end of
173+ // the reader is determined only when a `read()` call returns `0`.
174+ //
175+ // SAFETY: `buf_out` is a zero-initialized array, thus it will always
176+ // contain valid UTF-8.
177+ let buf_str = unsafe { std::str::from_utf8_unchecked_mut(&mut buf_out[..]) };
178+ let mut total_written = 0usize;
179+ loop {
180+ let mut total_read = 0usize;
181+
182+ loop {
183+ let (result, read, written, ..) = decoder.decode_to_str(
184+ &slice[total_read..],
185+ &mut buf_str[total_written..],
186+ is_empty,
187+ );
188+
189+ // These variables act as the read and write cursors of `buf` and `buf_str` respectively.
190+ // They are necessary in case the output buffer fills before decoding of the entire input
191+ // loop is complete. Otherwise, the loop would endlessly iterate over the same `buf` and
192+ // the data inside the output buffer would be overwritten.
193+ total_read += read;
194+ total_written += written;
195+ match result {
196+ encoding_rs::CoderResult::InputEmpty => {
197+ debug_assert_eq!(slice.len(), total_read);
198+ break;
199+ }
200+ encoding_rs::CoderResult::OutputFull => {
201+ debug_assert!(slice.len() > total_read);
202+ builder.append(&buf_str[..total_written]);
203+ total_written = 0;
204+ }
205+ }
206+ }
207+ // Once the end of the stream is reached, the output buffer is
208+ // flushed and the loop terminates.
209+ if is_empty {
210+ debug_assert_eq!(reader.read(&mut buf)?, 0);
211+ builder.append(&buf_str[..total_written]);
212+ break;
213+ }
214+
215+ // Once the previous input has been processed and decoded, the next set of
216+ // data is fetched from the reader. The end of the reader is determined to
217+ // be when exactly `0` bytes were read from the reader, as per the invariants
218+ // of the `Read` trait.
219+ let read = reader.read(&mut buf)?;
220+ slice = &buf[..read];
221+ is_empty = read == 0;
222+ }
223+ let rope = builder.finish();
224+ Ok((rope, encoding))
225+}
226+
227+// The documentation and implementation of this function should be up-to-date with
228+// its sibling function, `from_reader()`.
229+//
230+/// Encodes the text inside `rope` into the given `encoding` and writes the
231+/// encoded output into `writer.` As a `Rope` can only contain valid UTF-8,
232+/// replacement characters may appear in the encoded text.
233+pub async fn to_writer<'a, W: tokio::io::AsyncWriteExt + Unpin + ?Sized>(
234+ writer: &'a mut W,
235+ encoding: &'static encoding_rs::Encoding,
236+ rope: &'a Rope,
237+) -> Result<(), Error> {
238+ // Text inside a `Rope` is stored as non-contiguous blocks of data called
239+ // chunks. The absolute size of each chunk is unknown, thus it is impossible
240+ // to predict the end of the chunk iterator ahead of time. Instead, it is
241+ // determined by filtering the iterator to remove all empty chunks and then
242+ // appending an empty chunk to it. This is valuable for detecting when all
243+ // chunks in the `Rope` have been iterated over in the subsequent loop.
244+ let iter = rope
245+ .chunks()
246+ .filter(|c| !c.is_empty())
247+ .chain(std::iter::once(""));
248+ let mut buf = [0u8; BUF_SIZE];
249+ let mut encoder = encoding.new_encoder();
250+ let mut total_written = 0usize;
251+ for chunk in iter {
252+ let is_empty = chunk.is_empty();
253+ let mut total_read = 0usize;
254+
255+ loop {
256+ let (result, read, written, ..) =
257+ encoder.encode_from_utf8(&chunk[total_read..], &mut buf[total_written..], is_empty);
258+
259+ // These variables act as the read and write cursors of `chunk` and `buf` respectively.
260+ // They are necessary in case the output buffer fills before encoding of the entire input
261+ // loop is complete. Otherwise, the loop would endlessly iterate over the same `chunk` and
262+ // the data inside the output buffer would be overwritten.
263+ total_read += read;
264+ total_written += written;
265+ match result {
266+ encoding_rs::CoderResult::InputEmpty => {
267+ debug_assert_eq!(chunk.len(), total_read);
268+ debug_assert!(buf.len() >= total_written);
269+ break;
270+ }
271+ encoding_rs::CoderResult::OutputFull => {
272+ debug_assert!(chunk.len() > total_read);
273+ writer.write_all(&buf[..total_written]).await?;
274+ total_written = 0;
275+ }
276+ }
277+ }
278+
279+ // Once the end of the iterator is reached, the output buffer is
280+ // flushed and the outer loop terminates.
281+ if is_empty {
282+ writer.write_all(&buf[..total_written]).await?;
283+ writer.flush().await?;
284+ break;
285+ }
286+ }
287+ Ok(())
288+}
289+
119290/// Like std::mem::replace() except it allows the replacement value to be mapped from the
120291/// original value.
121292fn take_with<T, F>(mut_ref: &mut T, closure: F)
@@ -216,13 +387,15 @@ use helix_lsp::lsp;
216387use url::Url;
217388
218389impl Document {
219− pub fn new(text: Rope) -> Self {
390+ pub fn from(text: Rope, encoding: Option<&'static encoding_rs::Encoding>) -> Self {
391+ let encoding = encoding.unwrap_or(encoding_rs::UTF_8);
220392 let changes = ChangeSet::new(&text);
221393 let old_state = None;
222394
223395 Self {
224396 id: DocumentId::default(),
225397 path: None,
398+ encoding,
226399 text,
227400 selections: HashMap::default(),
228401 indent_style: IndentStyle::Spaces(4),
@@ -242,29 +415,31 @@ impl Document {
242415 }
243416
244417 // TODO: async fn?
245− pub fn load(
418+ /// Create a new document from `path`. Encoding is auto-detected, but it can be manually
419+ /// overwritten with the `encoding` parameter.
420+ pub fn open(
246421 path: PathBuf,
422+ encoding: Option<&'static encoding_rs::Encoding>,
247423 theme: Option<&Theme>,
248424 config_loader: Option<&syntax::Loader>,
249425 ) -> Result<Self, Error> {
250− use std::{fs::File, io::BufReader};
426+ if !path.exists() {
427+ return Ok(Self::default());
428+ }
251429
252− let mut doc = if !path.exists() {
253− Rope::from(DEFAULT_LINE_ENDING.as_str())
254− } else {
255− let file = File::open(&path).context(format!("unable to open {:?}", path))?;
256− Rope::from_reader(BufReader::new(file))?
257− };
430+ let mut file = std::fs::File::open(&path).context(format!("unable to open {:?}", path))?;
431+ let (mut rope, encoding) = from_reader(&mut file, encoding)?;
258432
259433 // search for line endings
260− let line_ending = auto_detect_line_ending(&doc).unwrap_or(DEFAULT_LINE_ENDING);
434+ let line_ending = auto_detect_line_ending(&rope).unwrap_or(DEFAULT_LINE_ENDING);
261435
262436 // add missing newline at the end of file
263− if doc.len_bytes() == 0 || !char_is_line_ending(doc.char(doc.len_chars() - 1)) {
264− doc.insert(doc.len_chars(), line_ending.as_str());
437+ if rope.len_bytes() == 0 || !char_is_line_ending(rope.char(rope.len_chars() - 1)) {
438+ rope.insert(rope.len_chars(), line_ending.as_str());
265439 }
266440
267− let mut doc = Self::new(doc);
441+ let mut doc = Self::from(rope, Some(encoding));
442+
268443 // set the path and try detecting the language
269444 doc.set_path(&path)?;
270445 doc.detect_indent_style();
@@ -303,6 +478,8 @@ impl Document {
303478
304479 // TODO: do we need some way of ensuring two save operations on the same doc can't run at once?
305480 // or is that handled by the OS/async layer
481+ /// The `Document`'s text is encoded according to its encoding and written to the file located
482+ /// at its `path()`.
306483 pub fn save(&mut self) -> impl Future<Output = Result<(), anyhow::Error>> {
307484 // we clone and move text + path into the future so that we asynchronously save the current
308485 // state without blocking any further edits.
@@ -320,8 +497,11 @@ impl Document {
320497 self.last_saved_revision = history.current_revision();
321498 self.history.set(history);
322499
500+ let encoding = self.encoding;
501+
502+ // We encode the file according to the `Document`'s encoding.
323503 async move {
324− use tokio::{fs::File, io::AsyncWriteExt};
504+ use tokio::fs::File;
325505 if let Some(parent) = path.parent() {
326506 // TODO: display a prompt asking the user if the directories should be created
327507 if !parent.exists() {
@@ -330,13 +510,9 @@ impl Document {
330510 ));
331511 }
332512 }
333− let mut file = File::create(path).await?;
334513
335− // write all the rope chunks to file
336− for chunk in text.chunks() {
337− file.write_all(chunk.as_bytes()).await?;
338− }
339− // TODO: flush?
514+ let mut file = File::create(path).await?;
515+ to_writer(&mut file, encoding, &text).await?;
340516
341517 if let Some(language_server) = language_server {
342518 language_server
@@ -531,7 +707,7 @@ impl Document {
531707 self.selections.insert(view_id, selection);
532708 }
533709
534− fn _apply(&mut self, transaction: &Transaction, view_id: ViewId) -> bool {
710+ fn apply_impl(&mut self, transaction: &Transaction, view_id: ViewId) -> bool {
535711 let old_doc = self.text().clone();
536712
537713 let success = transaction.changes().apply(&mut self.text);
@@ -594,7 +770,7 @@ impl Document {
594770 });
595771 }
596772
597− let success = self._apply(transaction, view_id);
773+ let success = self.apply_impl(transaction, view_id);
598774
599775 if !transaction.changes().is_empty() {
600776 // Compose this transaction with the previous one
@@ -608,7 +784,7 @@ impl Document {
608784 pub fn undo(&mut self, view_id: ViewId) {
609785 let mut history = self.history.take();
610786 let success = if let Some(transaction) = history.undo() {
611− self._apply(&transaction, view_id)
787+ self.apply_impl(transaction, view_id)
612788 } else {
613789 false
614790 };
@@ -623,7 +799,7 @@ impl Document {
623799 pub fn redo(&mut self, view_id: ViewId) {
624800 let mut history = self.history.take();
625801 let success = if let Some(transaction) = history.redo() {
626− self._apply(&transaction, view_id)
802+ self.apply_impl(transaction, view_id)
627803 } else {
628804 false
629805 };
@@ -638,14 +814,14 @@ impl Document {
638814 pub fn earlier(&mut self, view_id: ViewId, uk: helix_core::history::UndoKind) {
639815 let txns = self.history.get_mut().earlier(uk);
640816 for txn in txns {
641− self._apply(&txn, view_id);
817+ self.apply_impl(&txn, view_id);
642818 }
643819 }
644820
645821 pub fn later(&mut self, view_id: ViewId, uk: helix_core::history::UndoKind) {
646822 let txns = self.history.get_mut().later(uk);
647823 for txn in txns {
648− self._apply(&txn, view_id);
824+ self.apply_impl(&txn, view_id);
649825 }
650826 }
651827
@@ -670,12 +846,10 @@ impl Document {
670846 self.history.set(history);
671847 }
672848
673− #[inline]
674849 pub fn id(&self) -> DocumentId {
675850 self.id
676851 }
677852
678− #[inline]
679853 pub fn is_modified(&self) -> bool {
680854 let history = self.history.take();
681855 let current_revision = history.current_revision();
@@ -683,12 +857,10 @@ impl Document {
683857 current_revision != self.last_saved_revision || !self.changes.is_empty()
684858 }
685859
686− #[inline]
687860 pub fn mode(&self) -> Mode {
688861 self.mode
689862 }
690863
691− #[inline]
692864 /// Corresponding language scope name. Usually `source.<lang>`.
693865 pub fn language(&self) -> Option<&str> {
694866 self.language
@@ -696,21 +868,21 @@ impl Document {
696868 .map(|language| language.scope.as_str())
697869 }
698870
699− #[inline]
700871 pub fn language_config(&self) -> Option<&LanguageConfiguration> {
701872 self.language.as_deref()
702873 }
703874
704− #[inline]
705875 /// Current document version, incremented at each change.
706876 pub fn version(&self) -> i32 {
707877 self.version
708878 }
709879
880+ #[inline]
710881 pub fn language_server(&self) -> Option<&helix_lsp::Client> {
711882 self.language_server.as_deref()
712883 }
713884
885+ #[inline]
714886 /// Tree-sitter AST tree
715887 pub fn syntax(&self) -> Option<&Syntax> {
716888 self.syntax.as_ref()
@@ -756,10 +928,12 @@ impl Document {
756928 self.path().map(|path| Url::from_file_path(path).unwrap())
757929 }
758930
931+ #[inline]
759932 pub fn text(&self) -> &Rope {
760933 &self.text
761934 }
762935
936+ #[inline]
763937 pub fn selection(&self, view_id: ViewId) -> &Selection {
764938 &self.selections[&view_id]
765939 }
@@ -787,6 +961,7 @@ impl Document {
787961
788962 // -- LSP methods
789963
964+ #[inline]
790965 pub fn identifier(&self) -> lsp::TextDocumentIdentifier {
791966 lsp::TextDocumentIdentifier::new(self.url().unwrap())
792967 }
@@ -795,6 +970,7 @@ impl Document {
795970 lsp::VersionedTextDocumentIdentifier::new(self.url().unwrap(), self.version)
796971 }
797972
973+ #[inline]
798974 pub fn diagnostics(&self) -> &[Diagnostic] {
799975 &self.diagnostics
800976 }
@@ -804,6 +980,13 @@ impl Document {
804980 }
805981}
806982
983+impl Default for Document {
984+ fn default() -> Self {
985+ let text = Rope::from(DEFAULT_LINE_ENDING.as_str());
986+ Self::from(text, None)
987+ }
988+}
989+
807990#[cfg(test)]
808991mod test {
809992 use super::*;
@@ -812,7 +995,7 @@ mod test {
812995 fn changeset_to_changes() {
813996 use helix_lsp::{lsp, Client, OffsetEncoding};
814997 let text = Rope::from("hello");
815− let mut doc = Document::new(text);
998+ let mut doc = Document::from(text, None);
816999 let view = ViewId::default();
8171000 doc.set_selection(view, Selection::single(5, 5));
8181001
@@ -921,4 +1104,94 @@ mod test {
9211104 ]
9221105 );
9231106 }
1107+
1108+ #[test]
1109+ fn test_line_ending() {
1110+ if cfg!(windows) {
1111+ assert_eq!(Document::default().text().to_string(), "\r\n");
1112+ } else {
1113+ assert_eq!(Document::default().text().to_string(), "\n");
1114+ }
1115+ }
1116+
1117+ macro_rules! test_decode {
1118+ ($label:expr, $label_override:expr) => {
1119+ let encoding = encoding_rs::Encoding::for_label($label_override.as_bytes()).unwrap();
1120+ let base_path = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("tests");
1121+ let path = base_path.join(format!("{}_in.txt", $label));
1122+ let ref_path = base_path.join(format!("{}_in_ref.txt", $label));
1123+ assert!(path.exists());
1124+ assert!(ref_path.exists());
1125+
1126+ let mut file = std::fs::File::open(path).unwrap();
1127+ let text = from_reader(&mut file, Some(encoding))
1128+ .unwrap()
1129+ .0
1130+ .to_string();
1131+ let expectation = std::fs::read_to_string(ref_path).unwrap();
1132+ assert_eq!(text[..], expectation[..]);
1133+ };
1134+ }
1135+
1136+ macro_rules! test_encode {
1137+ ($label:expr, $label_override:expr) => {
1138+ let encoding = encoding_rs::Encoding::for_label($label_override.as_bytes()).unwrap();
1139+ let base_path = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("tests");
1140+ let path = base_path.join(format!("{}_out.txt", $label));
1141+ let ref_path = base_path.join(format!("{}_out_ref.txt", $label));
1142+ assert!(path.exists());
1143+ assert!(ref_path.exists());
1144+
1145+ let text = Rope::from_str(&std::fs::read_to_string(path).unwrap());
1146+ let mut buf: Vec<u8> = Vec::new();
1147+ helix_lsp::block_on(to_writer(&mut buf, encoding, &text)).unwrap();
1148+
1149+ let expectation = std::fs::read(ref_path).unwrap();
1150+ assert_eq!(buf, expectation);
1151+ };
1152+ }
1153+
1154+ macro_rules! test_decode_fn {
1155+ ($name:ident, $label:expr, $label_override:expr) => {
1156+ #[test]
1157+ fn $name() {
1158+ test_decode!($label, $label_override);
1159+ }
1160+ };
1161+ ($name:ident, $label:expr) => {
1162+ #[test]
1163+ fn $name() {
1164+ test_decode!($label, $label);
1165+ }
1166+ };
1167+ }
1168+
1169+ macro_rules! test_encode_fn {
1170+ ($name:ident, $label:expr, $label_override:expr) => {
1171+ #[test]
1172+ fn $name() {
1173+ test_encode!($label, $label_override);
1174+ }
1175+ };
1176+ ($name:ident, $label:expr) => {
1177+ #[test]
1178+ fn $name() {
1179+ test_encode!($label, $label);
1180+ }
1181+ };
1182+ }
1183+
1184+ test_decode_fn!(test_big5_decode, "big5");
1185+ test_encode_fn!(test_big5_encode, "big5");
1186+ test_decode_fn!(test_euc_kr_decode, "euc_kr", "EUC-KR");
1187+ test_encode_fn!(test_euc_kr_encode, "euc_kr", "EUC-KR");
1188+ test_decode_fn!(test_gb18030_decode, "gb18030");
1189+ test_encode_fn!(test_gb18030_encode, "gb18030");
1190+ test_decode_fn!(test_iso_2022_jp_decode, "iso_2022_jp", "ISO-2022-JP");
1191+ test_encode_fn!(test_iso_2022_jp_encode, "iso_2022_jp", "ISO-2022-JP");
1192+ test_decode_fn!(test_jis0208_decode, "jis0208", "EUC-JP");
1193+ test_encode_fn!(test_jis0208_encode, "jis0208", "EUC-JP");
1194+ test_decode_fn!(test_jis0212_decode, "jis0212", "EUC-JP");
1195+ test_decode_fn!(test_shift_jis_decode, "shift_jis");
1196+ test_encode_fn!(test_shift_jis_encode, "shift_jis");
9241197}
helix-view/src/editor.rs+3−4
@@ -17,7 +17,7 @@ use anyhow::Error;
1717
1818pub use helix_core::diagnostic::Severity;
1919pub use helix_core::register::Registers;
20−use helix_core::{Position, DEFAULT_LINE_ENDING};
20+use helix_core::Position;
2121
2222#[derive(Debug)]
2323pub struct Editor {
@@ -171,8 +171,7 @@ impl Editor {
171171 }
172172
173173 pub fn new_file(&mut self, action: Action) -> DocumentId {
174− use helix_core::Rope;
175− let doc = Document::new(Rope::from(DEFAULT_LINE_ENDING.as_str()));
174+ let doc = Document::default();
176175 let id = self.documents.insert(doc);
177176 self.documents[id].id = id;
178177 self.switch(id, action);
@@ -190,7 +189,7 @@ impl Editor {
190189 let id = if let Some(id) = id {
191190 id
192191 } else {
193− let mut doc = Document::load(path, Some(&self.theme), Some(&self.syn_loader))?;
192+ let mut doc = Document::open(path, None, Some(&self.theme), Some(&self.syn_loader))?;
194193
195194 // try to find a language server based on the language name
196195 let language_server = doc