Some zshrc tricks

栏目: IT技术 · 发布时间: 4年前

内容简介:Some useful “tricks” from myI found theDefine directory shortcuts with

Some useful “tricks” from my ~/.zshrc ; ( full version here ). Not all of this is “copy paste ready”, but it should give you some inspiration to build your own stuff :-)

I found the User’s Guide to ZSH very helpful when learning about zsh. It hasn’t been updated in a while and isn’t even finished, but found it’s quite well-written and useful.

Directory shortcuts

Define directory shortcuts with hash -d so you can use cd ~x and vim ~x/file instead of cd /very/long/and/often/accessed/path . Some examples:

# Directory shortcuts
hash -d pack=$HOME/.cache/vim/pack/plugins/start
hash -d vim=/usr/share/vim/vim82
hash -d d=$HOME/code/arp242.net/_drafts
hash -d p=$HOME/code/arp242.net/_posts
hash -d go=/usr/lib/go/src
hash -d c=$HOME/code
hash -d gc=$HOME/code/goatcounter

If you put %~ in your PROMPT then the short version will show up there, too:

$ PROMPT='%~ '
$~ cd ~/.cache/vim/pack/plugins/start
~/.cache/vim/pack/plugins/start$ hash -d pack=$HOME/.cache/vim/pack/plugins/start
~pack$

Filter history completion with what you typed

Make up and down arrow take what’s typed on the commandline in to account. E.g. if you type ls and press up it will only find history entries that start with ls :

autoload -Uz up-line-or-beginning-search down-line-or-beginning-search

zle -N up-line-or-beginning-search
zle -N down-line-or-beginning-search

bindkey '^[[A'  up-line-or-beginning-search    # Arrow up
bindkey '^[OA'  up-line-or-beginning-search
bindkey '^[[B'  down-line-or-beginning-search  # Arrow down
bindkey '^[OB'  down-line-or-beginning-search

I use this a lot, and is the #1 thing I miss if it’s not available.

Easier PATH

Many systems link /bin to /usr/bin , and storing all of those in PATH isn’t too useful. Some helper functiosn to prepend or append to PATH which also checks if the path exists so it’s easier to write a portable zshrc:

typeset -U path  # No duplicates
path=()

_prepath() {
    for dir in "$@"; do
        [[ -L "$dir" ]] && dir=$(/usr/bin/readlink -f "$dir")
        [[ ! -d "$dir" ]] && return
        path=("$dir" $path[@])
    done
}
_postpath() {
    for dir in "$@"; do
        [[ -L "$dir" ]] && dir=$(/usr/bin/readlink -f "$dir")
        [[ ! -d "$dir" ]] && return
        path=($path[@] "$dir")
    done
}

_prepath /bin /sbin /usr/bin /usr/sbin /usr/games
_prepath /usr/pkg/bin   /usr/pkg/sbin   # NetBSD
_prepath /usr/X11R6/bin /usr/X11R6/sbin # OpenBSD
_prepath /usr/local/bin /usr/local/sbin

_prepath "$HOME/go/bin"                # Go
_prepath "$HOME/.local/bin"            # My local stuff.
if [[ -d "$HOME/.gem/ruby" ]]; then    # Ruby
    for d in "$HOME/.gem/ruby/"*; do
        _postpath "$d/bin";
    done
fi

unfunction _prepath
unfunction _postpath

Easier alias

Adding a little _exist helper is similarly useful for a portable zshrc:

_exists() { hash $1 2>/dev/null }

_exists vim      && export EDITOR=vim
_exists less     && export PAGER=less
_exists bsdtar   && alias tar='bsdtar'
_exists htop     && alias top='htop'

if _exists vim; then
    alias vim="vim -p"
    alias vi="vim"
fi

unfunction _exists

Edit ag and grep results

“ag edit” and “grep edit” to quickly open stuff found with ag or grep in Vim:

age() {
    vim +'/\v'"$1" +':silent tabdo :1 | normal! n' +':tabfirst' -p $(ag "$@" | cut -d: -f1 | sort -u)
}
grepe() {
    vim +'/\v'"$1" +':silent tabdo :1 | normal! n' +':tabfirst' -p $(grep "$@" | cut -d: -f1 | sort -u)
}

$ ag pattern
[.. check if results look right ..]

