Skip to content

Commit 8f07474

Browse files
committed
Added tab completing subcommands to help command
1 parent 380924b commit 8f07474

1 file changed

Lines changed: 32 additions & 0 deletions

File tree

cmd2.py

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1332,6 +1332,38 @@ def complete(self, text, state):
13321332
except IndexError:
13331333
return None
13341334

1335+
def complete_help(self, text, line, begidx, endidx):
1336+
"""
1337+
Override of parent class method to handle tab completing subcommands
1338+
"""
1339+
completions = []
1340+
1341+
# Get all tokens prior to text being completed
1342+
try:
1343+
tokens = shlex.split(line[:begidx], posix=POSIX_SHLEX)
1344+
except ValueError:
1345+
# Invalid syntax for shlex (Probably due to missing closing quote)
1346+
return completions
1347+
1348+
# If we have "help" and a completed command token, then attempt to match subcommands
1349+
if len(tokens) == 2:
1350+
1351+
# Match subcommands if any exist
1352+
subcommands = self.get_subcommands(tokens[1])
1353+
if subcommands is not None:
1354+
completions = [cur_sub for cur_sub in subcommands if cur_sub.startswith(text)]
1355+
1356+
# Run normal help completion from the parent class
1357+
else:
1358+
completions = cmd.Cmd.complete_help(self, text, line, begidx, endidx)
1359+
1360+
# If only 1 command has been matched and it's at the end of the line,
1361+
# then add a space if it has subcommands
1362+
if len(completions) == 1 and endidx == len(line) and self.get_subcommands(completions[0]) is not None:
1363+
completions[0] += ' '
1364+
1365+
return completions
1366+
13351367
def precmd(self, statement):
13361368
"""Hook method executed just before the command is processed by ``onecmd()`` and after adding it to the history.
13371369

0 commit comments

Comments
 (0)