Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(commands): open urls with goto_file command #5820

Merged
merged 5 commits into from
Nov 21, 2023
Merged
Show file tree
Hide file tree
Changes from 4 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
38 changes: 38 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

3 changes: 3 additions & 0 deletions helix-term/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,9 @@ ignore = "0.4"
pulldown-cmark = { version = "0.9", default-features = false }
# file type detection
content_inspector = "0.2.4"
# openning URLs
matoous marked this conversation as resolved.
Show resolved Hide resolved
open = "5.0.0"
url = "2.4.1"

# config
toml = "0.7"
Expand Down
76 changes: 71 additions & 5 deletions helix-term/src/commands.rs
Original file line number Diff line number Diff line change
Expand Up @@ -60,8 +60,13 @@ use crate::{

use crate::job::{self, Jobs};
use futures_util::{stream::FuturesUnordered, TryStreamExt};
use std::{collections::HashMap, fmt, future::Future};
use std::{collections::HashSet, num::NonZeroUsize};
use std::{
collections::{HashMap, HashSet},
fmt,
future::Future,
io::Read,
num::NonZeroUsize,
};

use std::{
borrow::Cow,
Expand All @@ -70,6 +75,7 @@ use std::{

use once_cell::sync::Lazy;
use serde::de::{self, Deserialize, Deserializer};
use url::Url;

use grep_regex::RegexMatcherBuilder;
use grep_searcher::{sinks, BinaryDetection, SearcherBuilder};
Expand Down Expand Up @@ -331,7 +337,7 @@ impl MappableCommand {
goto_implementation, "Goto implementation",
goto_file_start, "Goto line number <n> else file start",
goto_file_end, "Goto file end",
goto_file, "Goto files in selection",
goto_file, "Goto files/URLs in selection",
goto_file_hsplit, "Goto files in selection (hsplit)",
goto_file_vsplit, "Goto files in selection (vsplit)",
goto_reference, "Goto references",
Expand Down Expand Up @@ -1190,10 +1196,53 @@ fn goto_file_impl(cx: &mut Context, action: Action) {
.to_string(),
);
}

for sel in paths {
let p = sel.trim();
if !p.is_empty() {
let path = &rel_path.join(p);
if p.is_empty() {
continue;
}

if let Ok(url) = Url::parse(p) {
return open_url(cx, url, action);
}

let path = &rel_path.join(p);
if path.is_dir() {
let picker = ui::file_picker(path.into(), &cx.editor.config());
cx.push_layer(Box::new(overlaid(picker)));
} else if let Err(e) = cx.editor.open(path, action) {
cx.editor.set_error(format!("Open file failed: {:?}", e));
}
}
}

/// Opens url. If the URL is a valid textual file it is open in helix, other
/// the file is open using external program.
matoous marked this conversation as resolved.
Show resolved Hide resolved
fn open_url(cx: &mut Context, url: Url, action: Action) {
let (_, doc) = current_ref!(cx.editor);
matoous marked this conversation as resolved.
Show resolved Hide resolved
let rel_path = doc
.relative_path()
.map(|path| path.parent().unwrap().to_path_buf())
.unwrap_or_default();

if url.scheme() != "file" {
return open_external_url(cx, url);
}

let content_type = std::fs::File::open(url.path()).and_then(|file| {
// Read up to 1kb to detect the content type
let mut read_buffer = Vec::new();
let n = file.take(1024).read_to_end(&mut read_buffer)?;
Ok(content_inspector::inspect(&read_buffer[..n]))
});

// we attempt to open binary files - files that can't be open in helix - using external
// program as well, e.g. pdf files or images
match content_type {
Ok(content_inspector::ContentType::BINARY) => open_external_url(cx, url),
Ok(_) | Err(_) => {
let path = &rel_path.join(url.path());
if path.is_dir() {
let picker = ui::file_picker(path.into(), &cx.editor.config());
cx.push_layer(Box::new(overlaid(picker)));
Expand All @@ -1204,6 +1253,23 @@ fn goto_file_impl(cx: &mut Context, action: Action) {
}
}

/// Opens URL in external program.
fn open_external_url(cx: &mut Context, url: Url) {
let commands = open::commands(url.as_str());
cx.jobs.callback(async {
for cmd in commands {
let mut command = tokio::process::Command::new(cmd.get_program());
command.args(cmd.get_args());
if command.output().await.is_ok() {
return Ok(job::Callback::Editor(Box::new(|_| {})));
}
}
Ok(job::Callback::Editor(Box::new(move |editor| {
editor.set_error("Opening URL in external program failed")
})))
});
}

fn extend_word_impl<F>(cx: &mut Context, extend_fn: F)
where
F: Fn(RopeSlice, Range, usize) -> Range,
Expand Down
2 changes: 1 addition & 1 deletion helix-view/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ helix-vcs = { version = "0.6", path = "../helix-vcs" }

# Conversion traits
once_cell = "1.18"
url = "2"
url = "2.4.1"

arc-swap = { version = "1.6.0" }

Expand Down
Loading