$ age pattern
[open in Vim]

Caveat: the Vim regexp syntax isn’t quite the same as extended POSIX or PCRE, so the pattern doesn’t always work as expect in Vim. It works most of the time though.

Caveat 2: sometimes I use this to check if I have the right results:

$ ag pattern | less

And then I modify it age while forgetting to remove the less :

$ age pattern | less

Vim will not like this :sweat_smile: Not sure if we can write something to be a bit smarter about this. Ideally I would be smarter, but alas I am not.

Global aliases

You can define global aliases with alias -g , which will work everywhere. I use it to make piping stdout and stderr to less or Vim a bit easier:

alias -g VV=' |& vim -'
alias -g LL=' |& less'

$ ls LL
$ go test -v VV

Playground environment

Set up a quick “tmp go” environment for testing; I mostly use Go these days, but this can be done for other languages as well:

tgo() {
    tmp="$(mktemp -p /tmp -d "tgo_$(date +%Y%m%d)_XXXXXXXX")"
    printf 'package main\n\nfunc main() {\n\n}\n' > "$tmp/main.go"
    printf 'package main\n\nfunc TestMain(t *testing.T) {\n\n}\n\n' > "$tmp/main_test.go"
    printf 'func BenchmarkMain(b *testing.B) {\n\tb.ReportAllocs()\n\tfor n := 0; n < b.N; n++ {\n\t}\n}\n' >> "$tmp/main_test.go"

    printf 'module %s\n' "$(basename "$tmp")" > "$tmp/go.mod"
    (
        cd "$tmp"
        vim -p main.go main_test.go
        echo "$tmp"
    )
}

It will create a main.go and main_test.go in /tmp/ with some useful boilerplate and a go.mod so it’s recognized as a module (required to get gopls etc. to work well) and opens the whole shebang in Vim.

This won’t be removed after Vim exits on purpose, so you won’t lose your prototype.

Run stored SQL queries

I have a bunch of scripts in ~/docs/sql/scripts to get some stats and whatnot from PostgreSQL. This adds a sql command with tab-completion to that directory and runs psql with some useful flags:

sql() {
    cmd="psql -X -P linestyle=unicode -P null=NULL goatcounter"
    f="$HOME/docs/sql/scripts/$1"
    if [[ -f "$f" ]]; then
        eval "$cmd" < "$HOME/docs/sql/scripts/$1" | less -S
    else
        eval "$cmd" <<< "$1" | less -S
    fi
}
_sql() { _files -W ~/docs/sql/scripts }
compdef _sql sql

If the file doesn’t exist then the query is just run:

$ sql ls-inactive.sql

$ sql 'select * from sites'

less -S prevents wrapping long lines, which I find more useful for tabular output.

Shortcuts to edit commandline

Custom mappings to preform some common substitutions, use <C-r> to prepend doas to the commandline, or <C-r> to replace the first word with rm :

insert_doas() { zle beginning-of-line; zle -U "doas " }
replace_rm()  { zle beginning-of-line; zle delete-word; zle -U "rm " }

zle -N insert-doas insert_doas
zle -N replace-rm replace_rm

bindkey '^s'    insert-doas
bindkey '^r'    replace-rm

以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

产品经理手册(原书第4版)(白金版)

产品经理手册(原书第4版)(白金版)

[美] 琳达·哥乔斯(Linda Gorchels) / 祝亚雄、冯华丽、金骆彬 / 机械工业出版社 / 2017-8 / 65.00

产品经理的职责起点是新产品开发,贯穿产品生命周期的全过程。本书按上下游产品管理进行组织。 在上游的新产品开发流程中,作者阐述了如何从市场、产品、行业、公司的角度规划企划方案,并获得老板、销售部、运营部的资源支持,推进新产品的项目流程,实现所有目标,制定和实施新产品发布。 下游产品的管理核心在于生命周期的管理,营销更是生命周期管理的重中之重。产品经理如何让产品满足客户需求,让客户获得对产......一起来看看 《产品经理手册(原书第4版)(白金版)》 这本书的介绍吧!

HTML 压缩/解压工具
HTML 压缩/解压工具

在线压缩/解压 HTML 代码

图片转BASE64编码
图片转BASE64编码

在线图片转Base64编码工具

正则表达式在线测试
正则表达式在线测试

正则表达式在线测试