ryanoasis / vim-devicons

Adds file type icons to Vim plugins such as: NERDTree, vim-airline, CtrlP, unite, Denite, lightline, vim-startify and many more
MIT License
5.57k stars 262 forks source link

FZF Support? #106

Open mhartington opened 8 years ago

mhartington commented 8 years ago

FZF has a vim interface for fast file searching.

https://github.com/junegunn/fzf

Similar to ctrlp/unite. Would be interested in have some icons in there too :grin:

ryanoasis commented 8 years ago

That's a cool idea :+1: . Just quickly looked at the code and I am not sure how much would be involved but definitely would like to try at some point :smile:

Thanks

danihodovic commented 8 years ago

:+1:

alexanderjeurissen commented 8 years ago

I really like this idea and have wanted this for a while as well. I think that the only way to achieve this is create a custom FZF source that appends the correct file icons in front of the filenames.

The problem with this approach is that we limit the user to using a specific FZF custom source and not have the devicons in all there already defined sources.

I'm willing to take this up and look into this further.

alexanderjeurissen commented 8 years ago

Ok so I've investigated it some more, and what I found so far is: Creating a custom source where we execute the default FZF_DEFAULT_COMMAND and prepend the icon for each resulting line seems like a really cumbersome way to do this.

nonetheless altough it took me a full afternoon (I'm a vimscript novice) I got it done (adding icons to fzf) see below screenshot:

screen shot 2016-04-27 at 16 43 01

The only part left is getting FZF to actually edit the file because now it tries to edit (icon + filename) as a path.

ryanoasis commented 8 years ago

@alexanderjeurissen Nice! Very cool. So this is for FZF in the terminal (executable)? Your previous comment I thought it was just the vim plugin of FZF.

The only part left is getting FZF to actually edit the file because now it tries to edit (icon + filename) as a path.

Ah yup, I had a similar struggle with CtrlP (eventually sending a PR to more easily do some things).

Not sure if it will be of any help to your particular case but this is how I was stripping out the glyphs for CtrlP: https://github.com/ryanoasis/vim-devicons/blob/master/plugin/webdevicons.vim#L505-L509

alexanderjeurissen commented 8 years ago

@ryanoasis DONE.

code:

" Files + devicons
function! Fzf_dev()
  function! s:files()
    let files = split(system($FZF_DEFAULT_COMMAND), '\n')
    return s:prepend_icon(files)
  endfunction

  function! s:prepend_icon(candidates)
    let result = []
    for candidate in a:candidates
      let filename = fnamemodify(candidate, ':p:t')
      let icon = WebDevIconsGetFileTypeSymbol(filename, isdirectory(filename))
      call add(result, printf("%s %s", icon, candidate))
    endfor

    return result
  endfunction

  function! s:edit_file(item)
    let parts = split(a:item, ' ')
    let file_path = get(parts, 1, '')
    execute 'silent e' file_path
  endfunction

  call fzf#run({
        \ 'source': <sid>files(),
        \ 'sink':   function('s:edit_file'),
        \ 'options': '-m -x +s',
        \ 'down':    '40%' })
endfunction
alexanderjeurissen commented 8 years ago

as I said the only downside of this approach is that people have to use this function.. as we require control over the source and sink options 😒 But it makes use of the $FZF_DEFAULT_COMMAND which is nice because that is where people specify if they want to use find or ag etc.

this function however doesn't include buffer files and MRU, not sure if that's a deal breaker for a lot of people. We could add them ofc but then we have to offer multiple variants or options ;)

And to answer your question: Yes this is only for using fzf in vim, the standalone fzf.vim plugin isn't required though.

alexanderjeurissen commented 8 years ago

I'll tackle some of the problems mentioned in my previous comment and refine the code. Expect a PullRequest somewhere this weekend. In the mean time people like ( @mhartington ) can use the snippet above ;-)

michaelmior commented 7 years ago

@alexanderjeurissen Any movement on this by chance?

alexanderjeurissen commented 7 years ago

@michaelmior the code snippet that i shared in a previous comment still works. However it is required that the user specifies this in their vimrc.

I so far haven't found time to work on implementing this in the devicons vim plugin. I don't expect to have spare time to work on this till september. So if people think it's a high priority feature, they can use the code I provided as a starting point for the implementation.

