on master help sign in
Fix expansion of `~` (#284)

* Fix expansion of `~`, dont use directory relative to cwd. * Add `expand_tilde` * Bring back `canonicalize_path`, use `expand_tilde` to `normalize` * Make `:open ~` completion work * Fix clippy * Fold home dir into tilde in Document `realitve_path`

commit41b07486ad935ad820dd4ba210457a03c95e1145 authorWojciech Kępka <46892771+wojciechkepka@users.noreply.github.com> dateFri 18 Jun 2021, 08:19 (5 years ago) parent42142cf
4 files changed+71−16
helix-core/src/lib.rs+2 helix-term/src/commands.rs+3−3 helix-term/src/ui/mod.rs+14−4 helix-view/src/document.rs+52−9
helix-core/src/lib.rs+2
@@ -89,6 +89,8 @@ pub fn cache_dir() -> std::path::PathBuf {
8989 path
9090}
9191
92+pub use etcetera::home_dir;
93+
9294use etcetera::base_strategy::{choose_base_strategy, BaseStrategy};
9395
9496pub use ropey::{Rope, RopeSlice};
helix-term/src/commands.rs+3−3
@@ -1188,8 +1188,8 @@ mod cmd {
11881188 .filter(|doc| doc.is_modified())
11891189 .map(|doc| {
11901190 doc.relative_path()
1191− .and_then(|path| path.to_str())
1192− .unwrap_or("[scratch]")
1191+ .map(|path| path.to_string_lossy().to_string())
1192+ .unwrap_or_else(|| "[scratch]".into())
11931193 })
11941194 .collect();
11951195 if !modified.is_empty() {
@@ -1487,7 +1487,7 @@ fn buffer_picker(cx: &mut Context) {
14871487 cx.editor
14881488 .documents
14891489 .iter()
1490− .map(|(id, doc)| (id, doc.relative_path().map(Path::to_path_buf)))
1490+ .map(|(id, doc)| (id, doc.relative_path()))
14911491 .collect(),
14921492 move |(id, path): &(DocumentId, Option<PathBuf>)| {
14931493 // format_fn
helix-term/src/ui/mod.rs+14−4
@@ -126,10 +126,11 @@ pub mod completers {
126126 use ignore::WalkBuilder;
127127 use std::path::{Path, PathBuf};
128128
129− let path = Path::new(input);
129+ let is_tilde = input.starts_with('~') && input.len() == 1;
130+ let path = helix_view::document::expand_tilde(Path::new(input));
130131
131132 let (dir, file_name) = if input.ends_with('/') {
132− (path.into(), None)
133+ (path, None)
133134 } else {
134135 let file_name = path
135136 .file_name()
@@ -154,7 +155,16 @@ pub mod completers {
154155 let is_dir = entry.file_type().map_or(false, |entry| entry.is_dir());
155156
156157 let path = entry.path();
157− let mut path = path.strip_prefix(&dir).unwrap_or(path).to_path_buf();
158+ let mut path = if is_tilde {
159+ // if it's a single tilde an absolute path is displayed so that when `TAB` is pressed on
160+ // one of the directories the tilde will be replaced with a valid path not with a relative
161+ // home directory name.
162+ // ~ -> <TAB> -> /home/user
163+ // ~/ -> <TAB> -> ~/first_entry
164+ path.to_path_buf()
165+ } else {
166+ path.strip_prefix(&dir).unwrap_or(path).to_path_buf()
167+ };
158168
159169 if is_dir {
160170 path.push("");
@@ -184,7 +194,7 @@ pub mod completers {
184194 })
185195 .collect();
186196
187− let range = ((input.len() - file_name.len())..);
197+ let range = ((input.len().saturating_sub(file_name.len()))..);
188198
189199 matches.sort_unstable_by_key(|(_file, score)| Reverse(*score));
190200 files = matches
helix-view/src/document.rs+52−9
@@ -127,6 +127,36 @@ where
127127 }
128128}
129129
130+/// Expands tilde `~` into users home directory if avilable, otherwise returns the path
131+/// unchanged. The tilde will only be expanded when present as the first component of the path
132+/// and only slash follows it.
133+pub fn expand_tilde(path: &Path) -> PathBuf {
134+ let mut components = path.components().peekable();
135+ if let Some(Component::Normal(c)) = components.peek() {
136+ if c == &"~" {
137+ if let Ok(home) = helix_core::home_dir() {
138+ // it's ok to unwrap, the path starts with `~`
139+ return home.join(path.strip_prefix("~").unwrap());
140+ }
141+ }
142+ }
143+
144+ path.to_path_buf()
145+}
146+
147+/// Replaces users home directory from `path` with tilde `~` if the directory
148+/// is available, otherwise returns the path unchanged.
149+pub fn fold_home_dir(path: &Path) -> PathBuf {
150+ if let Ok(home) = helix_core::home_dir() {
151+ if path.starts_with(&home) {
152+ // it's ok to unwrap, the path starts with home dir
153+ return PathBuf::from("~").join(path.strip_prefix(&home).unwrap());
154+ }
155+ }
156+
157+ path.to_path_buf()
158+}
159+
130160/// Normalize a path, removing things like `.` and `..`.
131161///
132162/// CAUTION: This does not resolve symlinks (unlike
@@ -137,6 +167,7 @@ where
137167/// needs to improve on.
138168/// Copied from cargo: https://github.com/rust-lang/cargo/blob/070e459c2d8b79c5b2ac5218064e7603329c92ae/crates/cargo-util/src/paths.rs#L81
139169pub fn normalize_path(path: &Path) -> PathBuf {
170+ let path = expand_tilde(path);
140171 let mut components = path.components().peekable();
141172 let mut ret = if let Some(c @ Component::Prefix(..)) = components.peek().cloned() {
142173 components.next();
@@ -163,12 +194,17 @@ pub fn normalize_path(path: &Path) -> PathBuf {
163194 ret
164195}
165196
166−// Returns the canonical, absolute form of a path with all intermediate components normalized.
167−//
168−// This function is used instead of `std::fs::canonicalize` because we don't want to verify
169−// here if the path exists, just normalize it's components.
197+/// Returns the canonical, absolute form of a path with all intermediate components normalized.
198+///
199+/// This function is used instead of `std::fs::canonicalize` because we don't want to verify
200+/// here if the path exists, just normalize it's components.
170201pub fn canonicalize_path(path: &Path) -> std::io::Result<PathBuf> {
171− std::env::current_dir().map(|current_dir| normalize_path(&current_dir.join(path)))
202+ let normalized = normalize_path(path);
203+ if normalized.is_absolute() {
204+ Ok(normalized)
205+ } else {
206+ std::env::current_dir().map(|current_dir| current_dir.join(normalized))
207+ }
172208}
173209
174210use helix_lsp::lsp;
@@ -709,12 +745,19 @@ impl Document {
709745 &self.selections[&view_id]
710746 }
711747
712− pub fn relative_path(&self) -> Option<&Path> {
748+ pub fn relative_path(&self) -> Option<PathBuf> {
713749 let cwdir = std::env::current_dir().expect("couldn't determine current directory");
714750
715− self.path
716− .as_ref()
717− .map(|path| path.strip_prefix(cwdir).unwrap_or(path))
751+ self.path.as_ref().map(|path| {
752+ let path = fold_home_dir(path);
753+ if path.is_relative() {
754+ path
755+ } else {
756+ path.strip_prefix(cwdir)
757+ .map(|p| p.to_path_buf())
758+ .unwrap_or(path)
759+ }
760+ })
718761 }
719762
720763 // pub fn slice<R>(&self, range: R) -> RopeSlice where R: RangeBounds {