MCPcopy Create free account
hub / github.com/python-cmd2/cmd2 / get_completions

Method get_completions

cmd2/pt_utils.py:65–153  ·  view source on GitHub ↗

Get completions for the current input.

(self, document: Document, _complete_event: object)

Source from the content-addressed store, hash-verified

63 self.custom_settings = custom_settings
64
65 def get_completions(self, document: Document, _complete_event: object) -> Iterable[Completion]:
66 """Get completions for the current input."""
67 # Find the beginning of the current word based on delimiters
68 line = document.text
69 cursor_pos = document.cursor_position
70
71 # Define delimiters for completion to match cmd2/readline behavior
72 delimiters = BASE_DELIMITERS
73 delimiters += "".join(self.cmd_app.statement_parser.terminators)
74
75 # Find last delimiter before cursor to determine the word being completed
76 begidx = 0
77 for i in range(cursor_pos - 1, -1, -1):
78 if line[i] in delimiters:
79 begidx = i + 1
80 break
81
82 endidx = cursor_pos
83 text = line[begidx:endidx]
84
85 completions = self.cmd_app.complete(
86 text, line=line, begidx=begidx, endidx=endidx, custom_settings=self.custom_settings
87 )
88
89 if completions.error:
90 print_formatted_text(pt_filter_style(completions.error))
91 return
92
93 # Print completion table if present
94 if completions.table is not None:
95 console = ru.Cmd2GeneralConsole(file=self.cmd_app.stdout)
96 with console.capture() as capture:
97 console.print(completions.table, end="", soft_wrap=False)
98 print_formatted_text(pt_filter_style("\n" + capture.get()))
99
100 if not completions:
101 # # Print hint if present
102 if completions.hint:
103 print_formatted_text(pt_filter_style(completions.hint))
104 return
105
106 # The length of the user's input minus any shortcut.
107 search_text_length = len(text) - completions._search_text_offset
108
109 # If matches require quoting but the word isn't quoted yet, we insert the
110 # opening quote directly into the buffer. We do this because if any completions
111 # change text before the cursor (like prepending a quote), prompt-toolkit will
112 # not return a common prefix to the command line. By modifying the buffer
113 # and returning early, we trigger a new completion cycle where the quote
114 # is already present, allowing for proper common prefix calculation.
115 if completions._add_opening_quote and search_text_length > 0:
116 buffer = get_app().current_buffer
117
118 buffer.cursor_left(search_text_length)
119 buffer.insert_text(completions._quote_char)
120 buffer.cursor_right(search_text_length)
121 return
122

Calls 4

pt_filter_styleFunction · 0.85
printMethod · 0.80
completeMethod · 0.45
getMethod · 0.45