Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python cmd on linux does not autocomplete special characters or symbols

Characters such as - , + etc are not parsed the same way as alphanumeric ASCII characters by Python's readline based cmd module. This seems to be linux specific issue only, as it seems to work as expected on Mac OS.

Sample code

import cmd

class Test(cmd.Cmd):
    def do_abc(self, line):
        print line 
    def complete_abc(self, text, line, begidx, endidx):
        return [i for i in ['-xxx', '-yyy', '-zzz'] if i.startswith(text)]

try:
    import readline
except ImportError:
    print "Module readline not available."
else:
    import rlcompleter
    if 'libedit' in readline.__doc__:
        readline.parse_and_bind("bind ^I rl_complete")
    else:
        readline.parse_and_bind("tab: complete")

Test().cmdloop()

Expected behavior on Mac OS

(Cmd) abc <TAB>
abc  
(Cmd) abc -<TAB>
-xxx  -yyy  -zzz  
(Cmd) abc -x<TAB>
(Cmd) abc -xxx

Incorrect behavior on Linux

(Cmd) abc <TAB>
abc  
(Cmd) abc -x<TAB>
 <Nothing>
(Cmd) abc -<TAB> 
(Cmd) abc --<TAB>
(Cmd) abc ---<TAB>
(Cmd) abc ----

I tried adding - to cmd.Cmd.identchars, but it didn't help.

cmd.Cmd.identchars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_-'

Why is there a difference in readline parsing between Mac OS and Linux even though both use GNU readline:

Mac OS:

>>> readline.__doc__
'Importing this module enables command line editing using GNU readline.'

Linux:

>>> readline.__doc__
'Importing this module enables command line editing using GNU readline.'

Thanks!

like image 453
rajivRaja Avatar asked Dec 04 '14 07:12

rajivRaja


1 Answers

On linux, the readline module considers - a delimiter for tab completion. That is, after a - is encountered a fresh completion will be tried.

The solution to your problem is the remove - from the set of characters used by readline as delimiters.

eg.

old_delims = readline.get_completer_delims()
readline.set_completer_delims(old_delims.replace('-', ''))
like image 140
Dunes Avatar answered Oct 03 '22 02:10

Dunes