dvcrn commented 7 years ago

Another fzf user here. I tried the snippet from @alexanderjeurissen without much success. Anything else needed to get it working?

pyrho commented 6 years ago

@dvcrn @alexanderjeurissen's snippet works on my setup. Just calling :FZF won't work, you need to issue :call Fzf_dev() once you've copied the snippet to your .vimrc.

dkarter commented 6 years ago

If you want preview you can install the rouge gem: gem install rouge and use this code

" Files + devicons
function! Fzf_dev()
  let l:fzf_files_options = '--preview "rougify {2..-1} | head -'.&lines.'"'

  function! s:files()
    let l:files = split(system($FZF_DEFAULT_COMMAND), '\n')
    return s:prepend_icon(l:files)
  endfunction

  function! s:prepend_icon(candidates)
    let l:result = []
    for l:candidate in a:candidates
      let l:filename = fnamemodify(l:candidate, ':p:t')
      let l:icon = WebDevIconsGetFileTypeSymbol(l:filename, isdirectory(l:filename))
      call add(l:result, printf('%s %s', l:icon, l:candidate))
    endfor

    return l:result
  endfunction

  function! s:edit_file(item)
    let l:pos = stridx(a:item, ' ')
    let l:file_path = a:item[pos+1:-1]
    execute 'silent e' l:file_path
  endfunction

  call fzf#run({
        \ 'source': <sid>files(),
        \ 'sink':   function('s:edit_file'),
        \ 'options': '-m ' . l:fzf_files_options,
        \ 'down':    '40%' })
endfunction
image
maxdevjs commented 6 years ago

@dkarter great solution! There is a simple way to use the 'internal' fzf.vim preview ( fzf#vim#with_preview)? Trying it without success.

mellery451 commented 6 years ago

I've tried using the two Fzf_dev() commands proposed here (nvim 0.2.3-dev on macos) and it produces no results. I suspect $FZF_DEFAULT_COMMAND might be part of my problem (it's not defined in my env) ? How can I debug an empty file list being returned? Standard FZF works fine, but is (obviously) missing the devicons.

mellery451 commented 6 years ago

Follow-up: looks like installing fd via homebrew and then setting FZF_DEFAULT_COMMAND to fd --type f as described in the FZF docs allows the snippets to work for me. I don't think FZF_DEFAULT_COMMAND is strictly required for normal fzf use, but I'm fine with this change.

dkarter commented 6 years ago

I use ag aka The Silver Searcher as my FZF_DEFAULT_COMMAND, which IMO is great because:

  1. It's built for speed
  2. It respects .gitignore files in your project
  3. Allows tweaking global ignore patterns via ~/.agignore

Ag

If you want the same setup install via homebrew (macOS):

brew install the_silver_searcher

and add this to your .vimrc:

let $FZF_DEFAULT_COMMAND = 'ag --hidden -l -g ""'

RipGrep

If you want it to be even faster - use ripgrep

brew install ripgrep

and add this to your .vimrc:

let $FZF_DEFAULT_COMMAND = 'rg --hidden -l ""'

Compared with fd the above are many orders of magnitude faster in my experiments.

wfxr commented 6 years ago

@dkarter Good solution. The preview command can be simplified into this:

let l:fzf_files_options = '--preview "rougify {2..} | head -'.&lines.'"'

Here 2.. means columns from 2nd to last, which compose the expected filename.

wfxr commented 6 years ago

@dkarter These lines in edit_file(item) function has problem when the filename contains white spaces.

let l:parts = split(a:item, ' ')
let l:file_path = get(l:parts, 1, '')

Suggest replacing it by the following:

let l:pos = stridx(a:item, ' ')
let l:file_path = a:item[pos+1:]
dkarter commented 6 years ago

Thanks @wfxr! I've updated my comment above to include your improvements.

idoa01 commented 6 years ago

@dkarter also, to remove the dependency of the rouge gem, you can use this:

let l:fzf_file_options = '--preview "[[ \$(file --mime {2..-1}) =~ binary ]] && echo {2..-1} is a binary file || (highlight -O ansi -l {2..-1} || coderay {2..-1} || rougify {2..-1} || cat {2..-1}) 2> /dev/null | head -'.&lines.'"'

