-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathcompleter.js
76 lines (72 loc) · 2.28 KB
/
completer.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
/*
###
Completer plugin
================
Provides tab completion. Options passed during creation are:
- `shell` , (required) A reference to your shell application.
###
module.exports = (settings) ->
# Validation
throw new Error 'No shell provided' if not settings.shell
shell = settings.shell
# Plug completer to interface
return unless shell.isShell
shell.interface().completer = (text, cb) ->
suggestions = []
routes = shell.routes
for route in routes
command = route.command
if command.substr(0, text.length) is text
suggestions.push command
cb(false, [suggestions, text])
null
*/
const longestCommonPrefix = require('./longest-common-prefix')
function processSuggestions (suggestions, startkey, text, cb) {
if (suggestions.length) {
const prefix = longestCommonPrefix(suggestions).substring(startkey.length)
if (prefix.length) { // one common prefix, so complete it
suggestions = [text + prefix]
}
}
cb(null, [suggestions, text])
}
module.exports = function (settings) {
if (!settings.shell) {
throw new Error('No shell provided')
}
if (!settings.appsettings) {
throw new Error('No appsettings provided')
}
const shell = settings.shell
const appsettings = settings.appsettings
if (!shell.isShell) {
return
}
shell.interface().completer = function (text, cb) {
// first let's see if the command has spaces in
const bits = text.split(' ')
// if we have no space, then we haven't finished typing the command - so we want command auto-completion
if (bits.length === 1) {
const suggestions = []
const routes = shell.routes
for (const i in routes) {
const command = routes[i].command
if (command.substr(0, text.length) === text) {
suggestions.push(command)
}
}
cb(null, [suggestions, text])
} else {
// if we are in a sub-directory, we want documentid auto-completion
const startkey = bits[1]
if (startkey && appsettings.autocomplete.length > 0) {
let suggestions = JSON.parse(JSON.stringify(appsettings.autocomplete))
suggestions = suggestions.filter(v => v.startsWith(startkey))
processSuggestions(suggestions, startkey, text, cb)
} else {
cb(null, [[], text])
}
}
}
}