coc-java
coc-java copied to clipboard
Extract to variable and function
I've tried to extract to a variable or method and it seem this capabilities are not yet supported, would be great to have these
relates to https://github.com/eclipse/eclipse.jdt.ls/pull/381
relates to eclipse/eclipse.jdt.ls#381
Seems that the Language Server supports variable and method extraction. I don't know the internals of coc-java or any other Language Client, but should it actually not work out of the box? Nevertheless I do not get the option to extract the selected code.
Do you have coc-codeaction-selected mapped in your config?
From the coc.nvim README example config or :help coc-codeaction-selected:
" 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)
If I select a region of code that can be extracted to a method I get the option. Sometimes the region can't be extracted due to how variables are scoped and I don't get the extract option. Usually I can simply increase the size of region selected to fix the problem or refactor the code to fix scoping issues.
In the screenshot below, I've typed the keys ,a$ on line 5 and received Extract to method as an option.
The result is:

Do you have
coc-codeaction-selectedmapped in your config?From the coc.nvim README example config or
:help coc-codeaction-selected:" 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)If I select a region of code that can be extracted to a method I get the option. Sometimes the region can't be extracted due to how variables are scoped and I don't get the extract option. Usually I can simply increase the size of region selected to fix the problem or refactor the code to fix scoping issues.
In the screenshot below, I've type the keys
,a$on line 5 and receivedExtract to methodas an option.The result is:
I am sorry, works exactly as you have described. My selected region could somehow not be extracted. Do you use a keybinding to extend or reduce the region?
I'm assuming coc-range-select and coc-range-select-backward is the equivalent to the eclipse shortcut Alt+Shit+Up/Down.
It works quite reasonably but is far away from the Eclipse quality.
For visual selection expansion then o and O are your friends. See :help v_o. I often use a motion key for the selection such as <leader>aap.
Should be fixed on recent version of coc-java, try upgrade coc.nvim to latest release and coc-java to version 1.14.0.
Request refactor code actions is recommanded like:
" Remap keys for applying refactor code actions
nmap <silent> <leader>re <Plug>(coc-codeaction-refactor)
xmap <silent> <leader>r <Plug>(coc-codeaction-refactor-selected)
nmap <silent> <leader>r <Plug>(coc-codeaction-refactor-selected)