which tries the different supported highlighting programs and finally defaults to cat.

see here: https://github.com/junegunn/fzf#preview-window

jamestthompson3 commented 5 years ago

You can take advantage of the neovim async api with the following:

function! Fzf_dev(no_git) abort
  let s:file_list = ['']
  let s:callbacks = {
    \ 'on_stdout': 'OnEvent',
    \ 'on_exit': 'OnExit'
    \ }

  if !a:no_git
    call jobstart([ 'rg',  '--files' ], s:callbacks)
  else
    call jobstart([ 'rg', '-L', '-i', '--no-ignore', '--files' ], s:callbacks)
  endif

  function! OnEvent(job_id, data, event)
    let s:file_list[-1] .= a:data[0]
    call extend(s:file_list, a:data[1:])
  endfunction

  function! OnExit(job_id, data, event)
      call fzf#run({
        \ 'source': s:prepend_icon(s:file_list),
        \ 'sink':   function('s:edit_file'),
        \ 'options': '-m',
        \ 'down': '40%'
        \ })
  endfunction

  function! s:prepend_icon(candidates)
    let l:result = []
    for l:candidate in a:candidates
      let l:filename = fnamemodify(l:candidate, ':p:t')
      let l:icon = WebDevIconsGetFileTypeSymbol(l:filename, isdirectory(l:filename))
      call add(l:result, printf('%s %s', l:icon, l:candidate))
    endfor
    return l:result
  endfunction

  function! s:edit_file(item)
    let l:pos = stridx(a:item, ' ')
    let l:file_path = a:item[l:pos+1:-1]
    execute 'silent e' l:file_path
  endfunction
endfunction

Then it can be called with a 1 or 0 if you want to search only the files tracked by git, or all files in the project

coreyja commented 5 years ago

Used @dkarter's comment as a starting point, and made some performance improvements and added some git diff support as well.

TLDR: Wrote a tool to do the devicon lookup in Rust (so it actually doesn't depend on this repo at all), and used bat for the previewing. The Rust lookup is about 10x faster than the VIM only implementation, and allows streaming before all results are populated. Directories that took ~4.5 seconds with the VIM implementation, finished near instantaneously with the Rust version.

You can install both with

cargo install bat
cargo install devicon-lookup

And here is the VIM config (also includes support for emulating :GFiles?):

" Files + devicons
function! Fzf_files_with_dev_icons(command)
  let l:fzf_files_options = '--preview "bat --color always --style numbers {2..} | head -'.&lines.'"'
   function! s:edit_devicon_prepended_file(item)
    let l:file_path = a:item[4:-1]
    execute 'silent e' l:file_path
  endfunction
   call fzf#run({
        \ 'source': a:command.' | devicon-lookup',
        \ 'sink':   function('s:edit_devicon_prepended_file'),
        \ 'options': '-m ' . l:fzf_files_options,
        \ 'down':    '40%' })
endfunction
 function! Fzf_git_diff_files_with_dev_icons()
  let l:fzf_files_options = '--ansi --preview "sh -c \"(git diff --color=always -- {3..} | sed 1,4d; bat --color always --style numbers {3..}) | head -'.&lines.'\""'
   function! s:edit_devicon_prepended_file_diff(item)
    echom a:item
    let l:file_path = a:item[7:-1]
    echom l:file_path
    let l:first_diff_line_number = system("git diff -U0 ".l:file_path." | rg '^@@.*\+' -o | rg '[0-9]+' -o | head -1")
     execute 'silent e' l:file_path
    execute l:first_diff_line_number
  endfunction
   call fzf#run({
        \ 'source': 'git -c color.status=always status --short --untracked-files=all | devicon-lookup',
        \ 'sink':   function('s:edit_devicon_prepended_file_diff'),
        \ 'options': '-m ' . l:fzf_files_options,
        \ 'down':    '40%' })
endfunction
 " Open fzf Files
map <C-f> :call Fzf_files_with_dev_icons($FZF_DEFAULT_COMMAND)<CR> " :Files
map <C-d> :call Fzf_git_diff_files_with_dev_icons()<CR> " :GFiles?
map <C-g> :call Fzf_files_with_dev_icons("git ls-files \| uniq")<CR> " :GFiles

