yaegassy / coc-ansible

ansible-language-server extension for coc.nvim
https://www.npmjs.com/package/@yaegassy/coc-ansible
MIT License
71 stars 3 forks source link

trouble getting autocompletion to work with #15

Closed haroonb closed 2 years ago

haroonb commented 2 years ago

Hello I'm trying to get the autocompletion to work with vim. However I can't seem to get anything to autocomplete. As I understand it, I should be able to use the autocomplete feature with crtl+, but nothing happens, nor do I get any suggestions for modules or arguments inside modules.

   vim version: VIM - Vi IMproved 8.1 8013741
   node version: v16.14.0
   coc.nvim version: 0.0.80-c7d7756089
   coc.nvim directory: /home/butt/.vim/plugged/coc.nvim
   term: dumb
   platform: linux

   ## Log of coc.nvim 
  2022-02-28T13:31:01.289 INFO (pid:224482) [plugin] - coc.nvim initialized with node: v16.14.0 after 91ms 
  2022-02-28T13:31:05.354 INFO (pid:224482) [attach] - receive notification: showInfo [] ```
  ansible [core 2.12.2]
  config file = /etc/ansible/ansible.cfg
  configured module search path = ['/home/butt/.ansible/plugins/modules', '/usr/share/ansible/plugins/modules']
  ansible python module location = /usr/lib/python3/dist-packages/ansible
  ansible collection location = /home/butt/.ansible/collections:/usr/share/ansible/collections
  executable location = /usr/bin/ansible
  python version = 3.8.10 (default, Nov 26 2021, 20:14:08) [GCC 9.3.0]
  jinja version = 2.10.1
  libyaml = True
pip list | grep lint
ansible-lint           5.4.0
.vim/
├── autoload
└── plugged
    ├── ansible-vim
    │   ├── ftdetect
    │   ├── ftplugin
    │   ├── indent
    │   ├── syntax
    │   └── UltiSnips
    ├── coc-ansible
    │   └── src
    │       └── features
    ├── coc.nvim
    │   ├── autoload
    │   │   ├── coc
    │   │   └── health
    │   ├── bin
    │   ├── build
    │   ├── data
    │   ├── doc
    │   └── plugin
    └── indentLine
        ├── after
        │   ├── plugin
        │   └── syntax
        ├── doc
        └── glyph
" configuration for coc-ansible
let g:coc_filetype_map = {
  \ 'yaml.ansible': 'ansible',
  \ }
let data_dir = has('nvim') ? stdpath('data') . '/site' : '~/.vim'
if empty(glob(data_dir . '/autoload/plug.vim'))
  silent execute '!curl -fLo '.data_dir.'/autoload/plug.vim --create-dirs  https://raw.githubusercontent.com/junegunn/vim-plug/master/plug.vim'
  autocmd VimEnter * PlugInstall --sync | source $MYVIMRC
endif
" Install vim-plug if not found
if empty(glob('~/.vim/autoload/plug.vim'))
  silent !curl -fLo ~/.vim/autoload/plug.vim --create-dirs
    \ https://raw.githubusercontent.com/junegunn/vim-plug/master/plug.vim
endif

" Run PlugInstall if there are missing plugins
autocmd VimEnter * if len(filter(values(g:plugs), '!isdirectory(v:val.dir)'))
  \| PlugInstall --sync | source $MYVIMRC
\| endif
call plug#begin()
" The default plugin directory will be as follows:
"   - Vim (Linux/macOS): '~/.vim/plugged'
" You can specify a custom plugin directory by passing it as the argument
"   - e.g. `call plug#begin('~/.vim/plugged')`
"   - Avoid using standard Vim directory names like 'plugin'

" visibility for indents https://github.com/Yggdroot/indentLine
Plug 'Yggdroot/indentLine'

" ansible syntax plugin https://github.com/pearofducks/ansible-vim
Plug 'pearofducks/ansible-vim', { 'do': './UltiSnips/generate.sh' }

" Make your Vim/Neovim as smart as VSCode ~ autocompletion ~ https://github.com/neoclide/coc.nvim
Plug 'neoclide/coc.nvim', {'branch': 'release'}

" ansible autocompletion ~ language server ~ https://github.com/yaegassy/coc-ansible
Plug 'yaegassy/coc-ansible', {'do': 'yarn install --frozen-lockfile'}

call plug#end()

" configuration for pearofducks/ansible-vim https://github.com/pearofducks/ansible-vim
autocmd BufRead,BufNewFile *.yaml  set filetype=yaml.ansible
autocmd BufNewFile *.yaml 0r ~/.vim/template.yaml

