1

I am using GDB's built in Python support. In my case Python will provide a specialized interface to the user. Internally the application will call various GDB functions to perform actions on a C library.

When using the GDB shell GDB provides very nice tab completion. But I would like to use the Python API.

I would like to present command completions depending on the user input. Ideally I would like to call a GDB function with a partial string. GDB should then return the possible completions.

Is there a Python API which I can use to perform completions?

1 Answer 1

2

Yes, there is a Python API. It is documented here under the function Command.complete (text, word)

The default completer will do filename and sub-command completion but you can extend that by providing your own custom complete method. Here is an example:

class MyGdbCommand(gdb.Command):
    def __init__(self):
        super().__init__("mycmd", gdb.COMMAND_USER) # or whatever command class you deem appropriate

    def complete(self, arguments_string, last):
        is_brk_char = (len(arguments_string) < len(last))
        args = gdb.string_to_argv(arguments_string)
        if arguments_string == "" or arguments_string[-1:] == " ":
            args.append("") # Add dummy argument to complete
        argc = len(args)

        if argc == 1:
            if is_brk_char:
                return gdb.COMPLETE_NONE
            if args[0] in ['-l', '-o']:
                return args[0] # it's complete
            return ['-l', '-o'] # valid option flags

        if argc == 2 and (args[0] == '-l' or args[0] == '-o'):
            if is_brk_char:
                return gdb.COMPLETE_FILENAME # -l and -o take file arguments
            (head, tail) = os.path.split(curr)
            return getMatchingFiles(head, tail) # implement appropriate heuristic; pass args[0] flag if it matters

        if argc == 3:
            if is_brk_char:
                return gdb.COMPLETE_NONE
            if args[0] == '-l':
                return ['-o']
            if args[0] == '-o':
                return ['-l']
            return []

        if argc == 4:
            if is_brk_char:
                return gdb.COMPLETE_FILENAME
            (head, tail) = os.path.split(curr)
            return getMatchingFiles(head, tail)           

        if is_brk_char:
            return gdb.COMPLETE_NONE
        return [] # No more valid options

NOTE!! The completer is not responsible for validation. That should be done once your command's invoke() method is called.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.