See my blog post for the long form write up! https://coreyja.com/blog/2018/11/17/vim-fzf-with-devicons.html

jonasstenberg commented 5 years ago

@coreyja Looks great, but all icons show up as question marks. Any idea why?

coreyja commented 5 years ago

@jonasstenberg hmm do you have a nerd font compatible font installed? And do you see Dev icons elsewhere, assuming you have this, vim-devicons, plugin installed?

jonasstenberg commented 5 years ago

@coreyja

@jonasstenberg hmm do you have a nerd font compatible font installed?

I installed these fonts using brew, no luck though.

And do you see Dev icons elsewhere

Not sure where to look if I can see them elsewhere?

assuming you have this, vim-devicons, plugin installed?

vim-devicons is installed.

Thanks for the quick reply!

jonasstenberg commented 5 years ago

My bad, had to switch font in iTerm2 as well.

Awesome job with the devicons!

coreyja commented 5 years ago

@jonasstenberg Ahh! Glad you got it figured out! Hope you enjoy and let me know if you run into other issues!

mellery451 commented 5 years ago

@coreyja this is very cool, but it seems to fail for .txt files on my machine...I'm guessing because devicon-lookup is not finding a symbol for that file type (although I believe there is as devicon for CMakeLists.txt, however). How should this snippet behave when the icon lookup fails? The failure manifests specifically as trying to open a (nonexistent) path with the first two chars of the path stripped off. This is on macos, if it matters.

coreyja commented 5 years ago

@mellery451 ahh sorry you are running into issues. From your description of what happens it sounds like the code that is supposed to chop off the dev char is also chopping off some of your file name. Which is part of the vim script. Are you seeing this with the standard files view or with the git changed files version? I probably won't have time to look into this before the weekend but I'll try to take a look for ya!

Also I might move this little script to a repo, so that we could use the issue tracker and stop using this comment thread!

mellery451 commented 5 years ago

@coreyja I've only used the standard files view. I think part of the issue might be: https://github.com/coreyja/devicon-lookup/blob/master/src/main.rs#L103 which looks like it returns a single width char (x65 'e') for `txt' which confuses the strip-leading-widechar part of this vim code. Happy to move this discussion to another repo as you suggest. Thanks.

coreyja commented 5 years ago

@mellery451 Sorry for the delayed response! I created an issue over on my rust repo, and tagged you in a potential workaround (which I took from @dkarter in this thread)! Here is a link to that issue: https://github.com/coreyja/devicon-lookup/issues/2

TaDaa commented 5 years ago

Nice ty..glad I found this was really helpful. Noticed that the fzf default_actions (ctrl+x, ctrl+v) weren't working. Seems that is possible to just precall fzf#wrap({}), store the sink function and then modify the returned object. I also needed to change the split file_path index from 1 to 2, could just be me though.

modified @dkarter's code :

function! FZFWithDevIcons()
  function! s:files()
    let files = split(system('fd --type f'), '\n')
    return s:prepend_icon(files)
  endfunction

  function! s:prepend_icon(candidates)
    let result = []
    for candidate in a:candidates
      let filename = fnamemodify(candidate, ':p:t')
      let icon = WebDevIconsGetFileTypeSymbol(filename, isdirectory(filename))
      call add(result, printf("%s %s", icon, candidate))
    endfor

    return result
  endfunction

  function! s:edit_file(items)
    let items = a:items
    let i = 1
    let ln = len(items)
    while i < ln
      let item = items[i]
      let parts = split(item, ' ')
      let file_path = get(parts, 2, '')
      let items[i] = file_path
      let i += 1
    endwhile
    call s:Sink(items)
  endfunction

  let opts = fzf#wrap({})
  let opts.source = <sid>files()
  let s:Sink = opts['sink*']
  let opts['sink*'] = function('s:edit_file')
  call fzf#run(opts)

endfunction
micke commented 5 years ago

I've continued on the work of @TaDaa and the others. What i have now supports devicons, multiselect, preview with highlighting by bat, ctrl-d and ctrl-u for navigating preview up/down, ctrl-x,v,t bindings.

I'm not a big fan of how we are bending fzf to work with the custom sink calling the default sink this way. It feels very fragile. But i'm a total viml noob, so if anyone have a better solution i'm all ears.

