response
stringlengths
1
33.1k
instruction
stringlengths
22
582k
Expand shell variables of the forms $var, ${var} and %var%. Unknown variables are left unchanged.
def expandvars(path): """Expand shell variables of the forms $var, ${var} and %var%. Unknown variables are left unchanged.""" env = xsh.env if isinstance(path, bytes): path = path.decode( encoding=env.get("XONSH_ENCODING"), errors=env.get("XONSH_ENCODING_ERRORS") ) elif ...
Moves an existing file to a new name that has the current time right before the extension.
def backup_file(fname): """Moves an existing file to a new name that has the current time right before the extension. """ # lazy imports import shutil from datetime import datetime base, ext = os.path.splitext(fname) timestamp = datetime.now().strftime("%Y-%m-%d-%H-%M-%S-%f") newfna...
Returns as normalized absolute path, namely, normcase(abspath(p))
def normabspath(p): """Returns as normalized absolute path, namely, normcase(abspath(p))""" return os.path.normcase(os.path.abspath(p))
Provides user expanded absolute path
def expanduser_abs_path(inp): """Provides user expanded absolute path""" return os.path.abspath(expanduser(inp))
Expands a string to a case insensitive globable string.
def expand_case_matching(s): """Expands a string to a case insensitive globable string.""" t = [] openers = {"[", "{"} closers = {"]", "}"} nesting = 0 drive_part = WINDOWS_DRIVE_MATCHER.match(s) if ON_WINDOWS else None if drive_part: drive_part = drive_part.group(0) t.appe...
Simple wrapper around glob that also expands home and env vars.
def globpath( s, ignore_case=False, return_empty=False, sort_result=None, include_dotfiles=None ): """Simple wrapper around glob that also expands home and env vars.""" o, s = _iglobpath( s, ignore_case=ignore_case, sort_result=sort_result, include_dotfiles=include_dotfiles, ...
Simple wrapper around iglob that also expands home and env vars.
def iglobpath(s, ignore_case=False, sort_result=None, include_dotfiles=None): """Simple wrapper around iglob that also expands home and env vars.""" try: return _iglobpath( s, ignore_case=ignore_case, sort_result=sort_result, include_dotfiles=include_dotfi...
Format datetime object to string base on $XONSH_DATETIME_FORMAT Env.
def format_datetime(dt): """Format datetime object to string base on $XONSH_DATETIME_FORMAT Env.""" format_ = xsh.env["XONSH_DATETIME_FORMAT"] return dt.strftime(format_)
Takes an iterable of strings and returns a list of lines with the elements placed in columns. Each line will be at most *width* columns. The newline character will be appended to the end of each line.
def columnize(elems, width=80, newline="\n"): """Takes an iterable of strings and returns a list of lines with the elements placed in columns. Each line will be at most *width* columns. The newline character will be appended to the end of each line. """ sizes = [len(e) + 1 for e in elems] total ...
Decorator that specifies that a callable alias should be run only on the main thread process. This is often needed for debuggers and profilers.
def unthreadable(f): """Decorator that specifies that a callable alias should be run only on the main thread process. This is often needed for debuggers and profilers. """ f.__xonsh_threadable__ = False return f
Decorator that specifies that a callable alias should not be run with any capturing. This is often needed if the alias call interactive subprocess, like pagers and text editors.
def uncapturable(f): """Decorator that specifies that a callable alias should not be run with any capturing. This is often needed if the alias call interactive subprocess, like pagers and text editors. """ f.__xonsh_capturable__ = False return f
Writes a carriage return to stdout, and nothing else.
def carriage_return(): """Writes a carriage return to stdout, and nothing else.""" print("\r", flush=True, end="")
Parametrized decorator that deprecates a function in a graceful manner. Updates the decorated function's docstring to mention the version that deprecation occurred in and the version it will be removed in if both of these values are passed. When removed_in is not a release equal to or less than the current release, c...
def deprecated(deprecated_in=None, removed_in=None): """Parametrized decorator that deprecates a function in a graceful manner. Updates the decorated function's docstring to mention the version that deprecation occurred in and the version it will be removed in if both of these values are passed. W...
Formats a trace line suitable for printing.
def tracer_format_line(fname, lineno, line, color=True, lexer=None, formatter=None): """Formats a trace line suitable for printing.""" fname = min(fname, prompt._replace_home(fname), os.path.relpath(fname), key=len) if not color: return COLORLESS_LINE.format(fname=fname, lineno=lineno, line=line) ...
Somewhat hacky method of finding the __file__ based on the line executed.
def _find_caller(args): """Somewhat hacky method of finding the __file__ based on the line executed.""" re_line = re.compile(r"[^;\s|&<>]+\s+" + r"\s+".join(args)) curr = inspect.currentframe() for _, fname, lineno, _, lines, _ in inspect.getouterframes(curr, context=1)[3:]: if lines is not Non...
Waits till spawned process finishes and closes the handle for it Parameters ---------- process_handle : HANDLE The Windows handle for the process
def wait_and_close_handle(process_handle): """ Waits till spawned process finishes and closes the handle for it Parameters ---------- process_handle : HANDLE The Windows handle for the process """ WaitForSingleObject(process_handle, INFINITE) CloseHandle(process_handle)
This will re-run current Python script requesting to elevate administrative rights. Parameters ---------- executable : str The path/name of the executable args : list of str The arguments to be passed to the executable
def sudo(executable, args=None): """ This will re-run current Python script requesting to elevate administrative rights. Parameters ---------- executable : str The path/name of the executable args : list of str The arguments to be passed to the executable """ if not args...
Tuple of the Windows handles for (stdin, stdout, stderr).
def STDHANDLES(): """Tuple of the Windows handles for (stdin, stdout, stderr).""" hs = [ lazyimps._winapi.STD_INPUT_HANDLE, lazyimps._winapi.STD_OUTPUT_HANDLE, lazyimps._winapi.STD_ERROR_HANDLE, ] hcons = [] for h in hs: hcon = GetStdHandle(int(h)) hcons.appen...
Get the mode of the active console input, output, or error buffer. Note that if the process isn't attached to a console, this function raises an EBADF IOError. Parameters ---------- fd : int Standard buffer file descriptor, 0 for stdin, 1 for stdout (default), and 2 for stderr
def get_console_mode(fd=1): """Get the mode of the active console input, output, or error buffer. Note that if the process isn't attached to a console, this function raises an EBADF IOError. Parameters ---------- fd : int Standard buffer file descriptor, 0 for stdin, 1 for stdout (defau...
Set the mode of the active console input, output, or error buffer. Note that if the process isn't attached to a console, this function raises an EBADF IOError. Parameters ---------- mode : int Mode flags to set on the handle. fd : int, optional Standard buffer file descriptor, 0 for stdin, 1 for stdout (defaul...
def set_console_mode(mode, fd=1): """Set the mode of the active console input, output, or error buffer. Note that if the process isn't attached to a console, this function raises an EBADF IOError. Parameters ---------- mode : int Mode flags to set on the handle. fd : int, optional ...
Enables virtual terminal processing on Windows. This includes ANSI escape sequence interpretation. See http://stackoverflow.com/a/36760881/2312428
def enable_virtual_terminal_processing(): """Enables virtual terminal processing on Windows. This includes ANSI escape sequence interpretation. See http://stackoverflow.com/a/36760881/2312428 """ SetConsoleMode(GetStdHandle(-11), 7)
Reads characters from the console buffer. Parameters ---------- x : int, optional Starting column. y : int, optional Starting row. fd : int, optional Standard buffer file descriptor, 0 for stdin, 1 for stdout (default), and 2 for stderr. buf : ctypes.c_wchar_p if raw else ctypes.c_wchar_p, optional ...
def read_console_output_character(x=0, y=0, fd=1, buf=None, bufsize=1024, raw=False): """Reads characters from the console buffer. Parameters ---------- x : int, optional Starting column. y : int, optional Starting row. fd : int, optional Standard buffer file descriptor,...
This is a console-based implementation of os.pread() for windows. that uses read_console_output_character().
def pread_console(fd, buffersize, offset, buf=None): """This is a console-based implementation of os.pread() for windows. that uses read_console_output_character(). """ cols, rows = os.get_terminal_size(fd=fd) x = offset % cols y = offset // cols return read_console_output_character( ...
Returns the windows version of the get screen buffer.
def GetConsoleScreenBufferInfo(): """Returns the windows version of the get screen buffer.""" gcsbi = ctypes.windll.kernel32.GetConsoleScreenBufferInfo gcsbi.errcheck = check_zero gcsbi.argtypes = (HANDLE, POINTER(CONSOLE_SCREEN_BUFFER_INFO)) gcsbi.restype = BOOL return gcsbi
Returns an screen buffer info object for the relevant stdbuf. Parameters ---------- fd : int, optional Standard buffer file descriptor, 0 for stdin, 1 for stdout (default), and 2 for stderr. Returns ------- csbi : CONSOLE_SCREEN_BUFFER_INFO Information about the console screen buffer.
def get_console_screen_buffer_info(fd=1): """Returns an screen buffer info object for the relevant stdbuf. Parameters ---------- fd : int, optional Standard buffer file descriptor, 0 for stdin, 1 for stdout (default), and 2 for stderr. Returns ------- csbi : CONSOLE_SCREEN_...
Gets the current cursor position as an (x, y) tuple.
def get_cursor_position(fd=1): """Gets the current cursor position as an (x, y) tuple.""" csbi = get_console_screen_buffer_info(fd=fd) coord = csbi.dwCursorPosition return (coord.X, coord.Y)
Gets the current cursor position as a total offset value.
def get_cursor_offset(fd=1): """Gets the current cursor position as a total offset value.""" csbi = get_console_screen_buffer_info(fd=fd) pos = csbi.dwCursorPosition size = csbi.dwSize return (pos.Y * size.X) + pos.X
Gets the current cursor position and screen size tuple: (x, y, columns, lines).
def get_position_size(fd=1): """Gets the current cursor position and screen size tuple: (x, y, columns, lines). """ info = get_console_screen_buffer_info(fd) return ( info.dwCursorPosition.X, info.dwCursorPosition.Y, info.dwSize.X, info.dwSize.Y, )
Set screen buffer dimensions.
def SetConsoleScreenBufferSize(): """Set screen buffer dimensions.""" scsbs = ctypes.windll.kernel32.SetConsoleScreenBufferSize scsbs.errcheck = check_zero scsbs.argtypes = (HANDLE, COORD) # _In_ HANDLE hConsoleOutput # _In_ COORD dwSize scsbs.restype = BOOL return scsbs
Sets the console size for a standard buffer. Parameters ---------- x : int Number of columns. y : int Number of rows. fd : int, optional Standard buffer file descriptor, 0 for stdin, 1 for stdout (default), and 2 for stderr.
def set_console_screen_buffer_size(x, y, fd=1): """Sets the console size for a standard buffer. Parameters ---------- x : int Number of columns. y : int Number of rows. fd : int, optional Standard buffer file descriptor, 0 for stdin, 1 for stdout (default), and 2...
Set cursor position in console.
def SetConsoleCursorPosition(): """Set cursor position in console.""" sccp = ctypes.windll.kernel32.SetConsoleCursorPosition sccp.errcheck = check_zero sccp.argtypes = ( HANDLE, # _In_ HANDLE hConsoleOutput COORD, # _In_ COORD dwCursorPosition ) sccp.restype = BOOL return ...
Sets the console cursor position for a standard buffer. Parameters ---------- x : int Number of columns. y : int Number of rows. fd : int, optional Standard buffer file descriptor, 0 for stdin, 1 for stdout (default), and 2 for stderr.
def set_console_cursor_position(x, y, fd=1): """Sets the console cursor position for a standard buffer. Parameters ---------- x : int Number of columns. y : int Number of rows. fd : int, optional Standard buffer file descriptor, 0 for stdin, 1 for stdout (default), ...
This creates a basic condition function for use with nodes like While or other conditions. The condition function creates and visits a TrueFalse node and returns the result. This TrueFalse node takes the prompt and path that is passed in here.
def create_truefalse_cond(prompt="yes or no [default: no]? ", path=None): """This creates a basic condition function for use with nodes like While or other conditions. The condition function creates and visits a TrueFalse node and returns the result. This TrueFalse node takes the prompt and path that is...
Creates a string or int.
def ensure_str_or_int(x): """Creates a string or int.""" if isinstance(x, int): return x x = x if isinstance(x, str) else str(x) try: x = ast.literal_eval(x) except (ValueError, SyntaxError): pass if not isinstance(x, (int, str)): msg = f"{x!r} could not be conver...
Returns the canonical form of a path, which is a tuple of str or ints. Indices may be optionally passed in.
def canon_path(path, indices=None): """Returns the canonical form of a path, which is a tuple of str or ints. Indices may be optionally passed in. """ if not isinstance(path, str): return tuple(map(ensure_str_or_int, path)) if indices is not None: path = path.format(**indices) pa...
Makes the foreign shell part of the wizard.
def make_fs_wiz(): """Makes the foreign shell part of the wizard.""" cond = wiz.create_truefalse_cond(prompt="Add a new foreign shell, " + wiz.YN) fs = wiz.While( cond=cond, body=[ wiz.Input("shell name (e.g. bash): ", path="/foreign_shells/{idx}/shell"), wiz.StoreNon...
Wraps paragraphs instead.
def _wrap_paragraphs(text, width=70, **kwargs): """Wraps paragraphs instead.""" pars = text.split("\n") pars = ["\n".join(textwrap.wrap(p, width=width, **kwargs)) for p in pars] s = "\n".join(pars) return s
Creates a message for how to exit the wizard.
def make_exit_message(): """Creates a message for how to exit the wizard.""" shell_type = XSH.shell.shell_type keyseq = "Ctrl-D" if shell_type == "readline" else "Ctrl-C" msg = "To exit the wizard at any time, press {BOLD_UNDERLINE_CYAN}" msg += keyseq + "{RESET}.\n" m = wiz.Message(message=msg)...
Makes a StoreNonEmpty node for an environment variable.
def make_envvar(name): """Makes a StoreNonEmpty node for an environment variable.""" env = XSH.env vd = env.get_docs(name) if not vd.is_configurable: return default = vd.doc_default if "\n" in default: default = "\n" + _wrap_paragraphs(default, width=69) curr = env.get(name) ...
Makes an environment variable wizard.
def make_env_wiz(): """Makes an environment variable wizard.""" w = _make_flat_wiz(make_envvar, sorted(XSH.env.keys())) return w
Makes a message and StoreNonEmpty node for a xontrib.
def make_xontrib(xon_item: tuple[str, Xontrib]): """Makes a message and StoreNonEmpty node for a xontrib.""" name, xontrib = xon_item name = name or "<unknown-xontrib-name>" msg = "\n{BOLD_CYAN}" + name + "{RESET}\n" if xontrib.url: msg += "{RED}url:{RESET} " + xontrib.url + "\n" if xo...
Makes a xontrib wizard.
def make_xontribs_wiz(): """Makes a xontrib wizard.""" return _make_flat_wiz(make_xontrib, get_xontribs().items())
Makes a configuration wizard for xonsh config file. Parameters ---------- default_file : str, optional Default filename to save and load to. User will still be prompted. confirm : bool, optional Confirm that the main part of the wizard should be run. no_wizard_file : str, optional Filename for that will fl...
def make_xonfig_wizard(default_file=None, confirm=False, no_wizard_file=None): """Makes a configuration wizard for xonsh config file. Parameters ---------- default_file : str, optional Default filename to save and load to. User will still be prompted. confirm : bool, optional Confir...
Launch configurator in terminal Parameters ------- rcfile : -f, --file config file location, default=$XONSHRC confirm : -c, --confirm confirm that the wizard should be run.
def _wizard( rcfile=None, confirm=False, ): """Launch configurator in terminal Parameters ------- rcfile : -f, --file config file location, default=$XONSHRC confirm : -c, --confirm confirm that the wizard should be run. """ env = XSH.env shell = XSH.shell.shell ...
Displays configuration information Parameters ---------- to_json : -j, --json reports results as json
def _info( to_json=False, ) -> str: """Displays configuration information Parameters ---------- to_json : -j, --json reports results as json """ env = XSH.env data: list[tp.Any] = [("xonsh", XONSH_VERSION)] hash_, date_ = githash() if hash_: data.append(("Git SHA...
Prints available xonsh color styles Parameters ---------- to_json: -j, --json reports results as json
def _styles(to_json=False, _stdout=None): """Prints available xonsh color styles Parameters ---------- to_json: -j, --json reports results as json """ env = XSH.env curr = env.get("XONSH_COLOR_STYLE") styles = sorted(color_style_names()) if to_json: s = json.dumps(st...
Preview color style Parameters ---------- style name of the style to preview. If not given, current style name is used.
def _colors( style: tp.Annotated[str, Arg(nargs="?", completer=xonfig_color_completer)] = None, ): """Preview color style Parameters ---------- style name of the style to preview. If not given, current style name is used. """ columns, _ = shutil.get_terminal_size() columns -= in...
Launch tutorial in browser.
def _tutorial(): """Launch tutorial in browser.""" import webbrowser webbrowser.open("http://xon.sh/tutorial.html")
Launch configurator in browser. Parameters ---------- browser : --nb, --no-browser, -n don't open browser
def _web( _args, browser=True, ): """Launch configurator in browser. Parameters ---------- browser : --nb, --no-browser, -n don't open browser """ from xonsh.webconfig import main main.serve(browser)
Align and pad a color formatted string
def _align_string(string, align="<", fill=" ", width=80): """Align and pad a color formatted string""" linelen = len(STRIP_COLOR_RE.sub("", string)) padlen = max(width - linelen, 0) if align == "^": return fill * (padlen // 2) + string + fill * (padlen // 2 + padlen % 2) elif align == ">": ...
Find the module and return its docstring without actual import
def get_module_docstring(module: str) -> str: """Find the module and return its docstring without actual import""" import ast spec = importlib.util.find_spec(module) if spec and spec.has_location and spec.origin: return ast.get_docstring(ast.parse(Path(spec.origin).read_text())) or "" retur...
Return xontrib definitions lazily.
def get_xontribs() -> dict[str, Xontrib]: """Return xontrib definitions lazily.""" return dict(_get_installed_xontribs())
Patch in user site packages directory. If xonsh is installed in non-writeable location, then xontribs will end up there, so we make them accessible.
def _patch_in_userdir(): """ Patch in user site packages directory. If xonsh is installed in non-writeable location, then xontribs will end up there, so we make them accessible.""" if not os.access(os.path.dirname(sys.executable), os.W_OK): from site import getusersitepackages if ...
List all core packages + newly installed xontribs
def _get_installed_xontribs(pkg_name="xontrib"): """List all core packages + newly installed xontribs""" _patch_in_userdir() spec = importlib.util.find_spec(pkg_name) def iter_paths(): for loc in spec.submodule_search_locations: path = Path(loc) if path.exists(): ...
Finds a xontribution from its name.
def find_xontrib(name, full_module=False): """Finds a xontribution from its name.""" _patch_in_userdir() # here the order is important. We try to run the correct cases first and then later trial cases # that will likely fail if name.startswith("."): return importlib.util.find_spec(name, pa...
Return a context dictionary for a xontrib of a given name.
def xontrib_context(name, full_module=False): """Return a context dictionary for a xontrib of a given name.""" spec = find_xontrib(name, full_module) if spec is None: return None module = importlib.import_module(spec.name) ctx = {} def _get__all__(): pubnames = getattr(module, ...
Returns a formatted string with name of xontrib package to prompt user
def prompt_xontrib_install(names: list[str]): """Returns a formatted string with name of xontrib package to prompt user""" return ( "The following xontribs are enabled but not installed: \n" f" {names}\n" "Please make sure that they are installed correctly by checking https://xonsh.git...
Updates a context in place from a xontrib.
def update_context(name, ctx: dict, full_module=False): """Updates a context in place from a xontrib.""" modctx = xontrib_context(name, full_module) if modctx is None: raise XontribNotInstalled(f"Xontrib - {name} is not found.") else: ctx.update(modctx) return ctx
Load xontribs from a list of names Parameters ---------- names names of xontribs verbose : -v, --verbose verbose output full_module : -f, --full indicates that the names are fully qualified module paths and not inside ``xontrib`` package suppress_warnings : -s, --suppress-warnings no warnings about mis...
def xontribs_load( names: Annotated[ tp.Sequence[str], Arg(nargs="+", completer=xontrib_names_completer), ] = (), verbose=False, full_module=False, suppress_warnings=False, ): """Load xontribs from a list of names Parameters ---------- names names of xontribs...
Unload the given xontribs Parameters ---------- names name of xontribs to unload Notes ----- Proper cleanup can be implemented by the xontrib. The default is equivalent to ``del sys.modules[module]``.
def xontribs_unload( names: Annotated[ tp.Sequence[str], Arg(nargs="+", completer=xontrib_unload_completer), ] = (), verbose=False, ): """Unload the given xontribs Parameters ---------- names name of xontribs to unload Notes ----- Proper cleanup can be i...
Reload the given xontribs Parameters ---------- names name of xontribs to reload
def xontribs_reload( names: Annotated[ tp.Sequence[str], Arg(nargs="+", completer=xontrib_unload_completer), ] = (), verbose=False, ): """Reload the given xontribs Parameters ---------- names name of xontribs to reload """ for name in names: if verbo...
Collects and returns the data about installed xontribs.
def xontrib_data(): """Collects and returns the data about installed xontribs.""" data = {} for xo_name, xontrib in get_xontribs().items(): data[xo_name] = { "name": xo_name, "loaded": xontrib.is_loaded, "auto": xontrib.is_auto_loaded, "module": xontri...
Returns list of loaded xontribs.
def xontribs_loaded(): """Returns list of loaded xontribs.""" return [k for k, xontrib in get_xontribs().items() if xontrib.is_loaded]
List installed xontribs and show whether they are loaded or not Parameters ---------- to_json : -j, --json reports results as json
def xontribs_list(to_json=False, _stdout=None): """List installed xontribs and show whether they are loaded or not Parameters ---------- to_json : -j, --json reports results as json """ data = xontrib_data() if to_json: s = json.dumps(data) return s else: ...
Load xontrib modules exposed via setuptools's entrypoints
def auto_load_xontribs_from_entrypoints( blocked: "tp.Sequence[str]" = (), verbose=False ): """Load xontrib modules exposed via setuptools's entrypoints""" if not hasattr(XSH.builtins, "autoloaded_xontribs"): XSH.builtins.autoloaded_xontribs = {} def get_loadable(): for entry in _get_x...
If the line is empty, complete based on valid commands, python names, and paths.
def complete_base(context: CompletionContext): """If the line is empty, complete based on valid commands, python names, and paths.""" # If we are completing the first argument, complete based on # valid commands and python names. if context.command is None or context.command.arg_index != 0: # do...
Completes based on results from BASH completion.
def complete_from_bash(context: CommandContext): """Completes based on results from BASH completion.""" env = XSH.env.detype() # type: ignore paths = XSH.env.get("BASH_COMPLETIONS", ()) # type: ignore command = xp.bash_command() args = [arg.value for arg in context.args] prefix = context.prefi...
Returns the path to git for windows, if available and None otherwise.
def _git_for_windows_path(): """Returns the path to git for windows, if available and None otherwise.""" import winreg try: key = winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, "SOFTWARE\\GitForWindows") gfwp, _ = winreg.QueryValueEx(key, "InstallPath") except FileNotFoundError: gfwp...
Determines the command for Bash on windows.
def _windows_bash_command(env=None): """Determines the command for Bash on windows.""" wbc = "bash" path = None if env is None else env.get("PATH", None) bash_on_path = shutil.which("bash", path=path) if bash_on_path: try: out = subprocess.check_output( [bash_on_p...
Determines the command for Bash on the current plaform.
def _bash_command(env=None): """Determines the command for Bash on the current plaform.""" if platform.system() == "Windows": bc = _windows_bash_command(env=None) else: bc = "bash" return bc
A possibly empty tuple with default paths to Bash completions known for the current platform.
def _bash_completion_paths_default(): """A possibly empty tuple with default paths to Bash completions known for the current platform. """ platform_sys = platform.system() if platform_sys == "Linux" or sys.platform == "cygwin": bcd = ("/usr/share/bash-completion/bash_completion",) elif ...
Returns the appropriate filepath separator char depending on OS and xonsh options set
def _bash_get_sep(): """Returns the appropriate filepath separator char depending on OS and xonsh options set """ if platform.system() == "Windows": return os.altsep else: return os.sep
Takes a string path and expands ~ to home and environment vars.
def _bash_expand_path(s): """Takes a string path and expands ~ to home and environment vars.""" # expand ~ according to Bash unquoted rules "Each variable assignment is # checked for unquoted tilde-prefixes immediately following a ':' or the # first '='". See the following for more details. # https:...
Completes based on results from BASH completion. Parameters ---------- prefix : str The string to match line : str The line that prefix appears on. begidx : int The index in line that prefix starts on. endidx : int The index in line that prefix ends on. env : Mapping, optional The environment dict ...
def bash_completions( prefix, line, begidx, endidx, env=None, paths=None, command=None, quote_paths=_bash_quote_paths, line_args=None, opening_quote="", closing_quote="", arg_index=None, **kwargs, ): """Completes based on results from BASH completion. Paramet...
Provides the completion from the end of the line. Parameters ---------- line : str Line to complete return_line : bool, optional If true (default), will return the entire line, with the completion added. If false, this will instead return the strings to append to the original line. kwargs : optional Al...
def bash_complete_line(line, return_line=True, **kwargs): """Provides the completion from the end of the line. Parameters ---------- line : str Line to complete return_line : bool, optional If true (default), will return the entire line, with the completion added. If false, ...
Runs complete_line() and prints the output.
def _bc_main(args=None): """Runs complete_line() and prints the output.""" from argparse import ArgumentParser p = ArgumentParser("bash_completions") p.add_argument( "--return-line", action="store_true", dest="return_line", default=True, help="will return the ent...
Returns a list of valid commands starting with the first argument
def complete_command(command: CommandContext): """ Returns a list of valid commands starting with the first argument """ cmd = command.prefix show_desc = (XSH.env or {}).get("CMD_COMPLETIONS_SHOW_DESC", False) for s, (path, is_alias) in XSH.commands_cache.iter_commands(): if get_filter...
Skip over several tokens (e.g., sudo) and complete based on the rest of the command.
def complete_skipper(command_context: CommandContext): """ Skip over several tokens (e.g., sudo) and complete based on the rest of the command. """ # Contextual completers don't need us to skip tokens since they get the correct completion context - # meaning we only need to skip commands like ``sud...
If there's no space following '|', '&', or ';' - insert one.
def complete_end_proc_tokens(command_context: CommandContext): """If there's no space following '|', '&', or ';' - insert one.""" if command_context.opening_quote or not command_context.prefix: return None prefix = command_context.prefix # for example `echo a|`, `echo a&&`, `echo a ;` if any...
If there's no space following 'and' or 'or' - insert one.
def complete_end_proc_keywords(command_context: CommandContext): """If there's no space following 'and' or 'or' - insert one.""" if command_context.opening_quote or not command_context.prefix: return None prefix = command_context.prefix if prefix in END_PROC_KEYWORDS: return {RichComplet...
List the active completers
def list_completers(): """List the active completers""" o = "Registered Completer Functions: (NX = Non Exclusive)\n\n" non_exclusive = " [NX]" _comp = XSH.completers ml = max((len(i) for i in _comp), default=0) exclusive_len = ml + len(non_exclusive) + 1 _strs = [] for c in _comp: ...
Complete all loaded completer names
def complete_completer_names(xsh, **_): """Complete all loaded completer names""" for name, comp in xsh.completers.items(): doc = NumpyDoc(comp) yield RichCompletion(name, description=doc.description)
Removes a completer from xonsh Parameters ---------- name: NAME is a unique name of a completer (run "completer list" to see the current completers in order)
def remove_completer( name: Annotated[str, Arg(completer=complete_completer_names)], ): """Removes a completer from xonsh Parameters ---------- name: NAME is a unique name of a completer (run "completer list" to see the current completers in order) """ err = None if name...
Completes environment variables.
def complete_environment_vars(context: CompletionContext): """Completes environment variables.""" if context.command: prefix = context.command.prefix elif context.python: prefix = context.python.prefix else: return None dollar_location = prefix.rfind("$") if dollar_lo...
Return the list containing the names of the modules available in the given folder.
def module_list(path): """ Return the list containing the names of the modules available in the given folder. """ # sys.path has the cwd as an empty string, but isdir/listdir need it as '.' if path == "": path = "." # A few local constants to be used in loops below pjoin = os.pa...
Returns a list containing the names of all the modules available in the folders of the pythonpath.
def get_root_modules(): """ Returns a list containing the names of all the modules available in the folders of the pythonpath. """ rootmodules_cache = XSH.modules_cache rootmodules = list(sys.builtin_module_names) start_time = time() for path in sys.path: try: modules...
Try to import given module and return list of potential completions.
def try_import(mod: str, only_modules=False) -> list[str]: """ Try to import given module and return list of potential completions. """ mod = mod.rstrip(".") try: m = import_module(mod) except Exception: return [] m_is_init = "__init__" in (getattr(m, "__file__", "") or "") ...
Completes module names and objects for "import ..." and "from ... import ...".
def complete_import(context: CompletionContext): """ Completes module names and objects for "import ..." and "from ... import ...". """ if not (context.command and context.python): # Imports are only possible in independent lines (not in `$()` or `@()`). # This means it's python code...
Creates a copy of the default completers.
def default_completers(cmd_cache): """Creates a copy of the default completers.""" defaults = [ # non-exclusive completers: ("end_proc_tokens", complete_end_proc_tokens), ("end_proc_keywords", complete_end_proc_keywords), ("environment_vars", complete_environment_vars), #...
without control characters
def _get_man_page(cmd: str): """without control characters""" env = XSH.env.detype() manpage = subprocess.Popen( ["man", cmd], stdout=subprocess.PIPE, stderr=subprocess.DEVNULL, env=env ) # This is a trick to get rid of reverse line feeds return subprocess.check_output(["col", "-b"], std...
Completes an option name, based on the contents of the associated man page.
def complete_from_man(context: CommandContext): """ Completes an option name, based on the contents of the associated man page. """ if context.arg_index == 0 or not context.prefix.startswith("-"): return cmd = context.args[0].value def completions(): for desc, opts in _pars...
Returns True if "cd" is a token in the line, False otherwise.
def cd_in_command(line): """Returns True if "cd" is a token in the line, False otherwise.""" lexer = XSH.execer.parser.lexer lexer.reset() lexer.input(line) have_cd = False for tok in lexer: if tok.type == "NAME" and tok.value == "cd": have_cd = True break re...
Wraps os.normpath() to avoid removing './' at the beginning and '/' at the end. On windows it does the same with backslashes
def _normpath(p): """ Wraps os.normpath() to avoid removing './' at the beginning and '/' at the end. On windows it does the same with backslashes """ initial_dotslash = p.startswith(os.curdir + os.sep) initial_dotslash |= xp.ON_WINDOWS and p.startswith(os.curdir + os.altsep) p = p.rstrip() ...
Completes current prefix using CDPATH
def _add_cdpaths(paths, prefix): """Completes current prefix using CDPATH""" env = XSH.env csc = env.get("CASE_SENSITIVE_COMPLETIONS") glob_sorted = env.get("GLOB_SORTED") for cdp in env.get("CDPATH"): test_glob = os.path.join(cdp, prefix) + "*" for s in xt.iglobpath( te...
Detects whether typed is a subsequence of ref. Returns ``True`` if the characters in ``typed`` appear (in order) in ``ref``, regardless of exactly where in ``ref`` they occur. If ``csc`` is ``False``, ignore the case of ``ref`` and ``typed``. Used in "subsequence" path completion (e.g., ``~/u/ro`` expands to ``~/lou...
def subsequence_match(ref, typed, csc): """ Detects whether typed is a subsequence of ref. Returns ``True`` if the characters in ``typed`` appear (in order) in ``ref``, regardless of exactly where in ``ref`` they occur. If ``csc`` is ``False``, ignore the case of ``ref`` and ``typed``. Used i...
Completes path names.
def complete_path(context): """Completes path names.""" if context.command: return contextual_complete_path(context.command) elif context.python: line = context.python.prefix # simple prefix _complete_path_raw will handle gracefully: prefix = line.rsplit(" ", 1)[-1] r...
Completes based on the contents of the current Python environment, the Python built-ins, and xonsh operators.
def complete_python(context: CompletionContext) -> CompleterResult: """ Completes based on the contents of the current Python environment, the Python built-ins, and xonsh operators. """ # If there are no matches, split on common delimiters and try again. if context.python is None: return...
Completes based on the contents of the current Python environment, the Python built-ins, and xonsh operators.
def _complete_python(prefix, context: PythonContext): """ Completes based on the contents of the current Python environment, the Python built-ins, and xonsh operators. """ line = context.multiline_code end = context.cursor_index ctx = context.ctx filt = get_filter_function() rtn = se...
Decorator to turn off warning temporarily.
def _turn_off_warning(func): """Decorator to turn off warning temporarily.""" def wrapper(*args, **kwargs): warnings.filterwarnings("ignore") r = func(*args, **kwargs) warnings.filterwarnings("once", category=DeprecationWarning) return r return wrapper
Safely tries to evaluate an expression. If this fails, it will return a (None, None) tuple.
def _safe_eval(expr, ctx): """Safely tries to evaluate an expression. If this fails, it will return a (None, None) tuple. """ _ctx = None xonsh_safe_eval = XSH.execer.eval try: val = xonsh_safe_eval(expr, ctx, ctx, transform=False) _ctx = ctx except Exception: try: ...