on master help sign in
Merge branch 'master' into great_line_ending_and_cursor_range_cleanup
e462f32Nathan Vegdahl
helix-core/src/comment.rs+5−5
@@ -38,18 +38,18 @@ fn find_line_comment(
38}
38}
39
39
40#[must_use]
40#[must_use]
41−pub fn toggle_line_comments(doc: &Rope, selection: &Selection) -> Transaction {
41+pub fn toggle_line_comments(doc: &Rope, selection: &Selection, token: Option<&str>) -> Transaction {
42 let text = doc.slice(..);
42 let text = doc.slice(..);
43 let mut changes: Vec<Change> = Vec::new();
43 let mut changes: Vec<Change> = Vec::new();
44
44
45− let token = "//";
45+ let token = token.unwrap_or("//");
46 let comment = Tendril::from(format!("{} ", token));
46 let comment = Tendril::from(format!("{} ", token));
47
47
48 for selection in selection {
48 for selection in selection {
49 let start = text.char_to_line(selection.from());
49 let start = text.char_to_line(selection.from());
50 let end = text.char_to_line(selection.to());
50 let end = text.char_to_line(selection.to());
51 let lines = start..end + 1;
51 let lines = start..end + 1;
52− let (commented, skipped, min) = find_line_comment(token, text, lines.clone());
52+ let (commented, skipped, min) = find_line_comment(&token, text, lines.clone());
53
53
54 changes.reserve((end - start).saturating_sub(skipped.len()));
54 changes.reserve((end - start).saturating_sub(skipped.len()));
55
55
@@ -95,14 +95,14 @@ mod test {
95 assert_eq!(res, (false, vec![1], 2));
95 assert_eq!(res, (false, vec![1], 2));
96
96
97 // comment
97 // comment
98− let transaction = toggle_line_comments(&state.doc, &state.selection);
98+ let transaction = toggle_line_comments(&state.doc, &state.selection, None);
99 transaction.apply(&mut state.doc);
99 transaction.apply(&mut state.doc);
100 state.selection = state.selection.clone().map(transaction.changes());
100 state.selection = state.selection.clone().map(transaction.changes());
101
101
102 assert_eq!(state.doc, " // 1\n\n // 2\n // 3");
102 assert_eq!(state.doc, " // 1\n\n // 2\n // 3");
103
103
104 // uncomment
104 // uncomment
105− let transaction = toggle_line_comments(&state.doc, &state.selection);
105+ let transaction = toggle_line_comments(&state.doc, &state.selection, None);
106 transaction.apply(&mut state.doc);
106 transaction.apply(&mut state.doc);
107 state.selection = state.selection.clone().map(transaction.changes());
107 state.selection = state.selection.clone().map(transaction.changes());
108 assert_eq!(state.doc, " 1\n\n 2\n 3");
108 assert_eq!(state.doc, " 1\n\n 2\n 3");
helix-core/src/diff.rs+27−29
@@ -1,6 +1,4 @@
1−use ropey::Rope;
2−
3−use crate::{Change, Transaction};
1+use crate::{Rope, Transaction};
4
2
5/// Compares `old` and `new` to generate a [`Transaction`] describing
3/// Compares `old` and `new` to generate a [`Transaction`] describing
6/// the steps required to get from `old` to `new`.
4/// the steps required to get from `old` to `new`.
@@ -25,34 +23,34 @@ pub fn compare_ropes(old: &Rope, new: &Rope) -> Transaction {
25 // The current position of the change needs to be tracked to
23 // The current position of the change needs to be tracked to
26 // construct the `Change`s.
24 // construct the `Change`s.
27 let mut pos = 0;
25 let mut pos = 0;
28− let changes: Vec<Change> = diff
26+ Transaction::change(
27+ old,
29− .ops()
28+ diff.ops()
30− .iter()
29+ .iter()
31− .map(|op| op.as_tag_tuple())
30+ .map(|op| op.as_tag_tuple())
32− .filter_map(|(tag, old_range, new_range)| {
31+ .filter_map(|(tag, old_range, new_range)| {
33− // `old_pos..pos` is equivalent to `start..end` for where
32+ // `old_pos..pos` is equivalent to `start..end` for where
34− // the change should be applied.
33+ // the change should be applied.
35− let old_pos = pos;
34+ let old_pos = pos;
36− pos += old_range.end - old_range.start;
35+ pos += old_range.end - old_range.start;
37
36
38− match tag {
37+ match tag {
39− // Semantically, inserts and replacements are the same thing.
38+ // Semantically, inserts and replacements are the same thing.
40− similar::DiffTag::Insert | similar::DiffTag::Replace => {
39+ similar::DiffTag::Insert | similar::DiffTag::Replace => {
41− // This is the text from the `new` rope that should be
40+ // This is the text from the `new` rope that should be
42− // inserted into `old`.
41+ // inserted into `old`.
43− let text: &str = {
42+ let text: &str = {
44− let start = new.char_to_byte(new_range.start);
43+ let start = new.char_to_byte(new_range.start);
45− let end = new.char_to_byte(new_range.end);
44+ let end = new.char_to_byte(new_range.end);
46− &new_converted[start..end]
45+ &new_converted[start..end]
47− };
46+ };
48− Some((old_pos, pos, Some(text.into())))
47+ Some((old_pos, pos, Some(text.into())))
48+ }
49+ similar::DiffTag::Delete => Some((old_pos, pos, None)),
50+ similar::DiffTag::Equal => None,
49 }
51 }
50− similar::DiffTag::Delete => Some((old_pos, pos, None)),
51− similar::DiffTag::Equal => None,
52− }
52+ }),
53− })
53+ )
54− .collect();
55− Transaction::change(old, changes.into_iter())
56}
54}
57
55
58#[cfg(test)]
56#[cfg(test)]
helix-core/src/indent.rs+2
@@ -262,8 +262,10 @@ where
262 file_types: vec!["rs".to_string()],
262 file_types: vec!["rs".to_string()],
263 language_id: "Rust".to_string(),
263 language_id: "Rust".to_string(),
264 highlight_config: OnceCell::new(),
264 highlight_config: OnceCell::new(),
265+ config: None,
265 //
266 //
266 roots: vec![],
267 roots: vec![],
268+ comment_token: None,
267 auto_format: false,
269 auto_format: false,
268 language_server: None,
270 language_server: None,
269 indent: Some(IndentationConfiguration {
271 indent: Some(IndentationConfiguration {
helix-core/src/syntax.rs+2
@@ -35,6 +35,8 @@ pub struct LanguageConfiguration {
35 pub scope: String, // source.rust
35 pub scope: String, // source.rust
36 pub file_types: Vec<String>, // filename ends_with? <Gemfile, rb, etc>
36 pub file_types: Vec<String>, // filename ends_with? <Gemfile, rb, etc>
37 pub roots: Vec<String>, // these indicate project roots <.git, Cargo.toml>
37 pub roots: Vec<String>, // these indicate project roots <.git, Cargo.toml>
38+ pub comment_token: Option<String>,
39+ pub config: Option<String>,
38
40
39 #[serde(default)]
41 #[serde(default)]
40 pub auto_format: bool,
42 pub auto_format: bool,
helix-core/src/transaction.rs+4−2
@@ -473,11 +473,13 @@ impl Transaction {
473 /// Generate a transaction from a set of changes.
473 /// Generate a transaction from a set of changes.
474 pub fn change<I>(doc: &Rope, changes: I) -> Self
474 pub fn change<I>(doc: &Rope, changes: I) -> Self
475 where
475 where
476− I: IntoIterator<Item = Change> + ExactSizeIterator,
476+ I: IntoIterator<Item = Change> + Iterator,
477 {
477 {
478 let len = doc.len_chars();
478 let len = doc.len_chars();
479
479
480+ let (lower, upper) = changes.size_hint();
481+ let size = upper.unwrap_or(lower);
480− let mut changeset = ChangeSet::with_capacity(2 * changes.len() + 1); // rough estimate
482+ let mut changeset = ChangeSet::with_capacity(2 * size + 1); // rough estimate
481
483
482 // TODO: verify ranges are ordered and not overlapping or change will panic.
484 // TODO: verify ranges are ordered and not overlapping or change will panic.
483
485
helix-lsp/src/client.rs+8−1
@@ -24,12 +24,14 @@ pub struct Client {
24 request_counter: AtomicU64,
24 request_counter: AtomicU64,
25 capabilities: Option<lsp::ServerCapabilities>,
25 capabilities: Option<lsp::ServerCapabilities>,
26 offset_encoding: OffsetEncoding,
26 offset_encoding: OffsetEncoding,
27+ config: Option<Value>,
27}
28}
28
29
29impl Client {
30impl Client {
30 pub fn start(
31 pub fn start(
31 cmd: &str,
32 cmd: &str,
32 args: &[String],
33 args: &[String],
34+ config: Option<Value>,
33 id: usize,
35 id: usize,
34 ) -> Result<(Self, UnboundedReceiver<(usize, Call)>)> {
36 ) -> Result<(Self, UnboundedReceiver<(usize, Call)>)> {
35 let process = Command::new(cmd)
37 let process = Command::new(cmd)
@@ -57,6 +59,7 @@ impl Client {
57 request_counter: AtomicU64::new(0),
59 request_counter: AtomicU64::new(0),
58 capabilities: None,
60 capabilities: None,
59 offset_encoding: OffsetEncoding::Utf8,
61 offset_encoding: OffsetEncoding::Utf8,
62+ config,
60 };
63 };
61
64
62 // TODO: async client.initialize()
65 // TODO: async client.initialize()
@@ -214,13 +217,17 @@ impl Client {
214 // TODO: delay any requests that are triggered prior to initialize
217 // TODO: delay any requests that are triggered prior to initialize
215 let root = find_root(None).and_then(|root| lsp::Url::from_file_path(root).ok());
218 let root = find_root(None).and_then(|root| lsp::Url::from_file_path(root).ok());
216
219
220+ if self.config.is_some() {
221+ log::info!("Using custom LSP config: {}", self.config.as_ref().unwrap());
222+ }
223+
217 #[allow(deprecated)]
224 #[allow(deprecated)]
218 let params = lsp::InitializeParams {
225 let params = lsp::InitializeParams {
219 process_id: Some(std::process::id()),
226 process_id: Some(std::process::id()),
220 // root_path is obsolete, use root_uri
227 // root_path is obsolete, use root_uri
221 root_path: None,
228 root_path: None,
222 root_uri: root,
229 root_uri: root,
223− initialization_options: None,
230+ initialization_options: self.config.clone(),
224 capabilities: lsp::ClientCapabilities {
231 capabilities: lsp::ClientCapabilities {
225 text_document: Some(lsp::TextDocumentClientCapabilities {
232 text_document: Some(lsp::TextDocumentClientCapabilities {
226 completion: Some(lsp::CompletionClientCapabilities {
233 completion: Some(lsp::CompletionClientCapabilities {
helix-lsp/src/lib.rs+6−1
@@ -312,7 +312,12 @@ impl Registry {
312 Entry::Vacant(entry) => {
312 Entry::Vacant(entry) => {
313 // initialize a new client
313 // initialize a new client
314 let id = self.counter.fetch_add(1, Ordering::Relaxed);
314 let id = self.counter.fetch_add(1, Ordering::Relaxed);
315− let (mut client, incoming) = Client::start(&config.command, &config.args, id)?;
315+ let (mut client, incoming) = Client::start(
316+ &config.command,
317+ &config.args,
318+ serde_json::from_str(language_config.config.as_deref().unwrap_or("")).ok(),
319+ id,
320+ )?;
316 // TODO: run this async without blocking
321 // TODO: run this async without blocking
317 futures_executor::block_on(client.initialize())?;
322 futures_executor::block_on(client.initialize())?;
318 s_incoming.push(UnboundedReceiverStream::new(incoming));
323 s_incoming.push(UnboundedReceiverStream::new(incoming));
helix-term/src/commands.rs+5−1
@@ -3499,7 +3499,11 @@ fn hover(cx: &mut Context) {
3499// comments
3499// comments
3500fn toggle_comments(cx: &mut Context) {
3500fn toggle_comments(cx: &mut Context) {
3501 let (view, doc) = current!(cx.editor);
3501 let (view, doc) = current!(cx.editor);
3502+ let token = doc
3503+ .language_config()
3504+ .and_then(|lc| lc.comment_token.as_ref())
3505+ .map(|tc| tc.as_ref());
3502− let transaction = comment::toggle_line_comments(doc.text(), doc.selection(view.id));
3506+ let transaction = comment::toggle_line_comments(doc.text(), doc.selection(view.id), token);
3503
3507
3504 doc.apply(&transaction, view.id);
3508 doc.apply(&transaction, view.id);
3505 doc.append_changes_to_history(view.id);
3509 doc.append_changes_to_history(view.id);
helix-term/src/ui/menu.rs+31−3
@@ -8,6 +8,7 @@ use fuzzy_matcher::skim::SkimMatcherV2 as Matcher;
8use fuzzy_matcher::FuzzyMatcher;
8use fuzzy_matcher::FuzzyMatcher;
9
9
10use helix_view::{graphics::Rect, Editor};
10use helix_view::{graphics::Rect, Editor};
11+use tui::layout::Constraint;
11
12
12pub trait Item {
13pub trait Item {
13 // TODO: sort_text
14 // TODO: sort_text
@@ -26,6 +27,8 @@ pub struct Menu<T: Item> {
26 /// (index, score)
27 /// (index, score)
27 matches: Vec<(usize, i64)>,
28 matches: Vec<(usize, i64)>,
28
29
30+ widths: Vec<Constraint>,
31+
29 callback_fn: Box<dyn Fn(&mut Editor, Option<&T>, MenuEvent)>,
32 callback_fn: Box<dyn Fn(&mut Editor, Option<&T>, MenuEvent)>,
30
33
31 scroll: usize,
34 scroll: usize,
@@ -44,6 +47,7 @@ impl<T: Item> Menu<T> {
44 matcher: Box::new(Matcher::default()),
47 matcher: Box::new(Matcher::default()),
45 matches: Vec::new(),
48 matches: Vec::new(),
46 cursor: None,
49 cursor: None,
50+ widths: Vec::new(),
47 callback_fn: Box::new(callback_fn),
51 callback_fn: Box::new(callback_fn),
48 scroll: 0,
52 scroll: 0,
49 size: (0, 0),
53 size: (0, 0),
@@ -218,8 +222,33 @@ impl<T: Item + 'static> Component for Menu<T> {
218 EventResult::Ignored
222 EventResult::Ignored
219 }
223 }
220
224
225+ // TODO: completion sorting
226+
221 fn required_size(&mut self, viewport: (u16, u16)) -> Option<(u16, u16)> {
227 fn required_size(&mut self, viewport: (u16, u16)) -> Option<(u16, u16)> {
228+ let n = self
229+ .options
230+ .first()
231+ .map(|option| option.row().cells.len())
232+ .unwrap_or_default();
233+ let max_lens = self.options.iter().fold(vec![0; n], |mut acc, option| {
234+ let row = option.row();
235+ // maintain max for each column
236+ for (i, cell) in row.cells.iter().enumerate() {
237+ let width = cell.content.width();
238+ if width > acc[i] {
239+ acc[i] = width;
240+ }
241+ }
242+
243+ acc
244+ });
245+ let len = (max_lens.iter().sum::<usize>()) + n + 1; // +1: reserve some space for scrollbar
222− let width = std::cmp::min(30, viewport.0);
246+ let width = len.min(viewport.0 as usize);
247+
248+ self.widths = max_lens
249+ .into_iter()
250+ .map(|len| Constraint::Length(len as u16))
251+ .collect();
223
252
224 const MAX: usize = 10;
253 const MAX: usize = 10;
225 let height = std::cmp::min(self.options.len(), MAX);
254 let height = std::cmp::min(self.options.len(), MAX);
@@ -263,13 +292,12 @@ impl<T: Item + 'static> Component for Menu<T> {
263 let scroll_line = (win_height - scroll_height) * scroll
292 let scroll_line = (win_height - scroll_height) * scroll
264 / std::cmp::max(1, len.saturating_sub(win_height));
293 / std::cmp::max(1, len.saturating_sub(win_height));
265
294
266− use tui::layout::Constraint;
267 let rows = options.iter().map(|option| option.row());
295 let rows = options.iter().map(|option| option.row());
268 let table = Table::new(rows)
296 let table = Table::new(rows)
269 .style(style)
297 .style(style)
270 .highlight_style(selected)
298 .highlight_style(selected)
271 .column_spacing(1)
299 .column_spacing(1)
272− .widths(&[Constraint::Percentage(50), Constraint::Percentage(50)]);
300+ .widths(&self.widths);
273
301
274 use tui::widgets::TableState;
302 use tui::widgets::TableState;
275
303
helix-tui/src/widgets/table.rs+2−2
@@ -36,7 +36,7 @@ use std::collections::HashMap;
36/// capabilities of [`Text`].
36/// capabilities of [`Text`].
37#[derive(Debug, Clone, PartialEq, Default)]
37#[derive(Debug, Clone, PartialEq, Default)]
38pub struct Cell<'a> {
38pub struct Cell<'a> {
39− content: Text<'a>,
39+ pub content: Text<'a>,
40 style: Style,
40 style: Style,
41}
41}
42
42
@@ -81,7 +81,7 @@ where
81/// By default, a row has a height of 1 but you can change this using [`Row::height`].
81/// By default, a row has a height of 1 but you can change this using [`Row::height`].
82#[derive(Debug, Clone, PartialEq, Default)]
82#[derive(Debug, Clone, PartialEq, Default)]
83pub struct Row<'a> {
83pub struct Row<'a> {
84− cells: Vec<Cell<'a>>,
84+ pub cells: Vec<Cell<'a>>,
85 height: u16,
85 height: u16,
86 style: Style,
86 style: Style,
87 bottom_margin: u16,
87 bottom_margin: u16,
languages.toml+22
@@ -5,6 +5,17 @@ injection-regex = "rust"
5file-types = ["rs"]
5file-types = ["rs"]
6roots = []
6roots = []
7auto-format = true
7auto-format = true
8+comment_token = "//"
9+config = """
10+{
11+ "cargo": {
12+ "loadOutDirsFromCheck": true
13+ },
14+ "procMacro": {
15+ "enable": false
16+ }
17+}
18+"""
8
19
9language-server = { command = "rust-analyzer" }
20language-server = { command = "rust-analyzer" }
10indent = { tab-width = 4, unit = " " }
21indent = { tab-width = 4, unit = " " }
@@ -15,6 +26,7 @@ scope = "source.toml"
15injection-regex = "toml"
26injection-regex = "toml"
16file-types = ["toml"]
27file-types = ["toml"]
17roots = []
28roots = []
29+comment_token = "#"
18
30
19indent = { tab-width = 2, unit = " " }
31indent = { tab-width = 2, unit = " " }
20
32
@@ -42,6 +54,7 @@ scope = "source.c"
42injection-regex = "c"
54injection-regex = "c"
43file-types = ["c"] # TODO: ["h"]
55file-types = ["c"] # TODO: ["h"]
44roots = []
56roots = []
57+comment_token = "//"
45
58
46language-server = { command = "clangd" }
59language-server = { command = "clangd" }
47indent = { tab-width = 2, unit = " " }
60indent = { tab-width = 2, unit = " " }
@@ -52,6 +65,7 @@ scope = "source.cpp"
52injection-regex = "cpp"
65injection-regex = "cpp"
53file-types = ["cc", "cpp", "hpp", "h"]
66file-types = ["cc", "cpp", "hpp", "h"]
54roots = []
67roots = []
68+comment_token = "//"
55
69
56language-server = { command = "clangd" }
70language-server = { command = "clangd" }
57indent = { tab-width = 2, unit = " " }
71indent = { tab-width = 2, unit = " " }
@@ -63,6 +77,7 @@ injection-regex = "go"
63file-types = ["go"]
77file-types = ["go"]
64roots = ["Gopkg.toml", "go.mod"]
78roots = ["Gopkg.toml", "go.mod"]
65auto-format = true
79auto-format = true
80+comment_token = "//"
66
81
67language-server = { command = "gopls" }
82language-server = { command = "gopls" }
68# TODO: gopls needs utf-8 offsets?
83# TODO: gopls needs utf-8 offsets?
@@ -74,6 +89,7 @@ scope = "source.js"
74injection-regex = "^(js|javascript)$"
89injection-regex = "^(js|javascript)$"
75file-types = ["js"]
90file-types = ["js"]
76roots = []
91roots = []
92+comment_token = "//"
77# TODO: highlights-jsx, highlights-params
93# TODO: highlights-jsx, highlights-params
78
94
79indent = { tab-width = 2, unit = " " }
95indent = { tab-width = 2, unit = " " }
@@ -113,6 +129,7 @@ scope = "source.python"
113injection-regex = "python"
129injection-regex = "python"
114file-types = ["py"]
130file-types = ["py"]
115roots = []
131roots = []
132+comment_token = "#"
116
133
117language-server = { command = "pyls" }
134language-server = { command = "pyls" }
118# TODO: pyls needs utf-8 offsets
135# TODO: pyls needs utf-8 offsets
@@ -133,6 +150,7 @@ scope = "source.ruby"
133injection-regex = "ruby"
150injection-regex = "ruby"
134file-types = ["rb"]
151file-types = ["rb"]
135roots = []
152roots = []
153+comment_token = "#"
136
154
137language-server = { command = "solargraph", args = ["stdio"] }
155language-server = { command = "solargraph", args = ["stdio"] }
138indent = { tab-width = 2, unit = " " }
156indent = { tab-width = 2, unit = " " }
@@ -143,6 +161,7 @@ scope = "source.bash"
143injection-regex = "bash"
161injection-regex = "bash"
144file-types = ["sh", "bash"]
162file-types = ["sh", "bash"]
145roots = []
163roots = []
164+comment_token = "#"
146
165
147language-server = { command = "bash-language-server", args = ["start"] }
166language-server = { command = "bash-language-server", args = ["start"] }
148indent = { tab-width = 2, unit = " " }
167indent = { tab-width = 2, unit = " " }
@@ -162,6 +181,7 @@ scope = "source.tex"
162injection-regex = "tex"
181injection-regex = "tex"
163file-types = ["tex"]
182file-types = ["tex"]
164roots = []
183roots = []
184+comment_token = "%"
165
185
166indent = { tab-width = 4, unit = "\t" }
186indent = { tab-width = 4, unit = "\t" }
167
187
@@ -171,6 +191,7 @@ scope = "source.julia"
171injection-regex = "julia"
191injection-regex = "julia"
172file-types = ["jl"]
192file-types = ["jl"]
173roots = []
193roots = []
194+comment_token = "#"
174language-server = { command = "julia", args = [ "--startup-file=no", "--history-file=no", "-e", "using LanguageServer;using Pkg;import StaticLint;import SymbolServer;env_path = dirname(Pkg.Types.Context().env.project_file);server = LanguageServer.LanguageServerInstance(stdin, stdout, env_path, \"\");server.runlinter = true;run(server);" ] }
195language-server = { command = "julia", args = [ "--startup-file=no", "--history-file=no", "-e", "using LanguageServer;using Pkg;import StaticLint;import SymbolServer;env_path = dirname(Pkg.Types.Context().env.project_file);server = LanguageServer.LanguageServerInstance(stdin, stdout, env_path, \"\");server.runlinter = true;run(server);" ] }
175indent = { tab-width = 2, unit = " " }
196indent = { tab-width = 2, unit = " " }
176
197
@@ -180,5 +201,6 @@ indent = { tab-width = 2, unit = " " }
180# injection-regex = "haskell"
201# injection-regex = "haskell"
181# file-types = ["hs"]
202# file-types = ["hs"]
182# roots = []
203# roots = []
204+# comment_token = "--"
183#
205#
184# indent = { tab-width = 2, unit = " " }
206# indent = { tab-width = 2, unit = " " }