1

I use fzf.vim plugin and I want to map Ctrl-P:

  1. If the file is part of a git repo, then I want to use the :GFiles command (to show all files from the root directory of project).
  2. If there is no git repo, then I want to use :Files (to show files from the directory that contains the file).

I wrote this function. It executes git status and check if it succeeded; if so, it's a git repo, otherwise not.

function! MyFunc()
    " echo 'MyFunc() begin'
    let status = system("git status")
    if v:shell_error
        echo 'v:shell_error cmd'
        execute "normal! :Files<CR>"
    else
        echo 'else cmd'
        execute "normal! :GFiles<CR>"
    endif
    " echo 'MyFunc() end'
endfunction

However, it doesn't work, the function gets called, but the if and else statements are omitted.

5
  • Probably not the issue, but execute "normal! :Files<CR>" can just be Files (and similarly for GFiles). Have you tried :debug call MyFunc()?
    – D. Ben Knoble
    Aug 1, 2022 at 14:33
  • Change code to simply Files and GFiles and not it works! Thank you! Aug 1, 2022 at 14:47
  • Maybe could you accept you own answer using the v button next to the arrow voting buttons. It allow the question to rest :-) Aug 31, 2023 at 4:37
  • @VivianDeSmedt I don't know is it ok ? Because answer is my, but solution is not. Sep 4, 2023 at 14:16
  • 1
    The accept button is to indicate others that the solution provided solved your problem. It is a good indication that if you have the same problem you should look at that solution first ;-). In short yes feel free to accept it :-) Sep 4, 2023 at 14:33

1 Answer 1

2

Thanks D.Ben Knoble for help. Full code

function! MyFunc()
    let status = system("git status")
    if v:shell_error
        Files
    else
        GFiles
    endif
endfunction
3
  • Hm, perhaps you needed either :execute 'normal! :Files<CR>' (single quotes) or :execute "normal! :Files\<CR>" (escaped key-sequence in double-quotes).
    – D. Ben Knoble
    Aug 1, 2022 at 14:58
  • 1
    @D.BenKnoble Your first suggestion won't work as <key> notation is only expanded by :map or such. Neither execute nor normal do this. The second one will, because backslash inside double quotes allows for substs"
    – Matt
    Aug 1, 2022 at 15:34
  • 1
    @Matt yes, I think you are right, thanks for reminding me. One more reason to keep it simple with just the command :)
    – D. Ben Knoble
    Aug 1, 2022 at 15:35

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.