function! FZFWithDevIcons()
  let l:fzf_files_options = ' -m --bind ctrl-d:preview-page-down,ctrl-u:preview-page-up --preview "bat --color always --style numbers {2..}"'

  function! s:files()
    let l:files = split(system($FZF_DEFAULT_COMMAND), '\n')
    return s:prepend_icon(l:files)
  endfunction

  function! s:prepend_icon(candidates)
    let result = []
    for candidate in a:candidates
      let filename = fnamemodify(candidate, ':p:t')
      let icon = WebDevIconsGetFileTypeSymbol(filename, isdirectory(filename))
      call add(result, printf("%s %s", icon, candidate))
    endfor

    return result
  endfunction

  function! s:edit_file(items)
    let items = a:items
    let i = 1
    let ln = len(items)
    while i < ln
      let item = items[i]
      let parts = split(item, ' ')
      let file_path = get(parts, 1, '')
      let items[i] = file_path
      let i += 1
    endwhile
    call s:Sink(items)
  endfunction

  let opts = fzf#wrap({})
  let opts.source = <sid>files()
  let s:Sink = opts['sink*']
  let opts['sink*'] = function('s:edit_file')
  let opts.options .= l:fzf_files_options
  call fzf#run(opts)

endfunction
blayz3r commented 5 years ago

bump

waigx commented 4 years ago

The biggest challenge here is to have the prepend icon runs asynchronously. Otherwise the prepend would be a long wait, depends on how many files in your directory.

ayoisaiah commented 4 years ago

I customised @micke's snippet to use @coreyja's devicon-lookup which results in significantly faster response for me.

function! FZFWithDevIcons()
  let l:fzf_files_options = ' -m --bind ctrl-d:preview-page-down,ctrl-u:preview-page-up --preview "bat --color always --style numbers {2..}"'

  function! s:files()
    let l:files = split(system($FZF_DEFAULT_COMMAND.'| devicon-lookup'), '\n')
    return l:files
  endfunction

  function! s:edit_file(items)
    let items = a:items
    let i = 1
    let ln = len(items)
    while i < ln
      let item = items[i]
      let parts = split(item, ' ')
      let file_path = get(parts, 1, '')
      let items[i] = file_path
      let i += 1
    endwhile
    call s:Sink(items)
  endfunction

  let opts = fzf#wrap({})
  let opts.source = <sid>files()
  let s:Sink = opts['sink*']
  let opts['sink*'] = function('s:edit_file')
  let opts.options .= l:fzf_files_options
  call fzf#run(opts)
endfunction
ayoisaiah commented 4 years ago

Is there a way to make this work with open buffers as well?

christopher-francisco commented 4 years ago

@waigx could we maybe use this for async? https://github.com/tpope/vim-dispatch

waigx commented 4 years ago

@chris-fran - I am using external devicon-lookup pipeline as suggested above. Will take a look at vim-dispatch. It would be nice to have it async without external binary.

roszczypalam commented 4 years ago

Is there a way to add devicons to :Ag search results (in fzf-vim plugin)? I am very satisfied with files searchinng with BAT but the last thing i wanna do is to search inside files with some BAT preview and devicons

coreyja commented 4 years ago

@roszczypalam There is now πŸ™ƒ

I'm back in this thread to announce a vim plugin that I put together again using my devicon-lookup tool.

The new plugin is fzf.devicon.vim :tada: It can be installed with your favorite vim package manager, though it does still depend on devicon-lookup being installed externally.

This plugin is a fork of fzf.vim and adds devicon support to each of the 'fileish' searches that it provided. Other fzf usages that you want to add devicons to are also welcome, and PRs and Issues are encouraged! While it is a fork, is made to be run side-by-side with fzf.vim as the commands are all named differently.

One of the new things is actually the grep support. I added prefix parsing into devicon-lookup meaning it is now able of parsing grep style results.

Besides the grep results, the functionality is pretty much the same as the other versions that have been shared here previously (so thanks to everyone for their contributions in this thread!). It supports all the the different ctrl variants when opening files and should be feature compatible with fzf.vim. Any missing features would be considered a bug (or an out of date fork) and issues and PRs would be appreciated!