" configguration for playbooks
autocmd BufRead,BufNewFile *.yaml setlocal expandtab tabstop=2 autoindent shiftwidth=2 softtabstop=0 foldmethod=syntax
autocmd BufRead,BufNewFile * colorscheme desert
set cursorline paste relativenumber number

" ####################################################################################################
" ####################################################################################################
" coc configuration part https://github.com/neoclide/coc.nvim
" Set internal encoding of vim, not needed on neovim, since coc.nvim using some
" unicode characters in the file autoload/float.vim
set encoding=utf-8

" TextEdit might fail if hidden is not set.
set hidden

" Some servers have issues with backup files, see #649.
set nobackup
set nowritebackup

" Give more space for displaying messages.
set cmdheight=2

" Having longer updatetime (default is 4000 ms = 4 s) leads to noticeable
" delays and poor user experience.
set updatetime=300

" Don't pass messages to |ins-completion-menu|.
set shortmess+=c

" Always show the signcolumn, otherwise it would shift the text each time
" diagnostics appear/become resolved.
if has("nvim-0.5.0") || has("patch-8.1.1564")
  " Recently vim can merge signcolumn and number column into one
  set signcolumn=number
else
  set signcolumn=yes
endif

" Use tab for trigger completion with characters ahead and navigate.
" NOTE: Use command ':verbose imap <tab>' to make sure tab is not mapped by
" other plugin before putting this into your config.
inoremap <silent><expr> <TAB>
      \ pumvisible() ? "\<C-n>" :
      \ <SID>check_back_space() ? "\<TAB>" :
      \ coc#refresh()
inoremap <expr><S-TAB> pumvisible() ? "\<C-p>" : "\<C-h>"

function! s:check_back_space() abort
  let col = col('.') - 1
  return !col || getline('.')[col - 1]  =~# '\s'
endfunction

" Use <c-space> to trigger completion.
if has('nvim')
  inoremap <silent><expr> <c-space> coc#refresh()
else
  inoremap <silent><expr> <c-@> coc#refresh()
endif

" Make <CR> auto-select the first completion item and notify coc.nvim to
" format on enter, <cr> could be remapped by other vim plugin
inoremap <silent><expr> <cr> pumvisible() ? coc#_select_confirm()
                              \: "\<C-g>u\<CR>\<c-r>=coc#on_enter()\<CR>"

" Use `[g` and `]g` to navigate diagnostics
" Use `:CocDiagnostics` to get all diagnostics of current buffer in location list.
nmap <silent> [g <Plug>(coc-diagnostic-prev)
nmap <silent> ]g <Plug>(coc-diagnostic-next)

" GoTo code navigation.
nmap <silent> gd <Plug>(coc-definition)
nmap <silent> gy <Plug>(coc-type-definition)
nmap <silent> gi <Plug>(coc-implementation)
nmap <silent> gr <Plug>(coc-references)

" Use K to show documentation in preview window.
nnoremap <silent> K :call <SID>show_documentation()<CR>

