Giter Club home page Giter Club logo

psfzf's Introduction

PSFzf

PowerShell Gallery Version PowerShell Gallery Version PowerShell Gallery Downloads Build status MIT licensed

PSFzf is a PowerShell module that wraps fzf, a fuzzy file finder for the command line.

keyboard shortcut demonstration

Usage

To change to a user selected directory:

Get-ChildItem . -Recurse -Attributes Directory | Invoke-Fzf | Set-Location

To edit a file:

Get-ChildItem . -Recurse -Attributes !Directory | Invoke-Fzf | % { notepad $_ }

For day-to-day usage, see the helper functions included with this module.

PSReadline Integration

Select Current Provider Path (default chord: Ctrl+t)

Press Ctrl+t to start PSFzf to select provider paths. PSFzf will parse the current token and use that as the starting path to search from. If current token is empty, or the token isn't a valid path, PSFzf will search below the current working directory.

Multiple items can be selected. If more than one is selected by the user, the results are returned as a comma separated list. Results are properly quoted if they contain whitespace.

Reverse Search Through PSReadline History (default chord: Ctrl+r)

Press Ctrl+r to start PSFzf to select a command in the command history saved by PSReadline. PSFzf will insert the command into the current line, but it will not execute the command.

PSFzf does not override Ctrl+r by default. To confirm that you want to override PSReadline's chord binding, use the Set-PsFzfOption command:

# replace 'Ctrl+t' and 'Ctrl+r' with your preferred bindings:
Set-PsFzfOption -PSReadlineChordProvider 'Ctrl+t' -PSReadlineChordReverseHistory 'Ctrl+r'

Set-Location Based on Selected Directory (default chord: Alt+c)

Press Alt+c to start PSFzf to select a directory. By default, Set-Location will be called with the selected directory. You can override the default command with the following code in our $PROFILE:

# example command - use $Location with a different command:
$commandOverride = [ScriptBlock]{ param($Location) Write-Host $Location }
# pass your override to PSFzf:
Set-PsFzfOption -AltCCommand $commandOverride

Search Through Command Line Arguments in PSReadline History (default chord: Alt+a)

Press Alt+a to start PSFzf to select command line arguments used in PSReadline history. The picked argument will be inserted in the current line. The line that would result from the selection is shown in the preview window.

Tab Expansion

PSFzf can replace the standard tab completion:

Set-PSReadLineKeyHandler -Key Tab -ScriptBlock { Invoke-FzfTabCompletion }

To activate continuous completion, press the directory separator character to complete the current selection and start tab completion for the next part of the container path.

PSFzf supports specialized tab expansion with a small set of commands. After typing the default trigger command, which defaults to "**", and press Tab, PsFzf tab expansion will provide selectable list of options.

The following commands are supported:

Command Notes
git Uses posh-git for providing tab completion options. Requires at least version 1.0.0 Beta 4.
Get-Service, Start-Service, Stop-Service Allows the user to select between the installed services.
Get-Process, Start-Process Allows the user to select between running processes.

To override the trigger command, set FZF_COMPLETION_TRIGGER to your preferred trigger sequence.

Use the following command to enable tab expansion:

Set-PsFzfOption -TabExpansion

Using within a Pipeline

Invoke-Fzf works with input from a pipeline. You can use it in the middle of a pipeline, or as part of an expression.

Set-Location (Get-ChildItem . -Recurse | ? { $_.PSIsContainer } | Invoke-Fzf) # This works as of version 2.2.8
Get-ChildItem . -Recurse | ? { $_.PSIsContainer } | Invoke-Fzf | Set-Location

Overriding Behavior

PsFzf supports overriding behavior by setting these fzf environment variables:

Env Var Name Description
_PSFZF_FZF_DEFAULT_OPTS If this environment variable is set, then FZF_DEFAULT_OPTS is temporarily set with the contents. This allows the user to have different default options for PSFZF and fzf.
FZF_DEFAULT_COMMAND The command specified in this environment variable will override the default command when PSFZF detects that the current location is a file system provider.
FZF_CTRL_T_COMMAND The command specified in this environment variable will be used when Ctrl+t is pressed by the user.
FZF_ALT_C_COMMAND The command specified in this environment variable will be used when Alt+c is pressed by the user.
PSFZF_EDITOR_OPTIONS Contains options passed to the editor application used in the Invoke-FuzzyEdit() function

Helper Functions

In addition to its core function Invoke-Fzf, PSFzf includes a set of useful functions and aliases. The aliases are not installed by default. To enable aliases, use Set-PSFzfOption's -EnableAlias* options.

