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: convert .xsh file to be .py file #18

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all 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
1 change: 1 addition & 0 deletions setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
author='David Strobach',
author_email='[email protected]',
description="fzf widgets for xonsh",
install_requires=['xonsh>=0.10'],
packages=['xontrib'],
package_dir={'xontrib': 'xontrib'},
package_data={'xontrib': ['*.xsh']},
Expand Down
106 changes: 66 additions & 40 deletions xontrib/fzf-widgets.xsh → xontrib/fzf_widgets.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,21 +3,28 @@
import subprocess
from xonsh.history.main import history_main
from xonsh.completers.path import complete_path
from prompt_toolkit.keys import Keys
from xonsh.built_ins import XSH, subproc_captured_stdout

__all__ = ()


def _run(*args):
return subproc_captured_stdout(args)


def get_fzf_binary_name():
fzf_tmux_cmd = 'fzf-tmux'
if 'TMUX' in ${...} and $(which fzf_tmux_cmd):
fzf_tmux_cmd = "fzf-tmux"
if "TMUX" in XSH.env and _run("which", "fzf_tmux_cmd"):
return fzf_tmux_cmd
return 'fzf'
return "fzf"


def get_fzf_binary_path():
path = $(which @(get_fzf_binary_name()))
path = _run("which", get_fzf_binary_name())
if not path:
raise Exception("Could not determine path of fzf using `which`; maybe it is not installed or not on PATH?")
raise Exception(
"Could not determine path of fzf using `which`; maybe it is not installed or not on PATH?"
)
return path


Expand All @@ -29,18 +36,23 @@ def fzf_insert_history(event):
# That also means that we don't have to `decode()` the stdout.read()` below.
popen_args = [
get_fzf_binary_path(),
'--read0',
'--tac',
'--tiebreak=index',
'+m',
'--reverse',
'--height=40%',
'--bind=ctrl-r:toggle-sort',
"--read0",
"--tac",
"--tiebreak=index",
"+m",
"--reverse",
"--height=40%",
"--bind=ctrl-r:toggle-sort",
]
if len(event.current_buffer.text) > 0:
popen_args.append(f'-q ^{event.current_buffer.text}')
proc = subprocess.Popen(popen_args, stdin=subprocess.PIPE, stdout=subprocess.PIPE, universal_newlines=True)
history_main(args=['show', '-0', 'all'], stdout=proc.stdin)
popen_args.append(f"-q ^{event.current_buffer.text}")
proc = subprocess.Popen(
popen_args,
stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
universal_newlines=True,
)
history_main(args=["show", "-0", "all"], stdout=proc.stdin)
proc.stdin.close()
proc.wait()
choice = proc.stdout.read().strip()
Expand All @@ -55,15 +67,17 @@ def fzf_insert_history(event):

def fzf_insert_file(event, dirs_only=False):
before_cursor = event.current_buffer.document.current_line_before_cursor
delim_pos = before_cursor.rfind(' ', 0, len(before_cursor))
delim_pos = before_cursor.rfind(" ", 0, len(before_cursor))
prefix = None
if delim_pos != -1 and delim_pos != len(before_cursor) - 1:
prefix = before_cursor[delim_pos+1:]
prefix = before_cursor[delim_pos + 1 :]

cwd = None
path = ''
path = ""
if prefix:
paths = complete_path(os.path.normpath(prefix), before_cursor, 0, len(before_cursor), None)[0]
paths = complete_path(
os.path.normpath(prefix), before_cursor, 0, len(before_cursor), None
)[0]
if len(paths) == 1:
path = paths.pop()
expanded_path = os.path.expanduser(path)
Expand All @@ -73,14 +87,19 @@ def fzf_insert_file(event, dirs_only=False):

env = os.environ
if dirs_only:
if 'fzf_find_dirs_command' in ${...}:
env['FZF_DEFAULT_COMMAND'] = $fzf_find_dirs_command
if "fzf_find_dirs_command" in XSH.env:
env["FZF_DEFAULT_COMMAND"] = XSH.env["fzf_find_dirs_command"]
else:
if 'fzf_find_command' in ${...}:
env['FZF_DEFAULT_COMMAND'] = $fzf_find_command
if 'FZF_DEFAULT_OPTS' in ${...}:
env['FZF_DEFAULT_OPTS'] = $FZF_DEFAULT_OPTS
choice = subprocess.run([get_fzf_binary_path(), '-m', '--reverse', '--height=40%'], stdout=subprocess.PIPE, universal_newlines=True, env=env).stdout.strip()
if "fzf_find_command" in XSH.env:
env["FZF_DEFAULT_COMMAND"] = XSH.env["fzf_find_command"]
if "FZF_DEFAULT_OPTS" in XSH.env:
env["FZF_DEFAULT_OPTS"] = XSH.env["FZF_DEFAULT_OPTS"]
choice = subprocess.run(
[get_fzf_binary_path(), "-m", "--reverse", "--height=40%"],
stdout=subprocess.PIPE,
universal_newlines=True,
env=env,
).stdout.strip()

if cwd:
os.chdir(cwd)
Expand All @@ -91,52 +110,59 @@ def fzf_insert_file(event, dirs_only=False):
if path:
event.current_buffer.delete_before_cursor(len(prefix))

command = ''
command = ""
for c in choice.splitlines():
command += "'" + os.path.join(path, c.strip()) + "' "

event.current_buffer.insert_text(command.strip())


def fzf_prompt_from_string(string):
choice = subprocess.run([get_fzf_binary_path(), '--tiebreak=index', '+m', '--reverse', '--height=40%'], input=string, stdout=subprocess.PIPE, universal_newlines=True).stdout.strip()
choice = subprocess.run(
[get_fzf_binary_path(), "--tiebreak=index", "+m", "--reverse", "--height=40%"],
input=string,
stdout=subprocess.PIPE,
universal_newlines=True,
).stdout.strip()
return choice


@events.on_ptk_create
@XSH.builtins.events.on_ptk_create
def custom_keybindings(bindings, **kw):
def handler(key_name):
def do_nothing(func):
pass

key = ${...}.get(key_name)
key = XSH.env.get(key_name)
if key:
return bindings.add(key)
return do_nothing

@handler('fzf_history_binding')
@handler("fzf_history_binding")
def fzf_history(event):
fzf_insert_history(event)

@handler('fzf_ssh_binding')
@handler("fzf_ssh_binding")
def fzf_ssh(event):
items = '\n'.join(
re.findall(r'Host\s(.*)\n?',
$(cat ~/.ssh/config /etc/ssh/ssh_config),
re.IGNORECASE)
items = "\n".join(
re.findall(
r"Host\s(.*)\n?",
_run("cat", "~/.ssh/config", "/etc/ssh/ssh_config"),
re.IGNORECASE,
)
)
choice = fzf_prompt_from_string(items)

# Redraw the shell because fzf used alternate mode
event.cli.renderer.erase()

if choice:
event.current_buffer.insert_text('ssh ' + choice)
event.current_buffer.insert_text("ssh " + choice)

@handler('fzf_file_binding')
@handler("fzf_file_binding")
def fzf_file(event):
fzf_insert_file(event)

@handler('fzf_dir_binding')
@handler("fzf_dir_binding")
def fzf_dir(event):
fzf_insert_file(event, True)