From 264efd151c6695d242418ad7e9e4f40595892224 Mon Sep 17 00:00:00 2001 From: Kevin S Kirkup Date: Mon, 26 Aug 2019 17:49:56 -0400 Subject: [PATCH] Add Python function for for sorting imports on file save It scans the from the top of the file looking for the first import and will sort all imports listed until a blank space is encountered. --- ftplugin/kotlin.vim | 48 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 48 insertions(+) diff --git a/ftplugin/kotlin.vim b/ftplugin/kotlin.vim index 95b5655..2ae0618 100644 --- a/ftplugin/kotlin.vim +++ b/ftplugin/kotlin.vim @@ -3,3 +3,51 @@ let b:did_ftplugin = 1 setlocal comments=:// setlocal commentstring=//\ %s + +" Function to sort import statements in Kotlin file +python3 << EOL +import re +def SortImports(): + """Sort the imports from the buffer """ + + buffer_lines = vim.current.buffer + + start = 0 + end = 0 + + for i, value in enumerate(buffer_lines): + + + if re.match("^$", buffer_lines[i]): + + # If we have reached the imports yet, just set the start index to current line + if end == 0: + start = i + + # We are at the end + else: + break + + if re.match("^import ", buffer_lines[i]): + end = i + + # Start is currently a blank line. + # Move it to the first import statement + start = start + 1 + + # End is at the last line, we want this to be the blank + # line after the import list + end = end + 1 + + # Sort the lines in the provided range + imports = sorted(buffer_lines[start:end]) + + # Replace the lines + for i, value in enumerate(imports): + buffer_lines[i + start] = value + +EOL +map :python3 SortImports() + +autocmd BufWrite *.kt :python3 SortImports() +