Function Alias Description
Invoke-FuzzyEdit fe Starts an editor for the selected files in the fuzzy finder.
Invoke-FuzzyFasd ff Starts fzf with input from the files saved in fasd(non-Windows) or fasdr (Windows) and sets the current location.
Invoke-FuzzyZLocation fz Starts fzf with input from the history of ZLocation and sets the current location.
Invoke-FuzzyGitStatus fgs Starts fzf with input from output of the git status function.
Invoke-FuzzyHistory fh Rerun a previous command from history based on the user's selection in fzf.
Invoke-FuzzyKillProcess fkill Runs Stop-Process on processes selected by the user in fzf.
Invoke-FuzzySetLocation fd Sets the current location from the user's selection in fzf.
Invoke-FuzzyScoop fs Starts fzf on Scoop applications list.
Invoke-PsFzfRipgrep N/A Uses Ripgrep and Fzf to interactively search files.
Set-LocationFuzzyEverything cde Sets the current location based on the Everything database.

Prerequisites

Follow the installation instructions for fzf before installing PSFzf. PSFzf will run Get-Command to find fzf in your path.

Windows

The latest version of fzf is available via Chocolatey, or you can download the fzf binary and place it in your path. Run Get-Command fzf*.exe to verify that PowerShell can find the executable.

PSFzf has been tested under PowerShell 5.0, 6.0, and 7.0.

MacOS

Use Homebrew or download the binary and place it in your path. Run Get-Command fzf* to verify that PowerShell can find the executable.

PSFzf has been tested under PowerShell 6.0 and 7.0.

Linux

PSFzf has been tested under PowerShell 6.0 and 7.0 in the Windows Subsystem for Linux.

Installation

PSFzf is available on the PowerShell Gallery and Scoop. PSReadline should be imported before PSFzf as PSFzf registers PSReadline key handlers listed in the PSReadline integration section.

Helper Function Requirements

psfzf's People

Contributors

asafmah avatar bedware avatar belotn avatar ceyfun avatar chenxiaolong avatar diegomichel avatar giggio avatar here-mikelley avatar kelleyma49 avatar mattcargile avatar ofzorzo avatar pitkali avatar rashil2000 avatar sitiom avatar stinos avatar varriount avatar vors avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar

psfzf's Issues

Ctrl + R fzf clears terminal

Hi,

If i had some output in my terminal, and then press Ctrl + R, the fzf output appears, and after i select something, the output of the terminal is not restored.

Is there a way to keep the output?

PSReadLine integration: history fuzzy search

Awesome project!

I was trying to implement this scenario with fzf and PSReadLine, but didn't succeed.
It would be useful to pipe all history records from PSReadLine to fzf.
Maybe you know how to get it done?

Escape sequence printed for CTRL-T, fe and fd commands

When I use any of the CTRL-T, fe, or fd commands in ConEmu, PowerShell console or Windows Terminal, an escape sequence appears at the beginning and end of the line. I assume this is supposed to colour the line?