Let me know what you guys think! Thanks!

blayz3r commented 4 years ago

@roszczypalam There is now πŸ™ƒ

I'm back in this thread to announce a vim plugin that I put together again using my devicon-lookup tool.

The new plugin is fzf.devicon.vim πŸŽ‰ It can be installed with your favorite vim package manager, though it does still depend on devicon-lookup being installed externally.

This plugin is a fork of fzf.vim and adds devicon support to each of the 'fileish' searches that it provided. Other fzf usages that you want to add devicons to are also welcome, and PRs and Issues are encouraged! While it is a fork, is made to be run side-by-side with fzf.vim as the commands are all named differently.

One of the new things is actually the grep support. I added prefix parsing into devicon-lookup meaning it is now able of parsing grep style results.

Besides the grep results, the functionality is pretty much the same as the other versions that have been shared here previously (so thanks to everyone for their contributions in this thread!). It supports all the the different ctrl variants when opening files and should be feature compatible with fzf.vim. Any missing features would be considered a bug (or an out of date fork) and issues and PRs would be appreciated!

Let me know what you guys think! Thanks!

Why not PR the main project?

coreyja commented 4 years ago

@blayz3r I thought about it and might still. The main reason I didn't is that it doesn't actually integrate into the fzf.vim plugin. It just provides a replacement/clone for the commands it provides. I decided that it would be easier to support a clone than it would be to support an insertion into the original code base, given the structure of the code and the nature of the problem at hand.

I wasn't sure this was in the spirit of this original repo, and I don't think maintaining a full fzf plugin within the original repo would be desirable.

Another reason is that it requires an external tool to function (even besides fzf itself).

But if @ryanoasis (and/or other maintainers) would like to include this in the original repo, I am MORE than happy to contribute it and help maintain it in this repo!

blayz3r commented 4 years ago

@blayz3r I thought about it and might still. The main reason I didn't is that it doesn't actually integrate into the fzf.vim plugin. It just provides a replacement/clone for the commands it provides. I decided that it would be easier to support a clone than it would be to support an insertion into the original code base, given the structure of the code and the nature of the problem at hand.

I wasn't sure this was in the spirit of this original repo, and I don't think maintaining a full fzf plugin within the original repo would be desirable.

Another reason is that it requires an external tool to function (even besides fzf itself).

But if @ryanoasis (and/or other maintainers) would like to include this in the original repo, I am MORE than happy to contribute it and help maintain it in this repo!

Makes sense I was imagining something like this https://github.com/kristijanhusak/defx-icons/blob/master/README.md. The plugins adds icons to Defx but doesn't force you to use new functions. But that is just my 2 cents.

ryanoasis commented 4 years ago

hey all, sorry for the delay in chiming in. :wave:

lots of good solutions here, I am open to any PRs and also very cool with people just creating their own forks or projects (that's what's cool about OSS right?). That said I would love it was supported out of the box and it looks like others have posted possible solutions here already..

coreyja commented 4 years ago

@ryanoasis Thanks for the reply!

So right now my solution (plus most of the others here that I am aware of) here don't really 'insert' icons into the original FZF commands. Instead we just created new VIM commands from the underlying piece (which is kinda what fzf.vim is on top of fzf).

I decided to rename my commands so as to not 'shadow' the original ones.

If you (@ryanoasis) are ok with maintaining (with help of course πŸ™ƒ ) my implementation (potentially with a shim to not need devicon-lookup ext tool) I would be happy to create a PR to this repo! I think it would basically be the same code I have, but instead of creating new command names it would just shadow the ones that already are exported by fzf.vim

yuki-yano commented 4 years ago

While we don't yet have full support for devicons, we are working on a plugin that provides various resources for FZF.

It uses Vim script and ripgrep to apply the devicons. https://github.com/yuki-ycino/fzf-preview.vim

γ‚Ήγ‚―γƒͺγƒΌγƒ³γ‚·γƒ§γƒƒγƒˆ 2020-04-15 18 30 06

blayz3r commented 3 years ago

Any update?

hadronized commented 3 years ago

Hey, it’s been 5 years people have been asking for this. I’m pretty sure lots of people would contribute to provide all the patches listed above. What’s your take on this @ryanoasis?