MCPcopy Index your code
hub / github.com/python-cmd2/cmd2 / Cmd2Lexer

Class Cmd2Lexer

cmd2/pt_utils.py:193–307  ·  view source on GitHub ↗

Lexer that highlights cmd2 command names, aliases, and macros.

Source from the content-addressed store, hash-verified

191
192
193class Cmd2Lexer(Lexer):
194 """Lexer that highlights cmd2 command names, aliases, and macros."""
195
196 def __init__(
197 self,
198 cmd_app: "Cmd",
199 command_color: str = "ansigreen",
200 alias_color: str = "ansicyan",
201 macro_color: str = "ansimagenta",
202 flag_color: str = "ansired",
203 argument_color: str = "ansiyellow",
204 ) -> None:
205 """Initialize the Lexer.
206
207 :param cmd_app: cmd2.Cmd instance
208 :param command_color: color to use for commands, defaults to 'ansigreen'
209 :param alias_color: color to use for aliases, defaults to 'ansicyan'
210 :param macro_color: color to use for macros, defaults to 'ansimagenta'
211 :param flag_color: color to use for flags, defaults to 'ansired'
212 :param argument_color: color to use for arguments, defaults to 'ansiyellow'
213 """
214 super().__init__()
215 self.cmd_app = cmd_app
216 self.command_color = command_color
217 self.alias_color = alias_color
218 self.macro_color = macro_color
219 self.flag_color = flag_color
220 self.argument_color = argument_color
221
222 def lex_document(self, document: Document) -> Callable[[int], Any]:
223 """Lex the document."""
224 # Get redirection tokens and terminators to avoid highlighting them as values
225 exclude_tokens = set(constants.REDIRECTION_TOKENS)
226 exclude_tokens.update(self.cmd_app.statement_parser.terminators)
227 arg_pattern = re.compile(r'(\s+)|(--?[^\s\'"]+)|("[^"]*"?|\'[^\']*\'?)|([^\s\'"]+)')
228
229 def highlight_args(text: str, tokens: list[tuple[str, str]]) -> None:
230 """Highlight arguments in a string."""
231 for m in arg_pattern.finditer(text):
232 space, flag, quoted, word = m.groups()
233 match_text = m.group(0)
234
235 if space:
236 tokens.append(("", match_text))
237 elif flag:
238 tokens.append((self.flag_color, match_text))
239 elif (quoted or word) and match_text not in exclude_tokens:
240 tokens.append((self.argument_color, match_text))
241 else:
242 tokens.append(("", match_text))
243
244 def get_line(lineno: int) -> list[tuple[str, str]]:
245 """Return the tokens for the given line number."""
246 line = document.lines[lineno]
247 tokens: list[tuple[str, str]] = []
248
249 # No syntax highlighting if styles are disallowed
250 if ru.ALLOW_STYLE == ru.AllowStyle.NEVER:

Callers 1

_create_main_sessionMethod · 0.85

Calls

no outgoing calls

Tested by

no test coverage detected

Used in the wild real call sites across dependent graphs

searching dependent graphs…