kotlin-language-server
kotlin-language-server copied to clipboard
"Organize Imports" action
Create a command to automatically import/unimport symbols.
It seems that ktlint can already clean up imports while formatting. How about utilizing it in the project as an optional formatter?
There seems to be some upstream support in LSP for organizing imports, see the docs on code actions (specifically the source.organizeImports
code action kind). Not sure if this directly maps to VSCode's built-in editor.action.organizeImports
, which binds to Shift + Alt + O by default, this would be something worth investigating.
I’m currently using a Quick Fix hack to make this happen, but is there any news on the proper implementation of this?
I’m currently using a Quick Fix hack to make this happen, but is there any news on the proper implementation of this?
There is a quick fix included to add missing imports. Other than that, I don't know... The activity in this project is fairly low, and the chief maintainer doesn't seem to have time for it. (+ strong opinions on how things should be, so I have grown weary of merging bigger PRs because of it). I have lost most of my motivation to work on it, and I think the same applies to many of our former contributors.
Feel free to try to implement a version yourself 😄 Also, feel free to share your quick fix hack! It might help other people. From experience, I know that it is the small hacks and extensions in editors that make this language server more usable.
function! ApplyImportQuickFixes()
let l:currentCursorPosition = getcurpos()
let l:addedImports = {}
while 1
let l:quickfixes = CocAction('quickfixes')
let l:importQuickfixes = filter(l:quickfixes, 'v:val.title =~ "^Import "')
if len(l:importQuickfixes) <= 0
break
endif
let l:importTitle = l:importQuickfixes[0].title
if has_key(l:addedImports, l:importTitle)
continue
endif
let l:addedImports[l:importTitle] = 1
call cursor(l:importQuickfixes[0].diagnostics[0].range.start.line + 1, l:importQuickfixes[0].diagnostics[0].range.start.character + 1)
call CocAction('doQuickfix', l:importQuickfixes[0])
endwhile
call setpos('.', l:currentCursorPosition)
endfunction
autocmd BufWritePre *.kt call ApplyImportQuickFixes()
I hope it's not too out of scope to post it here. And again it's not ideal and untested. Using Vim 8.x with coc.nvim and coc-kotlin.
As far as contributing goes, I might just try to cobble something together, but even if I manage I highly doubt it will be adequate enough for a pull request.
Thank you for the swift response and the insight!