Issue #29 Command and file autocomplete
This commit is contained in:
parent
dfa44b5fa2
commit
7e1e03284a
4 changed files with 169 additions and 0 deletions
66
lib/autocomplete.coffee
Normal file
66
lib/autocomplete.coffee
Normal file
|
|
@ -0,0 +1,66 @@
|
|||
fs = require 'fs'
|
||||
path = require 'path'
|
||||
Ex = require './ex'
|
||||
|
||||
module.exports =
|
||||
class AutoComplete
|
||||
constructor: (commands) ->
|
||||
@commands = commands
|
||||
@resetCompletion()
|
||||
|
||||
resetCompletion: () ->
|
||||
@autoCompleteIndex = 0
|
||||
@autoCompleteText = null
|
||||
@completions = []
|
||||
|
||||
getAutocomplete: (text) ->
|
||||
if !@autoCompleteText
|
||||
@autoCompleteText = text
|
||||
|
||||
parts = @autoCompleteText.split(' ')
|
||||
cmd = parts[0]
|
||||
|
||||
if parts.length > 1
|
||||
filePath = parts.slice(1).join(' ')
|
||||
return @getCompletion(() => @getFilePathCompletion(cmd, filePath))
|
||||
else
|
||||
return @getCompletion(() => @getCommandCompletion(cmd))
|
||||
|
||||
filterByPrefix: (commands, prefix) ->
|
||||
commands.filter((f) => f.startsWith(prefix))
|
||||
|
||||
getCompletion: (completeFunc) ->
|
||||
if @completions.length == 0
|
||||
@completions = completeFunc()
|
||||
|
||||
if @completions.length
|
||||
complete = @completions[@autoCompleteIndex % @completions.length]
|
||||
@autoCompleteIndex++
|
||||
|
||||
# Only one result so lets return this directory
|
||||
if complete.endsWith('/') && @completions.length == 1
|
||||
@resetCompletion()
|
||||
|
||||
return complete
|
||||
|
||||
getCommandCompletion: (command) ->
|
||||
if @completions.length == 0
|
||||
return @filterByPrefix(@commands, command)
|
||||
|
||||
getFilePathCompletion: (command, filePath) ->
|
||||
if filePath.endsWith(path.sep)
|
||||
basePath = path.dirname(filePath + '.')
|
||||
baseName = ''
|
||||
else
|
||||
basePath = path.dirname(filePath)
|
||||
baseName = path.basename(filePath)
|
||||
|
||||
files = fs.readdirSync(basePath)
|
||||
|
||||
return @filterByPrefix(files, baseName).map((f) =>
|
||||
filePath = path.join(basePath, f)
|
||||
if fs.lstatSync(filePath).isDirectory()
|
||||
return command + ' ' + filePath + path.sep
|
||||
else
|
||||
return command + ' ' + filePath
|
||||
)
|
||||
Loading…
Add table
Add a link
Reference in a new issue