on master help sign in
document should save even if formatter fails
commit3f07885b351748c5b8225aadb165f8ef7066f047 authorSkyler Hawthorne <skyler@dead10ck.com> dateFri 16 Sep 2022, 23:17 (4 years ago) parentb530a86
12 files changed+185−66
helix-core/src/syntax.rs+6 helix-term/src/application.rs+5−10 helix-term/src/commands.rs+15−12 helix-term/src/main.rs+11−1 helix-term/tests/test/auto_indent.rs+1 helix-term/tests/test/auto_pairs.rs+1 helix-term/tests/test/commands.rs+10−4 helix-term/tests/test/helpers.rs+77−13 helix-term/tests/test/movement.rs+3−1 helix-term/tests/test/prompt.rs+1−3 helix-term/tests/test/splits.rs+9−2 helix-term/tests/test/write.rs+46−20
helix-core/src/syntax.rs+6
@@ -61,6 +61,12 @@ pub struct Configuration {
6161 pub language: Vec<LanguageConfiguration>,
6262}
6363
64+impl Default for Configuration {
65+ fn default() -> Self {
66+ crate::config::default_syntax_loader()
67+ }
68+}
69+
6470// largely based on tree-sitter/cli/src/loader.rs
6571#[derive(Debug, Serialize, Deserialize)]
6672#[serde(rename_all = "kebab-case", deny_unknown_fields)]
helix-term/src/application.rs+5−10
@@ -1,7 +1,6 @@
11use arc_swap::{access::Map, ArcSwap};
22use futures_util::Stream;
33use helix_core::{
4− config::{default_syntax_loader, user_syntax_loader},
54 diagnostic::{DiagnosticTag, NumberOrString},
65 path::get_relative_path,
76 pos_at_coords, syntax, Selection,
@@ -110,7 +109,11 @@ fn restore_term() -> Result<(), Error> {
110109}
111110
112111impl Application {
113− pub fn new(args: Args, config: Config) -> Result<Self, Error> {
112+ pub fn new(
113+ args: Args,
114+ config: Config,
115+ syn_loader_conf: syntax::Configuration,
116+ ) -> Result<Self, Error> {
114117 #[cfg(feature = "integration")]
115118 setup_integration_logging();
116119
@@ -137,14 +140,6 @@ impl Application {
137140 })
138141 .unwrap_or_else(|| theme_loader.default_theme(true_color));
139142
140− let syn_loader_conf = user_syntax_loader().unwrap_or_else(|err| {
141− eprintln!("Bad language config: {}", err);
142− eprintln!("Press <ENTER> to continue with default language config");
143− use std::io::Read;
144− // This waits for an enter press.
145− let _ = std::io::stdin().read(&mut []);
146− default_syntax_loader()
147− });
148143 let syn_loader = std::sync::Arc::new(syntax::Loader::new(syn_loader_conf));
149144
150145 let mut compositor = Compositor::new().context("build compositor")?;
helix-term/src/commands.rs+15−12
@@ -2518,7 +2518,8 @@ async fn make_format_callback(
25182518 format: impl Future<Output = Result<Transaction, FormatterError>> + Send + 'static,
25192519 write: Option<(Option<PathBuf>, bool)>,
25202520) -> anyhow::Result<job::Callback> {
2521− let format = format.await?;
2521+ let format = format.await;
2522+
25222523 let call: job::Callback = Callback::Editor(Box::new(move |editor| {
25232524 if !editor.documents.contains_key(&doc_id) {
25242525 return;
@@ -2528,19 +2529,21 @@ async fn make_format_callback(
25282529 let doc = doc_mut!(editor, &doc_id);
25292530 let view = view_mut!(editor);
25302531
2531− if doc.version() == doc_version {
2532− apply_transaction(&format, doc, view);
2533− doc.append_changes_to_history(view.id);
2534− doc.detect_indent_and_line_ending();
2535− view.ensure_cursor_in_view(doc, scrolloff);
2532+ if let Ok(format) = format {
2533+ if doc.version() == doc_version {
2534+ apply_transaction(&format, doc, view);
2535+ doc.append_changes_to_history(view.id);
2536+ doc.detect_indent_and_line_ending();
2537+ view.ensure_cursor_in_view(doc, scrolloff);
2538+ } else {
2539+ log::info!("discarded formatting changes because the document changed");
2540+ }
2541+ }
25362542
2537− if let Some((path, force)) = write {
2538− if let Err(err) = doc.save(path, force) {
2539− editor.set_error(format!("Error saving: {}", err));
2540− }
2543+ if let Some((path, force)) = write {
2544+ if let Err(err) = doc.save(path, force) {
2545+ editor.set_error(format!("Error saving: {}", err));
25412546 }
2542− } else {
2543− log::info!("discarded formatting changes because the document changed");
25442547 }
25452548 }));
25462549
helix-term/src/main.rs+11−1
@@ -139,8 +139,18 @@ FLAGS:
139139 Err(err) => return Err(Error::new(err)),
140140 };
141141
142+ let syn_loader_conf = helix_core::config::user_syntax_loader().unwrap_or_else(|err| {
143+ eprintln!("Bad language config: {}", err);
144+ eprintln!("Press <ENTER> to continue with default language config");
145+ use std::io::Read;
146+ // This waits for an enter press.
147+ let _ = std::io::stdin().read(&mut []);
148+ helix_core::config::default_syntax_loader()
149+ });
150+
142151 // TODO: use the thread local executor to spawn the application task separately from the work pool
143− let mut app = Application::new(args, config).context("unable to create new application")?;
152+ let mut app = Application::new(args, config, syn_loader_conf)
153+ .context("unable to create new application")?;
144154
145155 let exit_code = app.run(&mut EventStream::new()).await?;
146156
helix-term/tests/test/auto_indent.rs+1
@@ -8,6 +8,7 @@ async fn auto_indent_c() -> anyhow::Result<()> {
88 ..Default::default()
99 },
1010 Config::default(),
11+ helpers::test_syntax_conf(None),
1112 // switches to append mode?
1213 (
1314 helpers::platform_line("void foo() {#[|}]#").as_ref(),
helix-term/tests/test/auto_pairs.rs+1
@@ -13,6 +13,7 @@ async fn auto_pairs_basic() -> anyhow::Result<()> {
1313 },
1414 ..Default::default()
1515 },
16+ helpers::test_syntax_conf(None),
1617 ("#[\n|]#", "i(<esc>", "(#[|\n]#"),
1718 )
1819 .await?;
helix-term/tests/test/commands.rs+10−4
@@ -1,16 +1,18 @@
11use std::ops::RangeInclusive;
22
33use helix_core::diagnostic::Severity;
4−use helix_term::application::Application;
54
65use super::*;
76
87#[tokio::test(flavor = "multi_thread")]
98async fn test_write_quit_fail() -> anyhow::Result<()> {
109 let file = helpers::new_readonly_tempfile()?;
10+ let mut app = helpers::AppBuilder::new()
11+ .with_file(file.path(), None)
12+ .build()?;
1113
1214 test_key_sequence(
13− &mut helpers::app_with_file(file.path())?,
15+ &mut app,
1416 Some("ihello<esc>:wq<ret>"),
1517 Some(&|app| {
1618 let mut docs: Vec<_> = app.editor.documents().collect();
@@ -30,7 +32,7 @@ async fn test_write_quit_fail() -> anyhow::Result<()> {
3032#[tokio::test(flavor = "multi_thread")]
3133async fn test_buffer_close_concurrent() -> anyhow::Result<()> {
3234 test_key_sequences(
33− &mut Application::new(Args::default(), Config::default())?,
35+ &mut helpers::AppBuilder::new().build()?,
3436 vec![
3537 (
3638 None,
@@ -70,8 +72,12 @@ async fn test_buffer_close_concurrent() -> anyhow::Result<()> {
7072
7173 command.push_str(":buffer<minus>close<ret>");
7274
75+ let mut app = helpers::AppBuilder::new()
76+ .with_file(file.path(), None)
77+ .build()?;
78+
7379 test_key_sequence(
74− &mut helpers::app_with_file(file.path())?,
80+ &mut app,
7581 Some(&command),
7682 Some(&|app| {
7783 assert!(!app.editor.is_err(), "error: {:?}", app.editor.get_status());
helix-term/tests/test/helpers.rs+77−13
@@ -108,7 +108,7 @@ pub async fn test_key_sequence_with_input_text<T: Into<TestCase>>(
108108 let test_case = test_case.into();
109109 let mut app = match app {
110110 Some(app) => app,
111− None => Application::new(Args::default(), Config::default())?,
111+ None => Application::new(Args::default(), Config::default(), test_syntax_conf(None))?,
112112 };
113113
114114 let (view, doc) = helix_view::current!(app.editor);
@@ -132,16 +132,30 @@ pub async fn test_key_sequence_with_input_text<T: Into<TestCase>>(
132132 .await
133133}
134134
135+/// Generates language configs that merge in overrides, like a user language
136+/// config. The argument string must be a raw TOML document.
137+pub fn test_syntax_conf(overrides: Option<String>) -> helix_core::syntax::Configuration {
138+ let mut lang = helix_loader::config::default_lang_config();
139+
140+ if let Some(overrides) = overrides {
141+ let override_toml = toml::from_str(&overrides).unwrap();
142+ lang = helix_loader::merge_toml_values(lang, override_toml, 3);
143+ }
144+
145+ lang.try_into().unwrap()
146+}
147+
135148/// Use this for very simple test cases where there is one input
136149/// document, selection, and sequence of key presses, and you just
137150/// want to verify the resulting document and selection.
138151pub async fn test_with_config<T: Into<TestCase>>(
139152 args: Args,
140153 config: Config,
154+ syn_conf: helix_core::syntax::Configuration,
141155 test_case: T,
142156) -> anyhow::Result<()> {
143157 let test_case = test_case.into();
144− let app = Application::new(args, config)?;
158+ let app = Application::new(args, config, syn_conf)?;
145159
146160 test_key_sequence_with_input_text(
147161 Some(app),
@@ -162,7 +176,13 @@ pub async fn test_with_config<T: Into<TestCase>>(
162176}
163177
164178pub async fn test<T: Into<TestCase>>(test_case: T) -> anyhow::Result<()> {
165− test_with_config(Args::default(), Config::default(), test_case).await
179+ test_with_config(
180+ Args::default(),
181+ Config::default(),
182+ test_syntax_conf(None),
183+ test_case,
184+ )
185+ .await
166186}
167187
168188pub fn temp_file_with_contents<S: AsRef<str>>(
@@ -207,16 +227,60 @@ pub fn new_readonly_tempfile() -> anyhow::Result<NamedTempFile> {
207227 Ok(file)
208228}
209229
210−/// Creates a new Application with default config that opens the given file
211−/// path
212−pub fn app_with_file<P: Into<PathBuf>>(path: P) -> anyhow::Result<Application> {
213− Application::new(
214− Args {
215− files: vec![(path.into(), helix_core::Position::default())],
216− ..Default::default()
217− },
218− Config::default(),
219− )
230+#[derive(Default)]
231+pub struct AppBuilder {
232+ args: Args,
233+ config: Config,
234+ syn_conf: helix_core::syntax::Configuration,
235+ input: Option<(String, Selection)>,
236+}
237+
238+impl AppBuilder {
239+ pub fn new() -> Self {
240+ AppBuilder::default()
241+ }
242+
243+ pub fn with_file<P: Into<PathBuf>>(
244+ mut self,
245+ path: P,
246+ pos: Option<helix_core::Position>,
247+ ) -> Self {
248+ self.args.files.push((path.into(), pos.unwrap_or_default()));
249+ self
250+ }
251+
252+ pub fn with_config(mut self, config: Config) -> Self {
253+ self.config = config;
254+ self
255+ }
256+
257+ pub fn with_input_text<S: Into<String>>(mut self, input_text: S) -> Self {
258+ self.input = Some(test::print(&input_text.into()));
259+ self
260+ }
261+
262+ pub fn with_lang_config(mut self, syn_conf: helix_core::syntax::Configuration) -> Self {
263+ self.syn_conf = syn_conf;
264+ self
265+ }
266+
267+ pub fn build(self) -> anyhow::Result<Application> {
268+ let mut app = Application::new(self.args, self.config, self.syn_conf)?;
269+
270+ if let Some((text, selection)) = self.input {
271+ let (view, doc) = helix_view::current!(app.editor);
272+ let sel = doc.selection(view.id).clone();
273+ let trans = Transaction::change_by_selection(doc.text(), &sel, |_| {
274+ (0, doc.text().len_chars(), Some((text.clone()).into()))
275+ })
276+ .with_selection(selection);
277+
278+ // replace the initial text with the input text
279+ doc.apply(&trans, view.id);
280+ }
281+
282+ Ok(app)
283+ }
220284}
221285
222286pub fn assert_file_has_content(file: &mut File, content: &str) -> anyhow::Result<()> {
helix-term/tests/test/movement.rs+3−1
@@ -70,7 +70,9 @@ async fn insert_to_normal_mode_cursor_position() -> anyhow::Result<()> {
7070async fn cursor_position_newly_opened_file() -> anyhow::Result<()> {
7171 let test = |content: &str, expected_sel: Selection| -> anyhow::Result<()> {
7272 let file = helpers::temp_file_with_contents(content)?;
73− let mut app = helpers::app_with_file(file.path())?;
73+ let mut app = helpers::AppBuilder::new()
74+ .with_file(file.path(), None)
75+ .build()?;
7476
7577 let (view, doc) = helix_view::current!(app.editor);
7678 let sel = doc.selection(view.id).clone();
helix-term/tests/test/prompt.rs+1−3
@@ -1,11 +1,9 @@
11use super::*;
22
3−use helix_term::application::Application;
4−
53#[tokio::test]
64async fn test_history_completion() -> anyhow::Result<()> {
75 test_key_sequence(
8− &mut Application::new(Args::default(), Config::default())?,
6+ &mut AppBuilder::new().build()?,
97 Some(":asdf<ret>:theme d<C-n><tab>"),
108 Some(&|app| {
119 assert!(!app.editor.is_err());
helix-term/tests/test/splits.rs+9−2
@@ -6,8 +6,12 @@ async fn test_split_write_quit_all() -> anyhow::Result<()> {
66 let mut file2 = tempfile::NamedTempFile::new()?;
77 let mut file3 = tempfile::NamedTempFile::new()?;
88
9+ let mut app = helpers::AppBuilder::new()
10+ .with_file(file1.path(), None)
11+ .build()?;
12+
913 test_key_sequences(
10− &mut helpers::app_with_file(file1.path())?,
14+ &mut app,
1115 vec![
1216 (
1317 Some(&format!(
@@ -66,9 +70,12 @@ async fn test_split_write_quit_all() -> anyhow::Result<()> {
6670#[tokio::test(flavor = "multi_thread")]
6771async fn test_split_write_quit_same_file() -> anyhow::Result<()> {
6872 let mut file = tempfile::NamedTempFile::new()?;
73+ let mut app = helpers::AppBuilder::new()
74+ .with_file(file.path(), None)
75+ .build()?;
6976
7077 test_key_sequences(
71− &mut helpers::app_with_file(file.path())?,
78+ &mut app,
7279 vec![
7380 (
7481 Some("O<esc>ihello<esc>:sp<ret>ogoodbye<esc>"),
helix-term/tests/test/write.rs+46−20
@@ -4,7 +4,6 @@ use std::{
44};
55
66use helix_core::diagnostic::Severity;
7−use helix_term::application::Application;
87use helix_view::doc;
98
109use super::*;
@@ -12,9 +11,12 @@ use super::*;
1211#[tokio::test]
1312async fn test_write() -> anyhow::Result<()> {
1413 let mut file = tempfile::NamedTempFile::new()?;
14+ let mut app = helpers::AppBuilder::new()
15+ .with_file(file.path(), None)
16+ .build()?;
1517
1618 test_key_sequence(
17− &mut helpers::app_with_file(file.path())?,
19+ &mut app,
1820 Some("ithe gostak distims the doshes<ret><esc>:w<ret>"),
1921 None,
2022 false,
@@ -38,9 +40,12 @@ async fn test_write() -> anyhow::Result<()> {
3840#[tokio::test(flavor = "multi_thread")]
3941async fn test_write_quit() -> anyhow::Result<()> {
4042 let mut file = tempfile::NamedTempFile::new()?;
43+ let mut app = helpers::AppBuilder::new()
44+ .with_file(file.path(), None)
45+ .build()?;
4146
4247 test_key_sequence(
43− &mut helpers::app_with_file(file.path())?,
48+ &mut app,
4449 Some("ithe gostak distims the doshes<ret><esc>:wq<ret>"),
4550 None,
4651 true,
@@ -66,19 +71,16 @@ async fn test_write_concurrent() -> anyhow::Result<()> {
6671 let mut file = tempfile::NamedTempFile::new()?;
6772 let mut command = String::new();
6873 const RANGE: RangeInclusive<i32> = 1..=5000;
74+ let mut app = helpers::AppBuilder::new()
75+ .with_file(file.path(), None)
76+ .build()?;
6977
7078 for i in RANGE {
7179 let cmd = format!("%c{}<esc>:w<ret>", i);
7280 command.push_str(&cmd);
7381 }
7482
75− test_key_sequence(
76− &mut helpers::app_with_file(file.path())?,
77− Some(&command),
78− None,
79− false,
80− )
81− .await?;
83+ test_key_sequence(&mut app, Some(&command), None, false).await?;
8284
8385 file.as_file_mut().flush()?;
8486 file.as_file_mut().sync_all()?;
@@ -93,9 +95,12 @@ async fn test_write_concurrent() -> anyhow::Result<()> {
9395#[tokio::test]
9496async fn test_write_fail_mod_flag() -> anyhow::Result<()> {
9597 let file = helpers::new_readonly_tempfile()?;
98+ let mut app = helpers::AppBuilder::new()
99+ .with_file(file.path(), None)
100+ .build()?;
96101
97102 test_key_sequences(
98− &mut helpers::app_with_file(file.path())?,
103+ &mut app,
99104 vec![
100105 (
101106 None,
@@ -133,7 +138,7 @@ async fn test_write_scratch_to_new_path() -> anyhow::Result<()> {
133138 let mut file = tempfile::NamedTempFile::new()?;
134139
135140 test_key_sequence(
136− &mut Application::new(Args::default(), Config::default())?,
141+ &mut AppBuilder::new().build()?,
137142 Some(format!("ihello<esc>:w {}<ret>", file.path().to_string_lossy()).as_ref()),
138143 Some(&|app| {
139144 assert!(!app.editor.is_err());
@@ -174,19 +179,40 @@ async fn test_write_scratch_no_path_fails() -> anyhow::Result<()> {
174179 Ok(())
175180}
176181
182+#[tokio::test]
183+async fn test_write_auto_format_fails_still_writes() -> anyhow::Result<()> {
184+ let mut file = tempfile::Builder::new().suffix(".rs").tempfile()?;
185+
186+ let lang_conf = indoc! {r#"
187+ [[language]]
188+ name = "rust"
189+ formatter = { command = "bash", args = [ "-c", "exit 1" ] }
190+ "#};
191+
192+ let mut app = helpers::AppBuilder::new()
193+ .with_file(file.path(), None)
194+ .with_input_text("#[l|]#et foo = 0;\n")
195+ .with_lang_config(helpers::test_syntax_conf(Some(lang_conf.into())))
196+ .build()?;
197+
198+ test_key_sequences(&mut app, vec![(Some(":w<ret>"), None)], false).await?;
199+
200+ // file still saves
201+ helpers::assert_file_has_content(file.as_file_mut(), "let foo = 0;\n")?;
202+
203+ Ok(())
204+}
205+
177206#[tokio::test]
178207async fn test_write_new_path() -> anyhow::Result<()> {
179208 let mut file1 = tempfile::NamedTempFile::new().unwrap();
180209 let mut file2 = tempfile::NamedTempFile::new().unwrap();
210+ let mut app = helpers::AppBuilder::new()
211+ .with_file(file1.path(), None)
212+ .build()?;
181213
182214 test_key_sequences(
183− &mut Application::new(
184− Args {
185− files: vec![(file1.path().to_path_buf(), Position::default())],
186− ..Default::default()
187− },
188− Config::default(),
189− )?,
215+ &mut app,
190216 vec![
191217 (
192218 Some("ii can eat glass, it will not hurt me<ret><esc>:w<ret>"),
@@ -228,7 +254,7 @@ async fn test_write_fail_new_path() -> anyhow::Result<()> {
228254 let file = helpers::new_readonly_tempfile()?;
229255
230256 test_key_sequences(
231− &mut Application::new(Args::default(), Config::default())?,
257+ &mut AppBuilder::new().build()?,
232258 vec![
233259 (
234260 None,