For example, CTRL-T gives:

 [0m[36m.File1.log[0m
 [0m[36m.File2.log[0m
...

And when I select one, the [0m[36m. and [0m are included in the selection, which I have to then delete.

I'm sure this used to work. I'm using PSFzF 1.1.26. Update-Module did not update it when I tried (in case there's a later version).

I've tried on PowerShell versions 5.1 and 6.2 running on Windows 10 1903.

I feel I'm doing something basically wrong! Please can you help correct this.

Thanks

CTRL-T does not work in vi-mode

I use vi-mode on the powershell command line by putting this in my profile:

Set-PSReadlineOption -EditMode vi

When using vi-mode, CTRL-T transposes characters. Is there any way to override the default behavior so that fzf is invoked instead?

Case sensitive?

Win7x64 here and all the instructions are accurate, but all case sensitive. Even if I disable my entire PS profile and run vanilla and only enable psreadline and then psfzf.

So, I literally have to also hold the SHIFT key along with the CTRL and T keys and CTRL and G for this:

Import-Module PSFzf -ArgumentList 'Ctrl+T','Ctrl+G'

But, I only have to press CTRL and T and CTRL and G for this:

Import-Module PSFzf -ArgumentList 'Ctrl+t','Ctrl+g'

And to even further prove that's what's happening, I could not figure out for the life of me why the built-in ALT+ A key and ALT+ C key as listed in the Readme also did nothing. It sure seemed like the module was just broken. Then, once I figured out the above, I also went back (in any of the shells since it's a default binding) and first held down SHIFT and then pressed the SHIFT+ALT+a and SHIFT+ALT+c, and wholla only with shift to make the literal uppercase "A" and "C" true did the default bindings suddenly work.

This seems to be the case on mult systems I am testing, so is this a new bug or ?

TIA!

Add ability to specify options for fzf

First, this is a great tool. I would like to be able to specify command line options that this tool sends to fzf.

This can already be set globally by using fzf's env variable FZF_DEFAULT_OPTS but that's not what I am looking for. I want to specify default options only for the case when fzf is invoked by PSFzf. Could you add another option or env variable for that ?

For example, zoxide uses another env variable for that - _ZO_FZF_OPTS: https://github.com/ajeetdsouza/zoxide#environment-variables

Key chords do not always register when Import-Module is run in $PROFILE

I'm finding that the module import process is not working from the $PROFILE configuration file. On my work computer, I got it to work consistently by moving the import statement from the top of $PROFILE to the bottom, but it has not been effective for my laptop. I always have to wait for powershell to load, then run the import statement manually. I assume powershell is loading something asynchronously that is overwriting the chords, but I don't know enough about it to figure out what it could be.

Here's a snippet from my $PROFILE with the imports.

# Modules
Import-Module PSReadLine
Import-Module PSFzf -ArgumentList 'Ctrl+t', 'Alt+r' -Force
Import-Module Get-ChildItemColor

# Module settings
Set-PSReadLineOption -EditMode Vi

Does anyone have a trick to make sure the chords always work?

Open file from powershell

when using ctrl + t, after selecting the file, the file name is marked with '{0}', hence could not autostart it.

i tweaked my PSFzf.psm1 to add '&' before '{0}' and start the file.

eg. .txt file will be opened in notepad by default,

Selecting an item from a long-running command before it completes causes an error

If I select an item from the output of a long running command, before the command completes, then the command terminates with an error and dumps a traceback on the screen.

As a demonstration, try the following Python script:

import time

for i in range(1000):
    print(f"Item {i}",flush=True)
    time.sleep(1)

This generates one line of output per second. Run py .\ex.py | invoke-fzf and select item 3 when it appears. The output is displayed, but then an error appears, along with some traceback output from Python.

>py .\ex.py | invoke-fzf
Item 3
ResourceUnavailable: Program 'py.exe' failed to run: Stopped fzf pipeline inputAt line:1 char:1
+ py .\ex.py | invoke-fzf
+ ~~~~~~~~~~.
PS 20:36 {00:05.139} D:\Work\Scratch
>Traceback (most recent call last):
  File ".\ex.py", line 4, in <module>
    print(f"Item {i}",flush=True)
OSError: [Errno 22] Invalid argument
Exception ignored in: <_io.TextIOWrapper name='<stdout>' mode='w' encoding='cp1252'>
OSError: [Errno 22] Invalid argument

Note that the prompt is part-way through the output, and if you start typing, what you types overwrites the output just after the > of the prompt.

FZF_DEFAULT_COMMAND ignored

[latest PSFzf and PowerShell 6.2.0-preview.2 on Windows]

I suspected because of similar timings for different FZF_DEFAULT_COMMAND that PSFzf ignores that environment variable. This seems to confirm the problem:

pwsh> $Env:FZF_DEFAULT_COMMAND = 'does_not_exist'
pwsh> fzf
>   < [$FZF_DEFAULT_COMMAND failed]

pwsh> Invoke-FuzzySetLocation
>   < 2299/2299

Warning about argumentlist even when provided

As of (I believe) 1.1.19, I get this warning even though I am using -ArgumentList:

λ Import-Module PSFzf -ArgumentList 'Alt+T','Ctrl+R'
WARNING: PSReadline chord ctrl+r already in use - keyboard handler not installed.  To bind your own keyboard chord, use  the -ArgumentList parameter when you call Import-Module.
WARNING: PSReadline chord alt+c already in use - keyboard handler not installed.  To bind your own keyboard chord, use
the -ArgumentList parameter when you call Import-Module.
WARNING: PSReadline chord alt+a already in use - keyboard handler not installed.  To bind your own keyboard chord, use
the -ArgumentList parameter when you call Import-Module.

Despite the warning, the key chord bindings work as expected.

Special characters are replaced with question marks after PSFzf runs (but not after fzf by itself)

When PSFzf is used with a powerline (e.g. oh-my-posh), the special characters are replaced with question marks after fzf runs.

image

Reproduction steps:

  1. Install oh-my-posh and choose a theme that uses special characters
  2. Invoke PSFzf, and then make a selection or close fzf

Tested on latest version (2.2.6)

Additional note: This issue does not occur when fzf is called manually from the command line

After invoking Ctrl+T search stops and fzf hangs after typing the first character

Repro Steps:

  1. Open a PowerShell Core instance in Windows Terminal
  2. Press Ctrl+T
  3. Type a search term

NOTE: Ctrl+R to search history works perfectly fine

Expected Behavior

Search is refined by the entered text, and am able to select a result with the arrow keys.

Actual Behavior

Search stops after the first character is entered, and fzf seems to freeze as it's no longer responsive to arrow keys or the escape key. It's possible to only backspace up to the first character entered, but it doesn't allow deleting that first character. Pressing enter selects the first entry, otherwise the only way to exit is Ctrl+C as it's not responsive to escape.

Screenshots

After entering a search term:
image

After attempting to delete the entire search term:
image

Versions

  • PSFzf: 2.2.8 and 2.2.6
  • PSReadline: 2.1.0
  • PowerShell Core: 7.1.4
    • Also repros in Windows PowerShell 5.1, but allows backspacing to delete the entire search term with otherwise identical behavior
  • Windows Terminal: 1.10.2383.0

PowerShell Profile

Relevant lines in my profile:

Import-Module PSFzf
Set-PSReadLineKeyHandler -Key Tab -ScriptBlock { Invoke-FzfTabCompletion }
Set-PsFzfOption -PSReadlineChordProvider 'Ctrl+t' -PSReadlineChordReverseHistory 'Ctrl+r'

Environment

FZF_DEFAULT_COMMAND = 'fd --type file'

Onedrive mess up with this plugin

Hi,
Thanks for this plugin, I had to switch from linux to windows and this save me a lot of time.

Script version :
Install-Module -Name PSFzf -AllowPrerelease

pwsh --version
PowerShell 7.2.0

$profile :

Import-Module posh-git
Import-Module oh-my-posh
Import-Module PSFzf
Import-Module ZLocation
Import-Module -Name PSKubectlCompletion

Register-KubectlCompletion

Set-PSReadLineKeyHandler -Key Tab -ScriptBlock { Invoke-FzfTabCompletion }
Set-PSReadlineOption -Color @{
  "Parameter"="$([char]0x1b)[93m"
  "Operator"="$([char]0x1b)[93m"
}
Set-PSReadLineOption -PredictionSource History
Set-PsFzfOption -PSReadlineChordProvider 'Ctrl+t' -PSReadlineChordReverseHistory 'Ctrl+r'
Set-PoshPrompt -Theme powerlevel10k_rainbow

I have onedrive on this pc, and in my home dir I have something like that:

d----          11/24/2021  4:20 PM                kaniko
d-r--          10/27/2021  3:08 PM                Links
d----           11/8/2021  6:22 PM                linux-install
d----           11/8/2021 11:13 PM                linux-wsl
d-r--          10/27/2021  3:08 PM                Music
d----          11/16/2021  6:36 PM                npm-cache
lar--          11/26/2021  4:52 PM                OneDrive - Yahoo
d-r--          10/27/2021  3:08 PM                Saved Games
d----          11/25/2021  4:28 PM                scoop
d-r--          11/23/2021  9:21 AM                Searches
d----          11/23/2021  3:40 PM                tmp
d----          11/19/2021  9:45 AM                video
d-r--          11/10/2021 11:25 AM                Videos

If I do

cd 
cd <TAB>

The terminal is splitted and on the right side I have

 The argument 'C:\Users\Ben\OneDrive' is not recognized as the name of a script file. Check the 
...
Usage: pwsh[.exe] [-Login] [[-File] <filePath> [args]] 
...

As if spaces in path are not protected.

Thanks in advance.

Support --expect

It looks like --expect works OK on Windows and would be useful to build PowerShell functions that take different actions on the search results. Could it be added to the Invoke-Fzf wrapper?

Arrow keys are unusable when using Windows Terminal

PSFzf Version: 2.2.6
PowerShell Version: 5.1.19041.906
Windows Version: 10.0.19043.985
Windows Terminal Version: 1.8.1521.0

Can't select items by arrow keys, just output ^[[A... and exit (like pressing Esc). In conhost.exe it works fine.

Screenshot 2021-06-08 193443

Add option to use something else instead of `Set-Location` with `Invoke-FzfPsReadlineHandlerSetLocation`

This package is awesome! The Alt+C binding is what I’m most interested in. I try to avoid cd/Set-Location, though; I’d like to be able to use Push-Location or even zoxide instead. Would it be possible to add a setting to use a different command? (I tried to do this myself and thought I got it right on the script side, but I couldn’t figure out how to get PowerShell to pick up my changes even after rebuilding and reimporting.)

Tab disabled by PSFzf?

Hello

I've enabled PSFzf with the commands:

Remove-PSReadlineKeyHandler 'CTRL+R'
Import-Module PSFzf

This all works. However, when I'm in PowerShell, the tab key does nothing!

If I use

Import-Module PSFzf -ArgumentList 'Ctrl+T','Ctrl+R', 'Tab'

Then I get fzf invoked when I press tab.

How do I get the default tab behaviour whilst using PSfzf. Note tab works fine when using just PSReadline and fzf.

I'm using Windows 10 Creators Update with PowerShell 5.1.

Thanks
Praful

Result of TAB completion not written to command line

DO

  1. Open Powershell
  2. Set-PSReadLineKeyHandler -Key Tab -ScriptBlock { Invoke-FzfTabCompletion }
  3. Type something and hit <TAB>
  4. fzf opens and I can type to narrow down matches and select the item I want on the command line
  5. hit <ENTER>

GET

the text I typed to narrow down the list of results

EXPECT

the Item I selected appended to my command line

Remark

Powershell 5.1.17763.1971

Using all other chords like - R work as expected. I guess I am missing something? Anything else I can try?

Prompt string gets erased

  1. Press Ctrl-r
  2. Type something to search
  3. Press Enter to select an entry
  4. The entry pops up, with powershell prompt erased

PSFzf

Exception in custom key handler when kubectl completion finds no results

The pre-release versions of kubectl v1.23.0 include PowerShell completion, which is provided under the hood by spf13/cobra. This works beautifully most of the time in conjunction with Set-PSReadLineKeyHandler -Key Tab -ScriptBlock { Invoke-FzfTabCompletion }:

Pressing Tab retrieves and shows the list of resources to complete

However, there seems to be an issue when there are no completions available:

Pressing Tab results in an exception message when no completions are available

(Note that pressing Ctrl + C has no effect. I have to press Enter to run the command before I can do anything else.)

I’ll reproduce it in text for legibility, though of course without the formatting:

❯❯ kubectl get pods fAn exception occurred in custom key handler, see $error for more information: Exception calling "CompleteInput" with "3" argument(s): "Cannot process argument because the value of argument "completionText" is null. Change the value of argument "completionText" to a non-null value."
~
❯❯ kubectl get pods f
Error from server (NotFound): pods "f" not found
~ took 1s157ms
❯❯ kubectl asdasdAn exception occurred in custom key handler, see $error for more information: Exception calling "CompleteInput" with "3" argument(s): "Cannot process argument because the value of argument "completionText" is null. Change the value of argument "completionText" to a non-null value."
~ took 1s157ms
❯❯ kubectl asdasd
E1128 12:56:48.823585   19468 run.go:120] "command failed" err="unknown command \"asdasd\" for \"kubectl\""

Now, if I run the command that the application’s completion script runs under the hood, this is what I see:

❯❯ k __complete asdasd
:4
Completion ended with directive: ShellCompDirectiveNoFileComp

Which is the result of this code:

    if (($Directive -band $ShellCompDirectiveNoFileComp) -ne 0 ) {
        __kubectl_debug "ShellCompDirectiveNoFileComp is called"

        if ($Values.Length -eq 0) {
            # Just print an empty string here so the
            # shell does not start to complete paths.
            # We cannot use CompletionResult here because
            # it does not accept an empty string as argument.
            ""
            return
        }
    }

As far as I can tell, the completion script is doing the right thing. Without PsFzf, pressing Tab does nothing if there are no completions, as you’d expect, and lets you continue your input. With PsFzf, pressing Tab with no completions available causes an error and prevents you from using Ctrl + C to cancel the input.

I’m running PsFzf v2.3.1-alpha (which I upgraded to from v2.2.9 in case it fixed this bug) with PowerShell v7.2.0 under Windows 10.0.19043 (64-bit).

tab completion errors

When hitting tab after Get-Module -:

PS C:\Users\cstrahan> Get-Module -
> -                                                                                 ╭─────────────────────────────────────────────────────────────────────────────────╮
  22/22                                                                             │ PsFzfTabExpansion-Preview.ps1: A parameter cannot be found that matches paramet │
> -All                                                                              │                                                                                 │
  -Name                                                                             │                                                                                 │
  -Debug                                                                            │                                                                                 │
  -Refresh                                                                          │                                                                                 │
  -Verbose                                                                          │                                                                                 │
  -PSEdition                                                                        │                                                                                 │
  -PSSession                                                                        │                                                                                 │
  -OutBuffer                                                                        │                                                                                 │
  -CimSession                                                                       ╰─────────────────────────────────────────────────────────────────────────────────╯


PS C:\Users\cstrahan> Get-Module -
> -                                                                                 ╭─────────────────────────────────────────────────────────────────────────────────╮
  22/22                                                                             │ InvalidOperation: C:\Users\cstrahan\Documents\PowerShell\Modules\PSFzf\2.3.1/40 │
  -All                                                                              │ Line |                                                                          │
  -Name                                                                             │    6 |  $Item = $Item.Trim("'").Trim('"')                                       │
> -Debug                                                                            │      |  ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~                                       │
  -Refresh                                                                          │      | You cannot call a method on a null-valued expression.                    │
  -Verbose                                                                          │                                                                                 │
  -PSEdition                                                                        │                                                                                 │
  -PSSession                                                                        │     Directory: C:\Users\cstrahan                                                │
  -OutBuffer                                                                        │ Mode                 LastWriteTime         Length Name                          │
  -CimSession                                                                       ╰─────────────────────────────────────────────────────────────────────────────────╯

Seems to fail here:

$Item = $Item.Trim("'").Trim('"')

This is on the latest alpha of PSFzF:

PS C:\Users\cstrahan> Get-Module -Name PSFzf

ModuleType Version    PreRelease Name                                ExportedCommands
---------- -------    ---------- ----                                ----------------
Script     2.3.1      alpha      PSFzf                               {Enable-PsFzfAliases, Invoke-FuzzyEdit, Invoke-FuzzyFasd, Invoke-FuzzyGitStatus…}

(also occurs with latest stable release)

FWIW, this is with the latest version of FZF installed through chocolatey:

C:\Windows\system32>fzf --version
0.28.0 (e4c3ecc)

Anything I can do to help resolve this? This module otherwise seems awesome!

Text preview with bat is not available after PSFzf version 2.1.0

After upgrading PSFzf to version 2.1.0, I found that I could not use bat for text preview.
This is my fzf configuration.

$env:FZF_DEFAULT_OPTS="--prompt '⯈ ' --height 50% --layout=reverse --border 
--color=dark
--color=fg:-1,bg:-1,hl:#5fff87,fg+:-1,bg+:-1,hl+:#ffaf5f
--color=info:#af87ff,prompt:#5fff87,pointer:#ff87d7,marker:#ff87d7,spinner:#ff87d7"
$env:FD_OPTIONS="--hidden --follow"
$env:FZF_DEFAULT_COMMAND="fd --type f --type l {0}" -f $env:FD_OPTION
$env:FZF_CTRL_T_OPTS='--preview "bat --style=numbers,changes,header --color=always --theme=Dracula --line-range :500 {}  || cat {}"'

When in the user directory, it can preview normally.
1

When entering a random directory, I can't use bat to preview, and the system can't find the specified file.
2

Cannot find fzf binary on mac os

So, its possible that something may be misconfigured, but I have fzf installed with homebrew and working in other shells. However, I cannot import psfzf even though Get-Command can find the fzf binary.
From my shell:

❯ pwsh
PowerShell v6.0.2
Copyright (c) Microsoft Corporation. All rights reserved.

https://aka.ms/pscore6-docs
Type 'help' to get help.

PS /Users/ryanzeigler> Get-Command fzf*

CommandType     Name                                               Version    Source
-----------     ----                                               -------    ------
Application     fzf                                                0.0.0.0    /usr/local/bin/fzf
Application     fzf                                                0.0.0.0    /usr/local/opt/fzf/bin/fzf
Application     fzf-tmux                                           0.0.0.0    /usr/local/bin/fzf-tmux
Application     fzf-tmux                                           0.0.0.0    /usr/local/opt/fzf/bin/fzf-tmux


PS /Users/ryanzeigler> Import-Module PSFzf -ArgumentList 'Ctrl+T','Ctrl+R'
Get-Command : Cannot validate argument on parameter 'Name'. The argument is null or empty. Provide an argument that is not null or empty, and then try the command again.
At /usr/local/share/powershell/Modules/PSFzf/1.1.14/PSFzf.psm1:491 char:35
+             $result = Get-Command $_ -ErrorAction SilentlyContinue
+                                   ~~
+ CategoryInfo          : InvalidData: (:) [Get-Command], ParameterBindingValidationException
+ FullyQualifiedErrorId : ParameterArgumentValidationError,Microsoft.PowerShell.Commands.GetCommandCommand

Resolve-Path : Cannot bind argument to parameter 'Path' because it is null.
At /usr/local/share/powershell/Modules/PSFzf/1.1.14/PSFzf.psm1:493 char:52
+                 $script:FzfLocation = Resolve-Path $_.Source
+                                                    ~~~~~~~~~
+ CategoryInfo          : InvalidData: (:) [Resolve-Path], ParameterBindingValidationException
+ FullyQualifiedErrorId : ParameterArgumentValidationErrorNullNotAllowed,Microsoft.PowerShell.Commands.ResolvePathCommand

Import-Module : Failed to find fzf binary in PATH.  You can download a binary from this page: https://github.com/junegunn/fzf-bin/releases
At line:1 char:1
+ Import-Module PSFzf -ArgumentList 'Ctrl+T','Ctrl+R'
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo          : OperationStopped: (Failed to find ...zf-bin/releases:String) [Import-Module], RuntimeException
+ FullyQualifiedErrorId : Failed to find fzf binary in PATH.  You can download a binary from this page: https://github.com/junegunn/fzf-bin/releases,Microsoft.PowerShell.Commands.ImportModuleCommand

The documentation for Invoke-Fzf is not up-to-date

The Invoke-Fzf.md file is not up-to-date. For example, it claims that there's a parameter called InlineInfo, but when I run Invoke-Fzf -InlineInfo, I got this error:

Invoke-Fzf: A parameter cannot be found that matches parameter name 'InlineInfo'.

Prevent the module from creating certain aliases

Is there a way to prevent the module from importing certain aliases? In my case, specifically, the alias fd shadows the fd command (the cool find command).

Is the solution to do something like this? This doesn't seem very clean, as it might end up not removing the alias that was intended.

Import-Module PSFzf -ArgumentList 'Ctrl+T','Ctrl+R'
Remove-Item alias:fd

Slow Start

Adding this plugin hogs powershell start time.

Is there a way to respect .gitignore?

I know there is a way to make fzf respect .gitignore files on Bash, but is there a way to do it with PowerShell? I am struggling to figure it out.

Enabling aliases is very slow

I add the following to my PS init script to enable aliases on all shells:

echo "Loading aliases ..."
Enable-PsFzfAliases
echo "Done."

However this slows down the shell initialization by several seconds (5s). Any way to speed things up here?

Missing partial history search functionality

When using zsh you can invoke the history widget and it will use what you already have as input to match commands from history. While PSFzf doesn't care about what you already have written before invoking it ctrl+r.

A second point is that it doesn't replace the entire line but rather insert it at the cursor position. I suspect because you had always planned for this to be used on an empty line.

See an example here:
lzFJZh4O5l

I tried to take a look at the code but sadly my experience with PowerShell scripting is very limited. I suspect you can probably re-use some of the logic in PSFzf.TabExpansion.ps1 specifically the part where you use GetBufferState().

P.S. thanks for the amazing work!

Populates the $Error variable

Hi,

First of all, thank you for this useful module.

I just noticed something, which may or may not affect #23 (slow start), I noticed that whenever I start a PS session, my $Error variable is populated with all kinds of errors:

Get-Command : The term 'fgs' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again.
At C:\Program Files\WindowsPowerShell\Modules\PSFzf\1.1.23\PSFzf.Functions.ps1:11 char:15
+ ...   if (-not (Get-Command -Name $Name -ErrorAction SilentlyContinue)) { ...
+                 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : ObjectNotFound: (fgs:String) [Get-Command], CommandNotFoundException
    + FullyQualifiedErrorId : CommandNotFoundException,Microsoft.PowerShell.Commands.GetCommandCommand

Get-Command : The term 'fz' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again.
At C:\Program Files\WindowsPowerShell\Modules\PSFzf\1.1.23\PSFzf.Functions.ps1:11 char:15
+ ...   if (-not (Get-Command -Name $Name -ErrorAction SilentlyContinue)) { ...
+                 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : ObjectNotFound: (fz:String) [Get-Command], CommandNotFoundException
    + FullyQualifiedErrorId : CommandNotFoundException,Microsoft.PowerShell.Commands.GetCommandCommand

Get-Variable : Cannot find a variable with the name 'IsWindows'.
At C:\Program Files\WindowsPowerShell\Modules\ZLocation\1.1.0\ZLocation.Search.psm1:3 char:5
+ if((Get-Variable IsWindows -ErrorAction SilentlyContinue) -eq $null)  ...
+     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : ObjectNotFound: (IsWindows:String) [Get-Variable], ItemNotFoundException
    + FullyQualifiedErrorId : VariableNotFound,Microsoft.PowerShell.Commands.GetVariableCommand

Get-Variable : Cannot find a variable with the name 'IsMacOS'.
At C:\Program Files\WindowsPowerShell\Modules\ZLocation\1.1.0\ZLocation.Service.psm1:61 char:25
+ ... :Mode = if( Get-Variable IsMacOS -ErrorAction SilentlyContinue ) { 'E ...
+                 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : ObjectNotFound: (IsMacOS:String) [Get-Variable], ItemNotFoundException
    + FullyQualifiedErrorId : VariableNotFound,Microsoft.PowerShell.Commands.GetVariableCommand

Get-Command : The term 'cde' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again.
At C:\Program Files\WindowsPowerShell\Modules\PSFzf\1.1.23\PSFzf.Functions.ps1:11 char:15
+ ...   if (-not (Get-Command -Name $Name -ErrorAction SilentlyContinue)) { ...
+                 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : ObjectNotFound: (cde:String) [Get-Command], CommandNotFoundException
    + FullyQualifiedErrorId : CommandNotFoundException,Microsoft.PowerShell.Commands.GetCommandCommand

Get-Command : The term 'fkill' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again.
At C:\Program Files\WindowsPowerShell\Modules\PSFzf\1.1.23\PSFzf.Functions.ps1:11 char:15
+ ...   if (-not (Get-Command -Name $Name -ErrorAction SilentlyContinue)) { ...
+                 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : ObjectNotFound: (fkill:String) [Get-Command], CommandNotFoundException
    + FullyQualifiedErrorId : CommandNotFoundException,Microsoft.PowerShell.Commands.GetCommandCommand

Get-Command : The term 'fh' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again.
At C:\Program Files\WindowsPowerShell\Modules\PSFzf\1.1.23\PSFzf.Functions.ps1:11 char:15
+ ...   if (-not (Get-Command -Name $Name -ErrorAction SilentlyContinue)) { ...
+                 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : ObjectNotFound: (fh:String) [Get-Command], CommandNotFoundException
    + FullyQualifiedErrorId : CommandNotFoundException,Microsoft.PowerShell.Commands.GetCommandCommand

Get-Command : The term 'fasd' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again.
At C:\Program Files\WindowsPowerShell\Modules\PSFzf\1.1.23\PSFzf.Functions.ps1:83 char:11
+ } elseif (Get-Command fasd -ErrorAction SilentlyContinue) {
+           ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : ObjectNotFound: (fasd:String) [Get-Command], CommandNotFoundException
    + FullyQualifiedErrorId : CommandNotFoundException,Microsoft.PowerShell.Commands.GetCommandCommand

Get-Command : The term 'Get-Frecents' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again.
At C:\Program Files\WindowsPowerShell\Modules\PSFzf\1.1.23\PSFzf.Functions.ps1:68 char:5
+ if (Get-Command Get-Frecents -ErrorAction SilentlyContinue) {
+     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : ObjectNotFound: (Get-Frecents:String) [Get-Command], CommandNotFoundException
    + FullyQualifiedErrorId : CommandNotFoundException,Microsoft.PowerShell.Commands.GetCommandCommand

Get-Command : The term 'fe' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again.
At C:\Program Files\WindowsPowerShell\Modules\PSFzf\1.1.23\PSFzf.Functions.ps1:11 char:15
+ ...   if (-not (Get-Command -Name $Name -ErrorAction SilentlyContinue)) { ...
+                 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : ObjectNotFound: (fe:String) [Get-Command], CommandNotFoundException
    + FullyQualifiedErrorId : CommandNotFoundException,Microsoft.PowerShell.Commands.GetCommandCommand

So, I thought it might be a good idea to use -ErrorAction Ignore to prevent this from happening

[Feature request] Set the current location as the parent of the user's selection file in fzf

I would like to have the ability to fuzzy search a file and have the current working location set to the directory that contains the selected file.

For example, I have a directory structure like this:

├───backend
│   data.json
│   main.cs

└───frontend
│   data.json
│   main.js
└───...
There are times when I want to go to the backend directory to work on a few backend related files and I don't remember the name of the directory, but know the directory contains a file called main.cs. It will be helpful if there's a new command or a new parameter added to one of the existing commands that allows me to fuzzy search the main.cs file and then set the current working directory to backend.

I think this is a common use case that other people may also need.

Invoke-Fzf working directory for -Preview

When using Invoke-Fzf, the working directory of the fzf sub-process isn't changed to match the shell's current directory. When items are relative paths or otherwise depend on the current directory, this causes problems passing them to a preview command.

Using native fzf from a non-home location:

fzf --preview cd

the preview window outputs my current location.

But using Invoke-Fzf:

Invoke-Fzf -Preview cd

the preview window displays my home directory.

My actual use case was piping in a set of git branch names, and trying to preview the selected one with git log --graph {}, only to find that git was erroring on the lack of a .git subdirectory in the fzf process's working directory.

Using PSFzf 1.1.24 on Windows 8.1, PowerShell 6.2.2.

Slow to complete with large list

If I call fzf directly at the root of a deep directory tree (for example), I can choose a match and immediately exit without waiting for the full set of available files to be listed.

Doing the same with Invoke-Fzf seems to accept my match, but then I sit waiting with an empty screen for a while before I can do anything with the result. I assume it is waiting for the input set to finish building, but if I already found what i want is there a way to bail out like with fzf directly?

Chronological order in history search

How to get the chronological order in the history search ? The fzf documentation says : «If you want to see the commands in chronological order, press CTRL-R again which toggles sorting by relevance», but it doesn't look like it's possible with PSFzf.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.