diff --git a/xontrib/rc_awesome.xsh b/xontrib/rc_awesome.xsh index 6a47ee5..4b4da2e 100644 --- a/xontrib/rc_awesome.xsh +++ b/xontrib/rc_awesome.xsh @@ -27,8 +27,14 @@ __import__('warnings').filterwarnings('ignore', 'There is no current event loop' # It's a good practice to keep xonsh session cleano and add `_` alias for import. # ------------------------------------------------------------------------------ -from shutil import which as _which import time as _time +from shutil import which as _which +from xonsh.platform import ON_LINUX, ON_DARWIN #, ON_WINDOWS, ON_WSL, ON_CYGWIN, ON_MSYS, ON_POSIX, ON_FREEBSD, ON_DRAGONFLY, ON_NETBSD, ON_OPENBSD + + +# ------------------------------------------------------------------------------ +# Cross platform, for interactive and non-interactive modes. +# ------------------------------------------------------------------------------ # Sugar shortcuts # Examples: @@ -37,19 +43,24 @@ import time as _time X, E = __xonsh__, __xonsh__.env P = type('LastCP', (object,), {'__getattr__':lambda self, name: getattr(__xonsh__.last, name) })() # xonsh >= 0.17.0 -# ------------------------------------------------------------------------------ -# Cross platform -# ------------------------------------------------------------------------------ - -if X.env.get('XONTRIB_RC_AWESOME_SHELL_TYPE_CHECK', True) and $SHELL_TYPE not in ['prompt_toolkit', 'none', 'best']: - printx("{YELLOW}xontrib-rc-awesome: We recommend to use prompt_toolkit shell by installing `xonsh[full]` package.{RESET}") +# +# Python sugar: inline import +# Usage: +# imp.json.loads('{"a":1}') # {'a': 1} +# imp.datetime.datetime.now().isoformat() # '2024-02-12T15:29:57.125696' +# imp.hashlib.md5(b'Hello world').hexdigest() # '3e25960a79dbc69b674cd4ec67a72c62' +# +imp = type('ImpCl', (object,), {'__getattr__':lambda self, name: __import__(name) })() -# First of all replace `$` to `@` in the prompt to not to be confused with another shell. -# It will be good to read -# - https://github.com/anki-code/xonsh-cheatsheet#three-most-frequent-things-that-newcomers-missed -# - https://github.com/xonsh/xonsh/issues/4152#issue-823993141 -$PROMPT_FIELDS['prompt_end'] = '@' +# Additional sugar: callable environment variable. Try `echo $dt`. +# See also - https://github.com/anki-code/xonsh-cheatsheet/blob/main/README.md#transparent-callable-environment-variables +$dt = type('TimeCl', (object,), {'__repr__':lambda self: imp.datetime.datetime.now().isoformat() })() +# Macro call sugar. +# Usage: +# j = from_json!(echo '{"a":1}') # returns dict +# +from_json = lambda cmd: __import__("json").loads(evalx(f"$({cmd})")) # Switch subprocess output to lines (xonsh >= 0.17.0) to have an ability to run commands like `du $(ls)`. # Note! Downstream tools can produce errors after this so wrap the loading of them into @@ -64,152 +75,145 @@ $PROMPT_FIELDS['prompt_end'] = '@' # aliases['xlines'] = "$XONSH_SUBPROC_OUTPUT_FORMAT = 'list_lines'; echo $XONSH_SUBPROC_OUTPUT_FORMAT" # aliases['xstream'] = "$XONSH_SUBPROC_OUTPUT_FORMAT = 'stream_lines'; echo $XONSH_SUBPROC_OUTPUT_FORMAT" -# Add xontrib-cmd-durations to right prompt. -$RIGHT_PROMPT = '{long_cmd_duration}' - -# The SQLite history backend: -# * Saves command immediately unlike JSON backend. -# * Allows to do `history pull` to get commands from another parallel session. -$XONSH_HISTORY_BACKEND = 'sqlite' - -# What commands are saved to the history list. By default all commands are saved. -# * The option ‘ignoredups’ will not save the command if it matches the previous command. -# * The option `erasedups` will remove all previous commands that matches and updates the command frequency. -# The minus of `erasedups` is that the history of every session becomes unrepeatable -# because it will have a lack of the command you repeat in another session. -# Docs: https://xonsh.github.io/envvars.html#histcontrol -$HISTCONTROL = 'ignoredups' - -# Set regex to avoid saving unwanted commands -# Do not write the command to the history if it was ended by `###` -$XONSH_HISTORY_IGNORE_REGEX = '.*(\\#\\#\\#\\s*)$' - +if ON_LINUX or ON_DARWIN: + # Add default bin paths. + for p in [p'/home/linuxbrew/.linuxbrew/bin', p'~/.local/bin'.expanduser(), p'/opt/homebrew/opt/coreutils/libexec/gnubin']: + if p.exists(): + $PATH.append(str(p)) # or `$PATH.prepend()` -# Remove front dot in multiline input to make the code copy-pastable. -$MULTILINE_PROMPT = ' ' -# Enable mouse support in the prompt_toolkit shell. -# This allows clicking for positioning the cursor or selecting a completion. -# In some terminals however, this disables the ability to scroll back through the history of the terminal. -# To scroll on macOS in iTerm2 press Option key and scroll on touchpad. -if 'pycharm' not in __xonsh__.env.get('__CFBundleIdentifier', ''): - $MOUSE_SUPPORT = True +if $XONSH_INTERACTIVE: + + if X.env.get('XONTRIB_RC_AWESOME_SHELL_TYPE_CHECK', True) and $SHELL_TYPE not in ['prompt_toolkit', 'none', 'best']: + printx("{YELLOW}xontrib-rc-awesome: We recommend to use prompt_toolkit shell by installing `xonsh[full]` package.{RESET}") + + # First of all replace `$` to `@` in the prompt to not to be confused with another shell. + # It will be good to read + # - https://github.com/anki-code/xonsh-cheatsheet#three-most-frequent-things-that-newcomers-missed + # - https://github.com/xonsh/xonsh/issues/4152#issue-823993141 + $PROMPT_FIELDS['prompt_end'] = '@' + + # Add xontrib-cmd-durations to right prompt. + # $RIGHT_PROMPT = '{long_cmd_duration}' + + # The SQLite history backend: + # * Saves command immediately unlike JSON backend. + # * Allows to do `history pull` to get commands from another parallel session. + $XONSH_HISTORY_BACKEND = 'sqlite' + + # What commands are saved to the history list. By default all commands are saved. + # * The option ‘ignoredups’ will not save the command if it matches the previous command. + # * The option `erasedups` will remove all previous commands that matches and updates the command frequency. + # The minus of `erasedups` is that the history of every session becomes unrepeatable + # because it will have a lack of the command you repeat in another session. + # Docs: https://xonsh.github.io/envvars.html#histcontrol + $HISTCONTROL = 'ignoredups' + + # Set regex to avoid saving unwanted commands + # Do not write the command to the history if it was ended by `###` + $XONSH_HISTORY_IGNORE_REGEX = '.*(\\#\\#\\#\\s*)$' -# Adding aliases from dict. -aliases |= { - # cd-ing shortcuts. - '-': 'cd -', - '..': 'cd ..', + # Remove front dot in multiline input to make the code copy-pastable. + $MULTILINE_PROMPT = ' ' - # update pip and xonsh - 'xonsh-update': 'xpip install -U pip && xpip install -U git+https://github.com/xonsh/xonsh', -} - - -# Easy way to go back cd-ing. -# Example: `,,` the same as `cd ../../` -@aliases.register(",") -@aliases.register(",,") -@aliases.register(",,,") -@aliases.register(",,,,") -def _alias_supercomma(): - """Easy way to go back cd-ing.""" - cd @("../" * len($__ALIAS_NAME)) - - -# Alias to get Xonsh Context. -# Read more: https://github.com/anki-code/xonsh-cheatsheet/blob/main/README.md#install-xonsh-with-package-and-environment-management-system -@aliases.register("xc") -def _alias_xc(): - """Get xonsh context.""" - print('xpython:', imp.sys.executable, '#', $(xpython -V).strip()) - print('xpip:', $(which xpip).strip()) # xpip - xonsh's builtin to install packages in current session xonsh environment. - print('') - print('xonsh:', $(which xonsh)) - print('python:', $(which python), '#' ,$(python -V).strip()) - print('pip:', $(which pip)) - if _which('pytest'): - print('pytest:', $(which pytest)) - print('') - envs = ['CONDA_DEFAULT_ENV'] - for ev in envs: - if (val := X.env.get(ev)): - print(f'{ev}:', val) - - -# Example of utilizing `xonsh.tools.chdir` to do git commit, git config, git pull and push at once. -# Usage: git-sync ~/git/myrepo1 ~/git/myrepo2 -if _which('git'): - @aliases.register('git-sync') - def _git_sync(args): - from xonsh.tools import chdir - paths = args if args else [$PWD] - for p in paths: - print(f'git sync {p}') - with chdir(p): - git config --local user.name $USER - git config --local user.email $USER@$USER.local - git commit --allow-empty -a -uno -m "Update" - git pull --rebase - git push - - -# Avoid typing cd just directory path. -# Docs: https://xonsh.github.io/envvars.html#auto-cd -$AUTO_CD = True + # Enable mouse support in the prompt_toolkit shell. + # This allows clicking for positioning the cursor or selecting a completion. + # In some terminals however, this disables the ability to scroll back through the history of the terminal. + # To scroll on macOS in iTerm2 press Option key and scroll on touchpad. + if 'pycharm' not in __xonsh__.env.get('__CFBundleIdentifier', ''): + $MOUSE_SUPPORT = True -# -# Xontribs - https://github.com/topics/xontrib -# -# Note! Because of xonsh read ~/.xonshrc on every start and can be executed from any virtual environment -# with the different set of installed packages it's a highly recommended approach to use `-s` to avoid errors. -# Read more: https://github.com/anki-code/xonsh-cheatsheet/blob/main/README.md#install-xonsh-with-package-and-environment-management-system -# -_xontribs_to_load = ( - 'jump_to_dir', # Jump to used before directory by part of the path. Lightweight zero-dependency implementation of autojump or zoxide projects functionality. - 'prompt_bar', # The bar prompt for xonsh shell with customizable sections. URL: https://github.com/anki-code/xontrib-prompt-bar - 'whole_word_jumping', # Jumping across whole words (non-whitespace) with Ctrl+Left/Right and Alt+Left/Right on Linux or Option+Left/Right on macOS. - 'back2dir', # Back to the latest used directory when starting xonsh shell. URL: https://github.com/anki-code/xontrib-back2dir - 'pipeliner', # Let your pipe lines flow thru the Python code. URL: https://github.com/anki-code/xontrib-pipeliner - 'cmd_done', # Show long running commands durations in prompt with option to send notification when terminal is not focused. URL: https://github.com/jnoortheen/xontrib-cmd-durations - 'jedi', # Jedi - an awesome autocompletion, static analysis and refactoring library for Python. URL: https://github.com/xonsh/xontrib-jedi - 'clp', # Copy output to clipboard. URL: https://github.com/anki-code/xontrib-clp -) -xontrib load -s @(_xontribs_to_load) -# -# Python sugar: inline import -# Usage: -# imp.json.loads('{"a":1}') # {'a': 1} -# imp.datetime.datetime.now().isoformat() # '2024-02-12T15:29:57.125696' -# imp.hashlib.md5(b'Hello world').hexdigest() # '3e25960a79dbc69b674cd4ec67a72c62' -# -imp = type('ImpCl', (object,), {'__getattr__':lambda self, name: __import__(name) })() + # Adding aliases from dict. + aliases |= { + # cd-ing shortcuts. + '-': 'cd -', + '..': 'cd ..', + + # update pip and xonsh + 'xonsh-update': 'xpip install -U pip && xpip install -U --force-reinstall git+https://github.com/xonsh/xonsh', + } -# Additional sugar: callable environment variable. Try `echo $dt`. -# See also - https://github.com/anki-code/xonsh-cheatsheet/blob/main/README.md#transparent-callable-environment-variables -$dt = type('TimeCl', (object,), {'__repr__':lambda self: imp.datetime.datetime.now().isoformat() })() -# Macro call sugar. -# Usage: -# j = from_json!(echo '{"a":1}') # returns dict -# -from_json = lambda cmd: __import__("json").loads(evalx(f"$({cmd})")) + # Easy way to go back cd-ing. + # Example: `,,` the same as `cd ../../` + @aliases.register(",") + @aliases.register(",,") + @aliases.register(",,,") + @aliases.register(",,,,") + def _alias_supercomma(): + """Easy way to go back cd-ing.""" + cd @("../" * len($__ALIAS_NAME)) -# ------------------------------------------------------------------------------ -# Conda (https://conda-forge.org/) -# ------------------------------------------------------------------------------ -# To speed up startup you can disable auto activate the base environment. -# $CONDA_AUTO_ACTIVATE_BASE = 'false' + # Alias to get Xonsh Context. + # Read more: https://github.com/anki-code/xonsh-cheatsheet/blob/main/README.md#install-xonsh-with-package-and-environment-management-system + @aliases.register("xc") + def _alias_xc(): + """Get xonsh context.""" + print('xpython:', imp.sys.executable, '#', $(xpython -V).strip()) + print('xpip:', $(which xpip).strip()) # xpip - xonsh's builtin to install packages in current session xonsh environment. + print('') + print('xonsh:', $(which xonsh)) + print('python:', $(which python), '#' ,$(python -V).strip()) + print('pip:', $(which pip)) + if _which('pytest'): + print('pytest:', $(which pytest)) + print('') + envs = ['CONDA_DEFAULT_ENV'] + for ev in envs: + if (val := X.env.get(ev)): + print(f'{ev}:', val) + + + # Example of utilizing `xonsh.tools.chdir` to do git commit, git config, git pull and push at once. + # Usage: git-sync ~/git/myrepo1 ~/git/myrepo2 + if _which('git'): + @aliases.register('git-sync') + def _git_sync(args): + from xonsh.tools import chdir + paths = args if args else [$PWD] + for p in paths: + print(f'git sync {p}') + with chdir(p): + git config --local user.name $USER + git config --local user.email $USER@$USER.local + git commit --allow-empty -a -uno -m "Update" + git pull --rebase + git push + + + # Avoid typing cd just directory path. + # Docs: https://xonsh.github.io/envvars.html#auto-cd + $AUTO_CD = True + # + # Xontribs - https://github.com/topics/xontrib + # + # Note! Because of xonsh read ~/.xonshrc on every start and can be executed from any virtual environment + # with the different set of installed packages it's a highly recommended approach to use `-s` to avoid errors. + # Read more: https://github.com/anki-code/xonsh-cheatsheet/blob/main/README.md#install-xonsh-with-package-and-environment-management-system + # + _xontribs_to_load = ( + 'jump_to_dir', # Jump to used before directory by part of the path. Lightweight zero-dependency implementation of autojump or zoxide projects functionality. + 'prompt_bar', # The bar prompt for xonsh shell with customizable sections. URL: https://github.com/anki-code/xontrib-prompt-bar + 'whole_word_jumping', # Jumping across whole words (non-whitespace) with Ctrl+Left/Right and Alt+Left/Right on Linux or Option+Left/Right on macOS. + 'back2dir', # Back to the latest used directory when starting xonsh shell. URL: https://github.com/anki-code/xontrib-back2dir + 'pipeliner', # Let your pipe lines flow thru the Python code. URL: https://github.com/anki-code/xontrib-pipeliner + 'cmd_done', # Show long running commands durations in prompt with option to send notification when terminal is not focused. URL: https://github.com/jnoortheen/xontrib-cmd-durations + 'jedi', # Jedi - an awesome autocompletion, static analysis and refactoring library for Python. URL: https://github.com/xonsh/xontrib-jedi + 'clp', # Copy output to clipboard. URL: https://github.com/anki-code/xontrib-clp + ) + xontrib load -s @(_xontribs_to_load) -# ------------------------------------------------------------------------------ -# Platform specific -# ------------------------------------------------------------------------------ + + # ------------------------------------------------------------------------------ + # Conda (https://conda-forge.org/) + # ------------------------------------------------------------------------------ + # To speed up startup you can disable auto activate the base environment. + # $CONDA_AUTO_ACTIVATE_BASE = 'false' -from xonsh.platform import ON_LINUX, ON_DARWIN #, ON_WINDOWS, ON_WSL, ON_CYGWIN, ON_MSYS, ON_POSIX, ON_FREEBSD, ON_DRAGONFLY, ON_NETBSD, ON_OPENBSD if ON_LINUX or ON_DARWIN: @@ -225,11 +229,6 @@ if ON_LINUX or ON_DARWIN: # It's for `mc` alias (below). $AUTO_PUSHD = True - # Add default bin paths. - for p in [p'/home/linuxbrew/.linuxbrew/bin', p'~/.local/bin'.expanduser(), p'/opt/homebrew/opt/coreutils/libexec/gnubin']: - if p.exists(): - $PATH.append(str(p)) - # Adding aliases from dict. aliases |= { @@ -256,7 +255,6 @@ if ON_LINUX or ON_DARWIN: # Run http server in the current directory. 'http-here': 'python3 -m http.server', - } # Run Midnight Commander where left and right panel will be the current and the previous directory. @@ -358,19 +356,17 @@ if ON_LINUX or ON_DARWIN: import xonsh.pretty xonsh.pretty.for_type(type(1), lambda int, printer, cycle: printer.text(f'{int:,}')) xonsh.pretty.for_type(type(1.0), lambda float, printer, cycle: printer.text(f'{float:,}')) - -# ------------------------------------------------------------------------------ -# Final -# ------------------------------------------------------------------------------ - -# For the experienced users: -# Suppress line "xonsh: For full traceback set: $XONSH_SHOW_TRACEBACK = True". -# in case of exceptions or wrong command. -$XONSH_SHOW_TRACEBACK = False + # + # For the experienced users: + # -# Suppress line "Did you mean one of the following?". -$SUGGEST_COMMANDS = False + # Suppress line "xonsh: For full traceback set: $XONSH_SHOW_TRACEBACK = True". + # in case of exceptions or wrong command. + $XONSH_SHOW_TRACEBACK = False + + # Suppress line "Did you mean one of the following?". + $SUGGEST_COMMANDS = False # Thanks for reading! PR is welcome!