function! s:show_documentation()
  if (index(['vim','help'], &filetype) >= 0)
    execute 'h '.expand('<cword>')
  elseif (coc#rpc#ready())
    call CocActionAsync('doHover')
  else
    execute '!' . &keywordprg . " " . expand('<cword>')
  endif
endfunction

" Highlight the symbol and its references when holding the cursor.
autocmd CursorHold * silent call CocActionAsync('highlight')

" Symbol renaming.
nmap <leader>rn <Plug>(coc-rename)

" Formatting selected code.
xmap <leader>f  <Plug>(coc-format-selected)
nmap <leader>f  <Plug>(coc-format-selected)

augroup mygroup
  autocmd!
  " Setup formatexpr specified filetype(s).
  autocmd FileType typescript,json setl formatexpr=CocAction('formatSelected')
  " Update signature help on jump placeholder.
  autocmd User CocJumpPlaceholder call CocActionAsync('showSignatureHelp')
augroup end

" Applying codeAction to the selected region.
" Example: `<leader>aap` for current paragraph
xmap <leader>a  <Plug>(coc-codeaction-selected)
nmap <leader>a  <Plug>(coc-codeaction-selected)

" Remap keys for applying codeAction to the current buffer.
nmap <leader>ac  <Plug>(coc-codeaction)
" Apply AutoFix to problem on the current line.
nmap <leader>qf  <Plug>(coc-fix-current)

" Run the Code Lens action on the current line.
nmap <leader>cl  <Plug>(coc-codelens-action)

" Map function and class text objects
" NOTE: Requires 'textDocument.documentSymbol' support from the language server.
xmap if <Plug>(coc-funcobj-i)
omap if <Plug>(coc-funcobj-i)
xmap af <Plug>(coc-funcobj-a)
omap af <Plug>(coc-funcobj-a)
xmap ic <Plug>(coc-classobj-i)
omap ic <Plug>(coc-classobj-i)
xmap ac <Plug>(coc-classobj-a)
omap ac <Plug>(coc-classobj-a)

" Remap <C-f> and <C-b> for scroll float windows/popups.
if has('nvim-0.4.0') || has('patch-8.2.0750')
  nnoremap <silent><nowait><expr> <C-f> coc#float#has_scroll() ? coc#float#scroll(1) : "\<C-f>"
  nnoremap <silent><nowait><expr> <C-b> coc#float#has_scroll() ? coc#float#scroll(0) : "\<C-b>"
  inoremap <silent><nowait><expr> <C-f> coc#float#has_scroll() ? "\<c-r>=coc#float#scroll(1)\<cr>" : "\<Right>"
  inoremap <silent><nowait><expr> <C-b> coc#float#has_scroll() ? "\<c-r>=coc#float#scroll(0)\<cr>" : "\<Left>"
  vnoremap <silent><nowait><expr> <C-f> coc#float#has_scroll() ? coc#float#scroll(1) : "\<C-f>"
  vnoremap <silent><nowait><expr> <C-b> coc#float#has_scroll() ? coc#float#scroll(0) : "\<C-b>"
endif

" Use CTRL-S for selections ranges.
" Requires 'textDocument/selectionRange' support of language server.
nmap <silent> <C-s> <Plug>(coc-range-select)
xmap <silent> <C-s> <Plug>(coc-range-select)

" Add `:Format` command to format current buffer.
command! -nargs=0 Format :call CocActionAsync('format')

" Add `:Fold` command to fold current buffer.
command! -nargs=? Fold :call     CocAction('fold', <f-args>)

" Add `:OR` command for organize imports of the current buffer.
command! -nargs=0 OR   :call     CocActionAsync('runCommand', 'editor.action.organizeImport')

" Add (Neo)Vim's native statusline support.
" NOTE: Please see `:h coc-status` for integrations with external plugins that
" provide custom statusline: lightline.vim, vim-airline.
set statusline^=%{coc#status()}%{get(b:,'coc_current_function','')}

" Mappings for CoCList
" Show all diagnostics.
nnoremap <silent><nowait> <space>a  :<C-u>CocList diagnostics<cr>
" Manage extensions.
nnoremap <silent><nowait> <space>e  :<C-u>CocList extensions<cr>
" Show commands.
nnoremap <silent><nowait> <space>c  :<C-u>CocList commands<cr>
" Find symbol of current document.
nnoremap <silent><nowait> <space>o  :<C-u>CocList outline<cr>
" Search workspace symbols.
nnoremap <silent><nowait> <space>s  :<C-u>CocList -I symbols<cr>
" Do default action for next item.
nnoremap <silent><nowait> <space>j  :<C-u>CocNext<CR>
" Do default action for previous item.
nnoremap <silent><nowait> <space>k  :<C-u>CocPrev<CR>
" Resume latest coc list.
nnoremap <silent><nowait> <space>p  :<C-u>CocListResume<CR>
" ####################################################################################################
" ####################################################################################################
yaegassy commented 2 years ago

It looks like your .vimrc is keymap to ctrl+space instead of crtl+,. Try ctrl+space.

haroonb commented 2 years ago

Hello, thanks for the quick reply. I tried using crtl+space. I also wrote that in the initial post, but I wrote it like crtl+<space> and the space part dissapeared, my bad. As I understand the plugin I should be getting module suggestions as I write module names and such.

The part, that still confuses me is, if i need a coc-settings.json, if I installed the plugin using :CocInstall @yaegassy/coc-ansible

yaegassy commented 2 years ago

coc-settings.json is not required. Is it only "auto-completion" that is not working? Are the "diagnostics" working?

There may be a problem with your ansible project or your python environment. Try it once in a virtual environment such as venv.

Example

Prepare:

mkdir -p $HOME/coc-ansible-check
cd $HOME/coc-ansible-check python3 -m venv venv
source venv/bin/activate
pip install ansible ansible-lint

Edit:

vim site.yml

or

mkdir -p roles/tasks/dummy/
vim roles/dummy/tasks/main.yml
haroonb commented 2 years ago

Hello, the issue still persists in the virtual env.

butt@ansible-controller:~/branch1/ansible_playbooks$ mkdir -p $HOME/coc-ansible-check
butt@ansible-controller:~/branch1/ansible_playbooks$ cd $HOME/coc-ansible-check
butt@ansible-controller:~/coc-ansible-check$ python3 -m venv venv
butt@ansible-controller:~/coc-ansible-check$ source venv/bin/activate
(venv) butt@ansible-controller:~/coc-ansible-check$ sudo pip install ansible ansible-lint
Requirement already satisfied: ansible in /usr/lib/python3/dist-packages (5.3.0)
Requirement already satisfied: ansible-lint in /usr/local/lib/python3.8/dist-packages (5.4.0)
Requirement already satisfied: ansible-core~=2.12.2 in /usr/lib/python3/dist-packages (from ansible) (2.12.2)
Requirement already satisfied: tenacity in /usr/local/lib/python3.8/dist-packages (from ansible-lint) (8.0.1)
Requirement already satisfied: rich>=9.5.1 in /usr/local/lib/python3.8/dist-packages (from ansible-lint) (11.2.0)
Requirement already satisfied: packaging in /usr/lib/python3/dist-packages (from ansible-lint) (20.3)
Requirement already satisfied: ruamel.yaml<1,>=0.15.37; python_version >= "3.7" in /usr/local/lib/python3.8/dist-packages (from ansible-lint) (0.17.21)
Requirement already satisfied: enrich>=1.2.6 in /usr/local/lib/python3.8/dist-packages (from ansible-lint) (1.2.7)
Requirement already satisfied: pyyaml in /usr/local/lib/python3.8/dist-packages (from ansible-lint) (6.0)
Requirement already satisfied: wcmatch>=7.0 in /usr/local/lib/python3.8/dist-packages (from ansible-lint) (8.3)
Requirement already satisfied: resolvelib<0.6.0,>=0.5.3 in /usr/lib/python3/dist-packages (from ansible-core~=2.12.2->ansible) (0.5.4)
Requirement already satisfied: commonmark<0.10.0,>=0.9.0 in /usr/local/lib/python3.8/dist-packages (from rich>=9.5.1->ansible-lint) (0.9.1)
Requirement already satisfied: colorama<0.5.0,>=0.4.0 in /usr/lib/python3/dist-packages (from rich>=9.5.1->ansible-lint) (0.4.3)
Requirement already satisfied: pygments<3.0.0,>=2.6.0 in /usr/local/lib/python3.8/dist-packages (from rich>=9.5.1->ansible-lint) (2.11.2)
Requirement already satisfied: ruamel.yaml.clib>=0.2.6; platform_python_implementation == "CPython" and python_version < "3.11" in /usr/local/lib/python3.8/dist-packages (from ruamel.yaml<1,>=0.15.37; python_version >= "3.7"->ansible-lint) (0.2.6)
Requirement already satisfied: bracex>=2.1.1 in /usr/local/lib/python3.8/dist-packages (from wcmatch>=7.0->ansible-lint) (2.2.1)
(venv) butt@ansible-controller:~/coc-ansible-check$ vim site.yml

The ansible-lint seems to work. image

When I enter ctrl+space I get this, don't know if this helps image

yaegassy commented 2 years ago

ctrl+space forcefully invokes completion, but I think just typing it in the first place will complete it to some extent....

I tried it in my environment. I usually use Neovim, but I tried it with Vim8 (v8.2.4478).


DEMO (mp4):

https://user-images.githubusercontent.com/188642/156018579-e8a31f10-8400-4c7c-ae8d-59155820510c.mp4


If you can, please update Vim to the latest version and try it.

haroonb commented 2 years ago

Can you maybe share your .vimrc with me?

I installed the latest vim and still didn't help

VIM - Vi IMproved 8.2 (2019 Dec 12, compiled Sep 28 2021 11:18:09)
Included patches: 1-3458
Modified by jonathon.fernyhough@york.ac.uk
Compiled by jonathon.fernyhough@york.ac.uk
Huge version without GUI.  Features included (+) or not (-):
+acl               +file_in_path      +mouse_urxvt       -tag_any_white
+arabic            +find_in_path      +mouse_xterm       -tcl
+autocmd           +float             +multi_byte        +termguicolors
+autochdir         +folding           +multi_lang        +terminal
-autoservername    -footer            -mzscheme          +terminfo
-balloon_eval      +fork()            +netbeans_intg     +termresponse
+balloon_eval_term +gettext           +num64             +textobjects
-browse            -hangul_input      +packages          +textprop
++builtin_terms    +iconv             +path_extra        +timers
+byte_offset       +insert_expand     -perl              +title
+channel           +ipv6              +persistent_undo   -toolbar
+cindent           +job               +popupwin          +user_commands
-clientserver      +jumplist          +postscript        +vartabs
-clipboard         +keymap            +printer           +vertsplit
+cmdline_compl     +lambda            +profile           +virtualedit
+cmdline_hist      +langmap           -python            +visual
+cmdline_info      +libcall           +python3           +visualextra
+comments          +linebreak         +quickfix          +viminfo
+conceal           +lispindent        +reltime           +vreplace
+cryptv            +listcmds          +rightleft         +wildignore
+cscope            +localmap          -ruby              +wildmenu
+cursorbind        -lua               +scrollbind        +windows
+cursorshape       +menu              +signs             +writebackup
+dialog_con        +mksession         +smartindent       -X11
+diff              +modify_fname      -sodium            -xfontset
+digraphs          +mouse             +sound             -xim
-dnd               -mouseshape        +spell             -xpm
-ebcdic            +mouse_dec         +startuptime       -xsmp
+emacs_tags        +mouse_gpm         +statusline        -xterm_clipboard
+eval              -mouse_jsbterm     -sun_workshop      -xterm_save
+ex_extra          +mouse_netterm     +syntax
+extra_search      +mouse_sgr         +tag_binary
-farsi             -mouse_sysmouse    -tag_old_static
   system vimrc file: "$VIM/vimrc"
     user vimrc file: "$HOME/.vimrc"
 2nd user vimrc file: "~/.vim/vimrc"
      user exrc file: "$HOME/.exrc"
       defaults file: "$VIMRUNTIME/defaults.vim"
  fall-back for $VIM: "/usr/share/vim"
Compilation: gcc -c -I. -Iproto -DHAVE_CONFIG_H -Wdate-time -g -O2 -fdebug-prefix-map=/build/vim-sZb2J1/vim-8.2.3458=. -fstack-protector-strong -Wformat -Werror=format-security -D_REENTRANT -U_FORTIFY_SOURCE -D_FORTIFY_SOURCE=1
Linking: gcc -Wl,-Bsymbolic-functions -Wl,-z,relro -Wl,-z,now -Wl,--as-needed -o vim -lm -ltinfo -lselinux -lcanberra -lacl -lattr -lgpm -ldl -L/usr/lib/python3.8/config-3.8-x86_64-linux-gnu -lpython3.8 -lcrypt -lpthread -ldl -lutil -lm -lm
yaegassy commented 2 years ago

I've prepared a small .vimrc.

mini.vim:

call plug#begin('/tmp/plugged')
Plug 'neoclide/coc.nvim', {'branch': 'release'}
Plug 'sheerun/vim-polyglot'
Plug 'yaegassy/coc-ansible', {'do': 'yarn install --frozen-lockfile'}
call plug#end()

syntax on
filetype plugin indent on
set hidden

if has('nvim')
  inoremap <silent><expr> <c-space> coc#refresh()
else
  inoremap <silent><expr> <c-@> coc#refresh()
endif

let g:coc_filetype_map = {
  \ 'yaml.ansible': 'ansible',
  \ }

It worked fine in my environment. (vim -Nu mini.vim)

coc-ansible-issue15-2
yaegassy commented 2 years ago

@haroonb I noticed in your png file that you are getting the error E29: No inserted text yet. Perhaps this is because ctrl+space is not mapped correctly.

This may be a problem with Vim8 or the terminal emulator you are using. Google search for "vim8 c-space" may help you find the solution.

If you change the mapping in this way, does it change the behavior?

"if has('nvim')
"  inoremap <silent><expr> <c-space> coc#refresh()
"else
"  inoremap <silent><expr> <c-@> coc#refresh()
"endif

inoremap <silent><expr> <c-space> coc#refresh()
haroonb commented 2 years ago

Thanks for the support.

I tried it in a virtual env, with your suggested .vimrc on another server, but that didn't help. crtl+space didn't do anything with the normal mapping or inoremap <silent><expr> <c-space> coc#refresh(). not even a error.

I also tried the same on my original configuration, with the same result.

I switched my terminal emulator for mobaXterm to the windows integrated ssh over the cmd and that didn't help either.

If you don't have any more ideas I would close this issue, because it seems to work for you, so the error must be on my side.

yaegassy commented 2 years ago

I have no ideas. 🙇

haroonb commented 2 years ago

I found out what the issue was. The autocompletion doesn't work with set paste. If I take that out of the .vimrc everthing works. Is this a bug or working as intended?

yaegassy commented 2 years ago

I found this article. https://www.reddit.com/r/neovim/comments/hm58yi/set_paste_no_cocnvim_completion_menu_with_it/