1
0
mirror of https://git.decapod.one/brethil/dotfiles synced 2024-11-01 02:11:30 +01:00

Compare commits

..

7 Commits

Author SHA1 Message Date
bretello
25eb757af3
vim: formatting in vimrc 2020-12-07 23:41:44 +01:00
bretello
56f0a4d6d4
vim: move ale definition to ale group 2020-12-07 23:41:44 +01:00
bretello
5241e825d2
vim: replace lightline with airline 2020-12-07 23:41:44 +01:00
bretello
029a867a74
vim: reload all configurations on write 2020-12-07 23:41:44 +01:00
bretello
b48649e1d6
vim: add <leader>vv to re-select text after pasting 2020-12-07 23:41:44 +01:00
bretello
b2f76856e6
vim: add vim-toml 2020-12-07 23:41:44 +01:00
bretello
4b2b598ed1
vim: add tagbar plugin 2020-12-07 23:41:44 +01:00
77 changed files with 1615 additions and 3179 deletions

View File

@ -1,7 +0,0 @@
/.drone.yml
/.gitignore
/.dotfiles-update
.mypy_cache
.venv
.zcompdump*
.vagrant

View File

@ -1 +0,0 @@
0c3b712

View File

@ -1,37 +0,0 @@
name: Build Image
on:
push:
branches: [main]
pull_request:
schedule:
- cron: "20 4 * * 6" # saturday at 4.20
workflow_dispatch:
jobs:
ansible:
runs-on: archlinux-latest
steps:
- name: Install ansible
run: |
pacman -Sy
pacman -S ansible --noconfirm
- name: Setup local inventory
run: |
echo "localhost ansible_user=root connection=local" > ansible-hosts
- name: Run playbook
run: |
ansible-playbook -i ansible-hosts playbook.yml
- name: Notify on failure
if: failure()
run: |
python -m venv .
./bin/pip install git+https://git.decapod.one/brethil/bretellofier
./bin/bretellofier "[brethil/dotfiles] 💥 Build failed"
env:
BRETELLOFIER_RECIPIENTS: ${{ secrets.BRETELLOFIER_RECIPIENTS }}
BRETELLOFIER_TOKEN: ${{ secrets.BRETELLOFIER_TOKEN}}

View File

@ -1,41 +0,0 @@
name: Build Image
on:
push:
branches: [main]
pull_request:
schedule:
- cron: "20 4 * * 6" # saturday at 4.20
workflow_dispatch:
env:
FORCE_COLOR: "1"
DOCKER_REGISTRY: registry.decapod.one
jobs:
docker:
runs-on: ubuntu-latest
steps:
- name: Set up Docker Buildx
uses: docker/setup-buildx-action@v3
- name: Login to docker registry
uses: docker/login-action@v3
with:
registry: registry.decapod.one
username: ${{ secrets.REGISTRY_USER }}
password: ${{ secrets.REGISTRY_TOKEN }}
- name: Build and push
uses: docker/build-push-action@v5
with:
push: true
tags: registry.decapod.one/brethil/dotfiles:latest
- name: Notify on failure
if: failure()
run: |
python -m venv .
./pip install git+https://git.decapod.one/brethil/bretellofier
./bin/bretellofier "[brethil/dotfiles] 💥 Build failed"
env:
BRETELLOFIER_RECIPIENTS: ${{ secrets.BRETELLOFIER_RECIPIENTS }}
BRETELLOFIER_TOKEN: ${{ secrets.BRETELLOFIER_TOKEN}}

3
.gitignore vendored
View File

@ -1,7 +1,8 @@
.dotfiles-update
.DS_store .DS_store
*antigen-compat
*.zwc *.zwc
history.sqlite history.sqlite
dhist
ipython/profile_default/{log,db} ipython/profile_default/{log,db}
ipython/profile_default/history.sqlite ipython/profile_default/history.sqlite

View File

@ -1,70 +0,0 @@
FROM archlinux:latest as base
ENV TERM=xterm-256color
ENV DOTFILES=/root/.dotfiles
RUN pacman --noconfirm -Syu && pacman --noconfirm -Sy \
vim \
tmux \
git \
fzf \
base-devel \
ipython \
python-pip \
htop \
python-ruff \
python-virtualenv \
bash-language-server \
&& rm -rf /var/cache/pacman/pkg/*
# Enable colors in pacman
RUN sed -i 's/^#Color/Color/' /etc/pacman.conf
FROM base as builder
# Cannot run makepkg as root: add build user
RUN useradd build && echo "build ALL=(ALL:ALL) NOPASSWD: ALL" >> /etc/sudoers
USER build
# yay (pre-compiled) and bretellofier
WORKDIR /home/build/yay
RUN git clone https://aur.archlinux.org/yay-bin.git /home/build/yay && \
git clone https://aur.archlinux.org/bretellofier.git /home/build/bretellofier && \
cd /home/build/yay && env GOCACHE=/home/build makepkg --syncdeps --noconfirm && \
cd /home/build/bretellofier && makepkg --syncdeps --noconfirm
FROM base as final
WORKDIR /root
RUN pacman -Sy --noconfirm zsh && chsh -s /bin/zsh
COPY --from=builder /home/build/yay/*zst /tmp/
COPY --from=builder /home/build/bretellofier/*zst /tmp/
RUN pacman --noconfirm -U /tmp/*zst && rm -rf /tmp/*zst
# antibody
RUN curl -sL https://git.io/antibody | sh -s - -b /usr/local/bin
# vim-plug
RUN curl -fLo ~/.vim/autoload/plug.vim --create-dirs \
https://raw.githubusercontent.com/junegunn/vim-plug/master/plug.vim
RUN git clone https://git.decapod.one/brethil/dotfiles ${DOTFILES}
COPY . ${DOTFILES}
WORKDIR /root/
RUN echo -e "export DOTFILES=/root/.dotfiles\nsource \$DOTFILES/brethil_dotfile.sh" >> .zshrc && \
ln -s $DOTFILES/vim/vimrc .vimrc && \
ln -s $DOTFILES/tmux.conf .tmux.conf && \
echo -e "[include]\npath = $DOTFILES/gitconfig" >> .gitconfig
# Install vim plugins
RUN vim -c 'PlugInstall|qa!'
# Install zsh plugins
RUN zsh -c exit
CMD ["tmux"]

145
README.md
View File

@ -1,40 +1,38 @@
# brethil's dotfiles # brethil's dotfiles
My own dotfiles. `zsh` configuration based on [antidote](https://github.com/mattmc3/antidote.git) and [oh-my-zsh](https://github.com/ohmyzsh/ohmyzsh), `vim` configuration uses [vim-plug](https://github.com/junegunn/vim-plug), [ALE](https://github.com/dense-analysis/ale) and more. A set of zsh dotfiles based on antibody and oh-my-zsh
[!ci.decapod.one status](https://ci.decapod.one/api/badges/2/status.svg)
[zsh theme](docs/brethil-theme.png "zsh theme")
[vim theme](docs/vim.png "vim theme")
[tmux theme](docs/tmux.png "tmux theme")
## Description ## Description
├── README.md ├── README.md
├── playbook.yml
   └── aliases definitions. Add .zsh files here to include more
├──────── Main files ──────── ├──────── Main files ────────
│ ├── aliases/ │ ├── aliases.sh
│ │    └── aliases definitions. Add .zsh files here to include more │ │     └── aliases definitions (sources `~/.dotfiles_aliases`)
│ ├── functions/ │ ├── colors.sh
│ │    └── functions definitions. ADD .zsh files here to include more
│ ├── colors.zsh
│ │     └── ANSI color escapes │ │     └── ANSI color escapes
│ ├── ansible │ ├── functions.sh
│ │    └── ansible roles/vars │ │     └── contains function definitions (sources `~/.dotfiles_functions`)
│ ├── brethil_dotfile.sh: │ ├── install.sh
│ │    └── main configuration file │ │     └── main install script
│ ├── zsh_plugins.txt │ └── brethil_dotfile.sh:
│ │     zsh plugins sourced by antidote       └── This file should be sourced by your `.zshrc`
├──────── antibody plugins ────────
│ ├── antibody_plugins_arch.txt
│ └── antibody_plugins.txt
├──────── oh-my-zsh themes ──────── ├──────── oh-my-zsh themes ────────
│ └── themes │ ├── brethil.zsh-theme
│     ├─ brethil.zsh-theme │ └── brethil-minimal.zsh-theme
│     └─ brethil-minimal.zsh-theme
├──────── Misc rc files──────── ├──────── Misc rc files────────
│ ├── gitconfig │ ├── gitconfig
│ │     └── git configuration │ │     └── git configuration
│ ├── ipython/ │ ├── ackrc
│ │    ├── ipython configs │ │     └── `ack`'s rc: a grep-like text finder
│ ├── ipython
│ │     ├── profile_default
│ │     ├── ipython_config.py
│ │     ├── startup
│ │     ├── 11-autoreload.py
│ │     └── README
│ ├── vim │ ├── vim
│ │    ├── vimrc │ │    ├── vimrc
│ │    │ └── main vim rc │ │    │ └── main vim rc
@ -44,55 +42,84 @@ My own dotfiles. `zsh` configuration based on [antidote](https://github.com/matt
│ │    │ └── plugins configuration │ │    │ └── plugins configuration
│ │    ├── shortcuts.vim │ │    ├── shortcuts.vim
│ │    │ └── vim shortcuts definitions │ │    │ └── vim shortcuts definitions
│ │    └── functions.vim │ │    ├── functions.vim
│ │      └── miscellaneous vim function │ │    │ └── miscellaneous vim function
│ │    └── twilight256.vim
│ │      └── an old colorscheme
│ └── pdbrc.py │ └── pdbrc.py
     └── pdb++ rc (a drop-in replacement for pdb)      └── pdb++'s rc (a drop-in replacement for pdb)
├──────── Other ───────────── ├──────── Other ─────────────
├── extras/check_for_update.zsh ├── check_for_update.sh
     └── selfupdate script      └── selfupdate script
└── useful_commands └── useful_commands
## Installation ## Installation
### With ansible:
```bash
bash dev/add_community.general.sh # only if community.general is not installed
ansible-playbook -v -i <hosts file> playbook.yml
```
This playbook can be tested [with a docker container](dev/README.md)
### Manually
```bash
git clone https://git.decapod.one/brethil/dotfiles ~/.dotfiles git clone https://git.decapod.one/brethil/dotfiles ~/.dotfiles
cat <<EOF >> .zshrc cd .dotfiles && bash install.sh
export DOTFILES=~/.dotfiles
source \$DOTFILES/brethil_dotfile.sh
EOF
ln -s ~/.dotfiles/vim/vimrc ~/.vimrc
```
## Updating
A self-update mechanism is included. It asks for confirmation to pull the latest changes A self-update mechanism is included. It asks for confirmation to pull the latest changes
from the git repo every two weeks. This also updates the git-sourced repositories installed from the git repo every two weeks. This also updates the git-sourced repositories installed
by the install script. The self-update routine can be called manually by calling by the install script. The self-update routine can be called manually by calling
```bash
dotfiles_selfupdate dotfiles_selfupdate
```
This can be disabling by setting the `DISABLE_DOTFILES_AUTO_UPDATE` env var before before sourcing `brethil_dotfile.sh` If you do not want to run the installer script, you can just add source `brethil_dotfile.sh`
in your `.zshrc`. This requires antibody installed.
## Try it out ### Available Functions
Docker images are regularly built, and they include a full development environment (hence are quite large) 0. `cheat`: show cheat sheet for commands using cheat.sh (`cheat <commandname>`)
1. Quickly edit/reload profile (`esource`/`resource`)
2. `dockertags` list all tags for a given docker image
3. `color` to print colored text (see 3. in the Misc section):
```bash color $Red "This will be printed in red"
docker run -it registry.decapod.one/brethil/dotfiles color $Yellow "This will be printed in red"
```
4. `mecp` to copy files back to the machine from wich you are ssh-ing.
For this to work an ssh tunnel with `Remoteforward` is needed:
ssh -R 22:localhost:2222 YOURHOSTNAMEHERE
or specify this in `~/.ssh/config` for a persistent configuration:
Host YOURHOSTNAMEHERE
Remoteforward 2222 localhost:22
This can be enabled in `~/.ssh/config` globally for all hosts by uncommenting the relevant `Host * Remoteforward`.
You might have to manually edit the username in the `mecp` definition in `functions.sh` if this is
different between the two machines. `mecp` copies by default on the local machine on `~/Desktop/`
5. Many more. Use `list_functions` to list defined functions and a small description
### Files/Folders
1. `~/bin`, `~/git`, `~/projects` folders
2. ssh config (`~/.ssh/config`):
- Create ssh keys if not defined already
- Keep connections alive by increasing timeout time
- Include multiplexer to allow quick multiple connections to the same host
- (Optional: Compression, this should allow more responsive shells with slow connections,
but will slow things down when copying large files. My suggestion is to have compression enabled
on a by-host basis in `~/.ssh/config`)
3. `brethil.zsh-theme`, `brethil-minimal.zsh-themes`, themes for oh-my-zsh,
symlinked in `$ZSH/custom/themes` (`$ZSH=~/.oh-my-zsh`)
4. `~/.dotfiles_functions`, `~/.dotfiles_aliases` are sourced by this dotfiles, allowing for custom functions/aliases
5. useful_commands contains a list of useful commands (the first rule of the tautology club...)
### Misc
1. Colored output (via `grc`) for several commands.
2. Easy names for ANSI color escapes (Black, Red, Green, Yellow, Blue, Cyan, Purple, White, CLEAR), for example:
echo -e "${Green}This text will be green${CLEAR}"
will result in green text. Use `$CLEAR` to clear previous escape sequences add B before the variable (check `colors.sh`)
name to use **bold** and U to underline (examples: `$BRed`, `$UBlack` for bold red and underlined black)
3. Autoupdate script running every two weeks, autoupdate function: `dotfiles_selfupdate` (or `git pull` from `$DOTFILES`folder)
4. Automatic fix of the`SSH_AUTH_SOCK`environment variable:`~/.ssh/rc` is installed run on every ssh login,
and updates a symlink pointing (`~/.ssh/ssh_auth_sock`). `SSH_AUTH_SOCK`points to this (set in`brethil_dotfile.sh`).
The idea is that if the user is logging in using `ssh -A`, and using tmux, it will be possible to use
the remote socket over different sessions by always using the symlink.

461
ackrc Normal file
View File

@ -0,0 +1,461 @@
--ignore-file=match:tags
--ignore-dir=build
--ignore-dir=dist
--ignore-dir=node-modules
--ignore-dir=.venv
--ignore-ack-defaults
# Vue
--type-add=vue:ext:vue
# This is the default ackrc for ack version v3.3.1.
# There are four different ways to match
#
# is: Match the filename exactly
#
# ext: Match the extension of the filename exactly
#
# match: Match the filename against a Perl regular expression
#
# firstlinematch: Match the first 250 characters of the first line
# of text against a Perl regular expression. This is only for
# the --type-add option.
### Directories to ignore
# Bazaar
# https://bazaar.canonical.com/
--ignore-directory=is:.bzr
# Codeville
# http://freshmeat.sourceforge.net/projects/codeville
--ignore-directory=is:.cdv
# Interface Builder (Xcode)
# https://en.wikipedia.org/wiki/Interface_Builder
--ignore-directory=is:~.dep
--ignore-directory=is:~.dot
--ignore-directory=is:~.nib
--ignore-directory=is:~.plst
# Git
# https://git-scm.com/
--ignore-directory=is:.git
# When submodules are used, .git is a file.
--ignore-file=is:.git
# Mercurial
# https://www.mercurial-scm.org/
--ignore-directory=is:.hg
# Quilt
# https://directory.fsf.org/wiki/Quilt
--ignore-directory=is:.pc
# Subversion
# https://subversion.apache.org/
--ignore-directory=is:.svn
# Monotone
# https://www.monotone.ca/
--ignore-directory=is:_MTN
# CVS
# https://savannah.nongnu.org/projects/cvs
--ignore-directory=is:CVS
# RCS
# https://www.gnu.org/software/rcs/
--ignore-directory=is:RCS
# SCCS
# https://en.wikipedia.org/wiki/Source_Code_Control_System
--ignore-directory=is:SCCS
# darcs
# http://darcs.net/
--ignore-directory=is:_darcs
# Vault/Fortress
--ignore-directory=is:_sgbak
# autoconf
# https://www.gnu.org/software/autoconf/
--ignore-directory=is:autom4te.cache
# Perl module building
--ignore-directory=is:blib
--ignore-directory=is:_build
# Perl Devel::Cover module's output directory
# https://metacpan.org/release/Devel-Cover
--ignore-directory=is:cover_db
# Node modules created by npm
--ignore-directory=is:node_modules
# CMake cache
# https://www.cmake.org/
--ignore-directory=is:CMakeFiles
# Eclipse workspace folder
# https://eclipse.org/
--ignore-directory=is:.metadata
# Cabal (Haskell) sandboxes
# https://www.haskell.org/cabal/users-guide/installing-packages.html
--ignore-directory=is:.cabal-sandbox
# Python caches
# https://docs.python.org/3/tutorial/modules.html
--ignore-directory=is:__pycache__
--ignore-directory=is:.pytest_cache
# macOS Finder remnants
--ignore-directory=is:__MACOSX
--ignore-file=is:.DS_Store
### Files to ignore
# Backup files
--ignore-file=ext:bak
--ignore-file=match:/~$/
# Emacs swap files
--ignore-file=match:/^#.+#$/
# vi/vim swap files https://www.vim.org/
--ignore-file=match:/[._].*[.]swp$/
# core dumps
--ignore-file=match:/core[.]\d+$/
# minified Javascript
--ignore-file=match:/[.-]min[.]js$/
--ignore-file=match:/[.]js[.]min$/
# minified CSS
--ignore-file=match:/[.]min[.]css$/
--ignore-file=match:/[.]css[.]min$/
# JS and CSS source maps
--ignore-file=match:/[.]js[.]map$/
--ignore-file=match:/[.]css[.]map$/
# PDFs, because they pass Perl's -T detection
--ignore-file=ext:pdf
# Common graphics, just as an optimization
--ignore-file=ext:gif,jpg,jpeg,png
# Common archives, as an optimization
--ignore-file=ext:gz,tar,tgz,zip
# Python compiles modules
--ignore-file=ext:pyc,pyd,pyo
# C extensions
--ignore-file=ext:so
# Compiled gettext files
--ignore-file=ext:mo
### Filetypes defined
# Makefiles
# https://www.gnu.org/s/make/
--type-add=make:ext:mk
--type-add=make:ext:mak
--type-add=make:is:makefile
--type-add=make:is:Makefile
--type-add=make:is:Makefile.Debug
--type-add=make:is:Makefile.Release
--type-add=make:is:GNUmakefile
# Rakefiles
# https://rake.rubyforge.org/
--type-add=rake:is:Rakefile
# CMake
# https://cmake.org/
--type-add=cmake:is:CMakeLists.txt
--type-add=cmake:ext:cmake
# Actionscript
--type-add=actionscript:ext:as,mxml
# Ada
# https://www.adaic.org/
--type-add=ada:ext:ada,adb,ads
# ASP
# https://docs.microsoft.com/en-us/previous-versions/office/developer/server-technologies/aa286483(v=msdn.10)
--type-add=asp:ext:asp
# ASP.Net
# https://dotnet.microsoft.com/apps/aspnet
--type-add=aspx:ext:master,ascx,asmx,aspx,svc
# Assembly
--type-add=asm:ext:asm,s
# DOS/Windows batch
--type-add=batch:ext:bat,cmd
# ColdFusion
# https://en.wikipedia.org/wiki/ColdFusion
--type-add=cfmx:ext:cfc,cfm,cfml
# Clojure
# https://clojure.org/
--type-add=clojure:ext:clj,cljs,edn,cljc
# C
# .xs are Perl C files
--type-add=cc:ext:c,h,xs
# C header files
--type-add=hh:ext:h
# CoffeeScript
# https://coffeescript.org/
--type-add=coffeescript:ext:coffee
# C++
--type-add=cpp:ext:cpp,cc,cxx,m,hpp,hh,h,hxx
# C++ header files
--type-add=hpp:ext:hpp,hh,h,hxx
# C#
--type-add=csharp:ext:cs
# CSS
# https://www.w3.org/Style/CSS/
--type-add=css:ext:css
# Dart
# https://dart.dev/
--type-add=dart:ext:dart
# Delphi
# https://en.wikipedia.org/wiki/Embarcadero_Delphi
--type-add=delphi:ext:pas,int,dfm,nfm,dof,dpk,dproj,groupproj,bdsgroup,bdsproj
# Elixir
# https://elixir-lang.org/
--type-add=elixir:ext:ex,exs
# Emacs Lisp
# https://www.gnu.org/software/emacs
--type-add=elisp:ext:el
# Erlang
# https://www.erlang.org/
--type-add=erlang:ext:erl,hrl
# Fortran
# https://en.wikipedia.org/wiki/Fortran
--type-add=fortran:ext:f,f77,f90,f95,f03,for,ftn,fpp
# Go
# https://golang.org/
--type-add=go:ext:go
# Groovy
# https://www.groovy-lang.org/
--type-add=groovy:ext:groovy,gtmpl,gpp,grunit,gradle
# GSP
# https://gsp.grails.org/
--type-add=gsp:ext:gsp
# Haskell
# https://www.haskell.org/
--type-add=haskell:ext:hs,lhs
# HTML
--type-add=html:ext:htm,html,xhtml
# Jade
# http://jade-lang.com/
--type-add=jade:ext:jade
# Java
# https://www.oracle.com/technetwork/java/index.html
--type-add=java:ext:java,properties
# JavaScript
--type-add=js:ext:js
# JSP
# https://www.oracle.com/technetwork/java/javaee/jsp/index.html
--type-add=jsp:ext:jsp,jspx,jspf,jhtm,jhtml
# JSON
# https://json.org/
--type-add=json:ext:json
# Kotlin
# https://kotlinlang.org/
--type-add=kotlin:ext:kt,kts
# Less
# http://www.lesscss.org/
--type-add=less:ext:less
# Common Lisp
# https://common-lisp.net/
--type-add=lisp:ext:lisp,lsp
# Lua
# https://www.lua.org/
--type-add=lua:ext:lua
--type-add=lua:firstlinematch:/^#!.*\blua(jit)?/
# Markdown
# https://en.wikipedia.org/wiki/Markdown
--type-add=markdown:ext:md,markdown
# We understand that there are many ad hoc extensions for markdown
# that people use. .md and .markdown are the two that ack recognizes.
# You are free to add your own in your ackrc file.
# Matlab
# https://en.wikipedia.org/wiki/MATLAB
--type-add=matlab:ext:m
# Objective-C
--type-add=objc:ext:m,h
# Objective-C++
--type-add=objcpp:ext:mm,h
# OCaml
# https://ocaml.org/
--type-add=ocaml:ext:ml,mli,mll,mly
# Perl
# https://perl.org/
--type-add=perl:ext:pl,pm,pod,t,psgi
--type-add=perl:firstlinematch:/^#!.*\bperl/
# Perl tests
--type-add=perltest:ext:t
# Perl's Plain Old Documentation format, POD
--type-add=pod:ext:pod
# PHP
# https://www.php.net/
--type-add=php:ext:php,phpt,php3,php4,php5,phtml
--type-add=php:firstlinematch:/^#!.*\bphp/
# Plone
# https://plone.org/
--type-add=plone:ext:pt,cpt,metadata,cpy,py
# Python
# https://www.python.org/
--type-add=python:ext:py
--type-add=python:firstlinematch:/^#!.*\bpython/
# R
# https://www.r-project.org/
--type-add=rr:ext:R
# reStructured Text
# https://docutils.sourceforge.io/rst.html
--type-add=rst:ext:rst
# Ruby
# https://www.ruby-lang.org/
--type-add=ruby:ext:rb,rhtml,rjs,rxml,erb,rake,spec
--type-add=ruby:is:Rakefile
--type-add=ruby:firstlinematch:/^#!.*\bruby/
# Rust
# https://www.rust-lang.org/
--type-add=rust:ext:rs
# Sass
# https://sass-lang.com
--type-add=sass:ext:sass,scss
# Scala
# https://www.scala-lang.org/
--type-add=scala:ext:scala
# Scheme
# https://groups.csail.mit.edu/mac/projects/scheme/
--type-add=scheme:ext:scm,ss
# Shell
--type-add=shell:ext:sh,bash,csh,tcsh,ksh,zsh,fish
--type-add=shell:firstlinematch:/^#!.*\b(?:ba|t?c|k|z|fi)?sh\b/
# Smalltalk
# http://www.smalltalk.org/
--type-add=smalltalk:ext:st
# Smarty
# https://www.smarty.net/
--type-add=smarty:ext:tpl
# SQL
# https://www.iso.org/standard/45498.html
--type-add=sql:ext:sql,ctl
# Stylus
# http://stylus-lang.com/
--type-add=stylus:ext:styl
# SVG
# https://en.wikipedia.org/wiki/Scalable_Vector_Graphics
--type-add=svg:ext:svg
# Swift
# https://developer.apple.com/swift/
--type-add=swift:ext:swift
--type-add=swift:firstlinematch:/^#!.*\bswift/
# Tcl
# https://www.tcl.tk/
--type-add=tcl:ext:tcl,itcl,itk
# TeX & LaTeX
# https://www.latex-project.org/
--type-add=tex:ext:tex,cls,sty
# Template Toolkit (Perl)
# http//template-toolkit.org/
--type-add=ttml:ext:tt,tt2,ttml
# Typescript
# https://www.typescriptlang.org/
--type-add=ts:ext:ts,tsx
# Visual Basic
--type-add=vb:ext:bas,cls,frm,ctl,vb,resx
# Verilog
--type-add=verilog:ext:v,vh,sv
# VHDL
# http://www.eda.org/twiki/bin/view.cgi/P1076/WebHome
--type-add=vhdl:ext:vhd,vhdl
# Vim
# https://www.vim.org/
--type-add=vim:ext:vim
# XML
# https://www.w3.org/TR/REC-xml/
--type-add=xml:ext:xml,dtd,xsd,xsl,xslt,ent,wsdl
--type-add=xml:firstlinematch:/<[?]xml/
# YAML
# https://yaml.org/
--type-add=yaml:ext:yaml,yml

101
aliases.sh Executable file
View File

@ -0,0 +1,101 @@
###########################
#### ALIAS #
###########################
####
#### Easier life (MAC SPECIFIC)
####
if [[ "$(uname)" == "Darwin" ]]; then
alias o="open"
alias ls="ls -G"
## Colorize system.log contents (with grc), and inspect with less.
alias console="grc cat /var/log/system.log | sort -r | less -R"
## Quicklook shortcut
alias quicklook='qlmanage -px 2>/dev/null'
alias ql='quicklook'
## Airport command line interface
alias airport='/System/Library/PrivateFrameworks/Apple80211.framework/Resources/airport'
## Flush dns cache
#alias dnsflushcache='sudo discoveryutil mdnsflushcache' # used to work until 10.6
alias dnsflushcache='sudo killall -HUP mDNSResponder' # Works up until 10.9 and after 10.10.4
alias lsrt='ls -G -lrt | tail -5'
else
alias ls='ls --color'
fi
####
#### Easier life (everything)
alias dot="cd $DOTFILES"
#### Audible bell
alias bell='echo -en "\007"'
alias grep="grep --colour=auto"
##############
## ls aliases
############
# ls -al, only show files that start with a dot
alias lsdot="ls -al | awk '\$9 ~ /^\./ {print \$0}'"
alias lt='ls -lrt | tail -10'
alias ll='ls -lhL' #long ls output
alias ka="killall"
alias ipy='ipython'
alias ipyl='ipython --pylab'
## Show the last 10 modified files
if [[ ! "$(uname)" == "Darwin" ]]; then
alias lsrt="ls -lrt | tail -10"
fi
## Stress one CPU core
alias stress='yes >> /dev/null'
# define ssh without controlmaster
alias ssh1="ssh -o ControlMaster=no"
# git: useful_stuff
alias git_sort_branches_by_date="git for-each-ref --sort=committerdate refs/heads/ --format='%(committerdate:short) %(refname:short)'"
alias gl5='git log -n 5'
alias pvim='poetry run vim'
# grc: try to source the definitions file in /etc/grc.zsh (print a warning if it does not exist)
if [[ -f /etc/grc.zsh ]] ; then
source /etc/grc.zsh
elif [[ -f /usr/local/etc/grc.zsh ]] ; then
source /usr/local/etc/grc.zsh
else
echo "Could not grc completion file (checked /etc/grc.zsh and /usr/local/etc/grc.zsh. Command colorization will not work. Check your grc configuration (is grc installed?)" 1>&2
fi
alias powerline_update="pip install --upgrade --user 'git+https://github.com/powerline/powerline.git@develop#powerline'"
alias gcf='git commit --fixup=HEAD'
alias gcaf='git commit -a --fixup=HEAD'
alias gls="git log --pretty=oneline --abbrev-commit" # gls: Git Log Short
alias watcha='watch ' # note the space after watch. This makes watch work with aliases
# A short version of docker ps
alias dps='docker ps --format "table {{.Image}}\t{{.RunningFor}}\t{{.Status}}\t{{.Ports}}\t{{.Names}}"'
# Get ip for a docker container, usage: `docker inspect <container> | dockerip`
alias dockerip="jq -r '.[].NetworkSettings.Networks.bridge.IPAddress'"
alias pvim='poetry run vim'
alias pshell='poetry shell'
# dotfiles user aliases
if [[ -f ~/.dotfiles_aliases ]]; then
source $HOME/.dotfiles_aliases
fi
# source ssh aliases
if [[ -f $HOME/.ssh_aliases ]]; then
source $HOME/.ssh_aliases
fi

View File

@ -1,4 +0,0 @@
# aliases
Place custom alias definitions in this folder, with a `.zsh` extension.
These files will be sourced on startup

View File

@ -1,88 +0,0 @@
###########################
#### ALIAS #
###########################
####
#### Easier life (MAC SPECIFIC)
####
if [[ "$(uname)" == "Darwin" ]]; then
alias o="open"
alias ls="ls -G"
## Colorize system.log contents (with grc), and inspect with less.
alias console="grc cat /var/log/system.log | sort -r | less -R"
## Quicklook shortcut
alias quicklook='qlmanage -px 2>/dev/null'
alias ql='quicklook'
## Airport command line interface
alias airport='/System/Library/PrivateFrameworks/Apple80211.framework/Resources/airport'
## Flush dns cache
#alias dnsflushcache='sudo discoveryutil mdnsflushcache' # used to work until 10.6
alias dnsflushcache='sudo killall -HUP mDNSResponder' # Works up until 10.9 and after 10.10.4
alias lsrt='ls -G -lrt | tail -5'
else
alias ls='ls --color'
fi
####
#### Easier life (everything)
alias dot="cd $DOTFILES"
#### Audible bell
alias bell='echo -en "\007"'
alias grep="grep --colour=auto"
alias grepi="grep -i"
##############
## ls aliases
############
# ls -al, only show files that start with a dot
alias lsdot="ls -al | awk '\$9 ~ /^\./ {print \$0}'"
alias lt='ls -lrt | tail -10'
alias ll='ls -lhL' #long ls output
alias ka="killall"
alias ipy='ipython'
alias ipyl='ipython --pylab'
alias treep='tree -I __pycache__'
## Show the last 10 modified files
if [[ ! "$(uname)" == "Darwin" ]]; then
alias lsrt="ls -lrt | tail -10"
fi
## Stress one CPU core
alias stress='yes >> /dev/null'
# ssh forcing a new connection (no persistent)
alias ssh1="ssh -o ControlMaster=yes -o ControlPersist=no"
alias watcha='watch ' # note the space after watch. This makes watch work with aliases
# A short version of docker ps
alias dps='docker ps --format "table {{.Image}}\t{{.RunningFor}}\t{{.Status}}\t{{.Ports}}\t{{.Names}}"'
# Get ip for a docker container, usage: `docker inspect <container> | dockerip`
alias dockerip="jq -r '.[].NetworkSettings.Networks.bridge.IPAddress'"
alias pvim='poetry run vim'
alias pshell='poetry shell'
alias venv='source .venv/bin/activate'
# Run fzf with file preview
alias pf="fzf --preview='BAT_STYLE='header,changes' bat --color=always {}' --bind shift-up:preview-page-up,shift-down:preview-page-down"
# dvc
alias dst='dvc status'
alias dstc='dvc status --cloud'
alias drp='dvc repro'
alias drps='dvc repro -s'
alias -g J="| jq "
# These two depend on oh-my-zsh's clipcopy/clippaste functions
alias -g C='| clipcopy'
alias -g P='clippaste'

View File

@ -1,8 +0,0 @@
# git: useful_stuff
alias git-sort-branches-by-date="git for-each-ref --sort=committerdate refs/heads/ --format='%(committerdate:short) %(refname:short)'"
alias gswr="git-switch-recent-branch" # defined in functions/git.zsh
alias gl5='git log -n 5'
alias gs='git status'
alias gcfx='git-fixup'
alias gls="git log --pretty=oneline --abbrev-commit" # gls: Git Log Short
alias glsu='git ls-files --others --exclude-standard'

View File

@ -1,17 +0,0 @@
# Archlinux User Repository (AUR)
Role to install [Archlinux User Repository (AUR)](https://aur.archlinux.org/packages) packages.
Add extra packages to the defaults in [vars/main.yml](vars/main.yml) by providing the `aur_extra` variable:
```yaml
- hosts: all
vars:
aur_extra:
- bretellofier
- yay
roles:
- role: aur-packages
```

View File

@ -1,6 +0,0 @@
---
collections:
# - { name: community.general, version: 3.1.0 }
- community.general
# dependencies:
# - role: yay

View File

@ -1,24 +0,0 @@
---
- debug:
msg: "Installing AUR package: {{ package }}"
- name: Clone package repo
become: true
become_method: sudo
become_user: nobody
git:
repo: "https://aur.archlinux.org/{{ package }}.git"
dest: "/home/build/{{ package }}"
# version: master
clone: true
force: true
- name: Build package
become: true
become_method: sudo
become_user: nobody
shell: |
cd "/home/build/{{package}}"
makepkg --force --syncdeps --rmdeps --noconfirm --install
environment:
GOCACHE: /tmp/go_cache/

View File

@ -1,34 +0,0 @@
---
- name: Create build directory
file:
path: "/home/build"
state: directory
mode: "0700"
owner: nobody
- name: Install aur packages
block:
- name: Allow nobody user to run pacman
community.general.sudoers:
name: allow-nobody-pacman
user: nobody
commands:
- /usr/sbin/pacman
# noexec: true # required by makepkg
state: present
- name: Install packages
include_tasks: ./build_package.yml
vars:
package: "{{ item }}"
loop: "{{ aur_packages + aur_extra }} "
always:
- name: Disallow nobody user to run pacman
community.general.sudoers:
name: allow-nobody-pacman
user: nobody
commands:
- /usr/sbin/pacman
noexec: true
state: absent

View File

@ -1,4 +0,0 @@
aur_packages:
- bretellofier
- yay
aur_extra: []

View File

@ -1,5 +0,0 @@
# dotfiles
Role to install dotfiles and do initial configuration of a new host.
Installed packages can be found in [vars/main.yml](vars/main.yml).

View File

@ -1,3 +0,0 @@
---
collections:
- community.general

View File

@ -1,155 +0,0 @@
---
- name: Install required system packages (debian)
apt:
install_recommends: false
update_cache: true
pkg: "{{ packages + packages_debian }}"
state: present
when: ansible_facts['os_family'] == "Debian"
become: true
- name: Install required system packages (arch)
pacman:
update_cache: true
name: "{{ packages + packages_archlinux }}"
state: present
when: ansible_facts['os_family'] == "Archlinux"
become: true
- name: Clone dotfiles repo
git:
repo: https://git.decapod.one/brethil/dotfiles
dest: "{{ dotfiles_path }}"
clone: true
update: false
register: git_clone_result
tags:
- dotfiles-update
- debug:
var: git_clone_result['after']
when: git_clone_result['before'] == "null"
tags:
- dotfiles-update
- name: Update dotfiles repo
git:
repo: https://git.decapod.one/brethil/dotfiles
dest: "{{ dotfiles_path }}"
clone: false
update: false
when: git_clone_result['before'] != "null"
register: git_update_result
tags:
- dotfiles-update
- debug:
var: git_update_result['after']
when: git_update_result['before'] != "null"
- name: directories
file:
dest: "{{ item }}"
state: directory
mode: "0700"
loop: "{{ directories }}"
vars:
directories:
- "$HOME/bin"
- "$HOME/projects"
- "$HOME/git"
- "$HOME/.config/git"
- "$HOME/.ssh/"
- "$HOME/.ssh/sockets"
- "$HOME/.ipython/profile_default"
- name: Set zsh as default shell
user:
name: "{{ ansible_user }}"
shell: /usr/bin/zsh
become: true
- name: Update zshrc
blockinfile:
path: $HOME/.zshrc
marker: "# {mark} brethil dotfiles"
block: |
export DOTFILES={{ dotfiles_path }}
source $DOTFILES/brethil_dotfile.sh
create: true
mode: 600
- name: Update .ssh/config
blockinfile:
path: $HOME/.ssh/config
marker: "# {mark} brethil dotfiles"
insertbefore: "BOF"
block: |
TCPKeepAlive=yes
ServerAliveCountMax=6
## Uncomment to enable compression for all ssh sessions
#Compression=yes
ControlMaster auto
ControlPath ~/.ssh/sockets/%r@%n:%p
ControlPersist yes
Host *
ServerAliveInterval 300
create: true
- name: dotfiles symlinks
file:
src: "{{ dotfiles_path }}/{{ item.key }}"
dest: "{{ item.value }}"
state: link
force: yes
loop: "{{ files | dict2items }}"
vars:
files:
"tmux.conf": "~/.tmux.conf"
"vim/vimrc": "~/.vimrc"
"pdbrc.py": "~/.pdbrc.py"
"gitignore": "~/.config/git/ignore"
"ipython/profile_default/ipython_config.py": "~/.ipython/profile_default/ipython_config.py"
"ipython/profile_default/startup": "~/.ipython/profile_default/startup"
- name: Exec vim undodir migration (if required)
command: |
mv ${HOME}/.vim_runtime/temp_dirs/undodir ${HOME}/.vim/undo
args:
removes: .vim_runtime/temp_dirs/undodir
- name: Install and update vim plugins
command: |
vim -c 'PlugInstall|PlugUpdate|qa!'
environment:
- DOTFILES: "{{ dotfiles_path }}"
tags:
- dotfiles-update
- name: Get git config facts
community.general.git_config:
name: "include.path"
scope: global
register: config_value
- name: Set up git config include if required
community.general.git_config:
name: "include.path"
value: "{{ dotfiles_path }}/gitconfig"
scope: global
when: config_value is not defined
- name: check gitignore migration
stat: path=${HOME}/.gitignore
register: gitignore
- name: gitignore migration
shell: |
set -eu
mkdir -p ${HOME}/.config/git
ln -s {{ dotfiles_path }}/gitignore ${HOME}/.config/git/ignore
rm -f ~/.gitignore
when: gitignore.stat.exists

View File

@ -1,36 +0,0 @@
---
dotfiles_path: "$HOME/.dotfiles"
packages:
- "bmon"
- "byobu"
- "ccze"
- "curl"
- "fzf"
- "git"
- "grc"
- "htop"
- "iotop"
- "nmap"
- "ripgrep"
- "tmux"
- "tree"
- "vim"
- "zsh"
packages_debian:
- "bat"
- "ipython3"
- "mtr-tiny"
- "python3-pip"
- "python3-setuptools"
- "virtualenv"
packages_archlinux:
- "ansible-language-server"
- "bash-language-server"
- "base-devel"
- "bat"
- "ipython"
- "man"
- "mtr"
- "python-virtualenv"
- "sudo"

View File

@ -1,53 +0,0 @@
---
- name: Create build directory
file:
path: "/home/build"
state: directory
mode: "0700"
owner: nobody
- name: Make sure requirements are installed
community.general.pacman:
update_cache: yes
name:
- base-devel
- git
- go
- sudo
state: present
become: true
- name: Clone yay repo
become: true
become_method: sudo
become_user: nobody
git:
repo: https://aur.archlinux.org/yay.git
dest: /home/build/yay
version: master
clone: true
force: true
- name: build
become: true
become_method: sudo
become_user: nobody
shell: |
cd /home/build/yay
makepkg -f
environment:
- GOCACHE: /tmp/gocache
- ANSIBLE_REMOTE_TMP: /tmp/ansible
- name: Get built package
shell: |
ls -rt /home/build/yay/yay*.pkg.tar.zst | grep -v debug | tail -1
register: yay_package
- debug:
msg: "Built {{ yay_package.stdout }}"
- name: Install yay
community.general.pacman:
name: "{{ yay_package.stdout }}"
state: present

16
antibody_plugins.txt Normal file
View File

@ -0,0 +1,16 @@
robbyrussell/oh-my-zsh
robbyrussell/oh-my-zsh path:plugins/colored-man-pages
robbyrussell/oh-my-zsh path:plugins/common-aliases
robbyrussell/oh-my-zsh path:plugins/docker
robbyrussell/oh-my-zsh path:plugins/docker-compose
robbyrussell/oh-my-zsh path:plugins/git
#robbyrussell/oh-my-zsh path:plugins/kubectl
robbyrussell/oh-my-zsh path:plugins/sudo
robbyrussell/oh-my-zsh path:plugins/vi-mode
robbyrussell/oh-my-zsh path:plugins/pyenv
djui/alias-tips
psprint/zsh-navigation-tools
zdharma/fast-syntax-highlighting
zsh-users/zsh-autosuggestions
zsh-users/zsh-completions
MichaelAquilina/zsh-autoswitch-virtualenv

View File

@ -0,0 +1,2 @@
robbyrussell/oh-my-zsh path:plugins/systemd
robbyrussell/oh-my-zsh path:plugins/archlinux

View File

@ -1,5 +1,3 @@
# vim:ft=zsh ts=2 sw=2 sts=2
local ret_status="%(?:%{$fg_bold[green]%}➜%{$reset_color%}:%{$fg[red]%}➜%{$reset_color%})" local ret_status="%(?:%{$fg_bold[green]%}➜%{$reset_color%}:%{$fg[red]%}➜%{$reset_color%})"
local user="%(#:root@:)" local user="%(#:root@:)"
PROMPT='[%{$fg[red]%}${user}%M%{$reset_color%}][:%{$fg[green]%}%c%{$reset_color%}]$(git_prompt_info) ${ret_status} ' PROMPT='[%{$fg[red]%}${user}%M%{$reset_color%}][:%{$fg[green]%}%c%{$reset_color%}]$(git_prompt_info) ${ret_status} '

126
brethil.zsh-theme Normal file
View File

@ -0,0 +1,126 @@
# vim:ft=zsh ts=2 sw=2 sts=2
# color chart available at https://www.calmar.ws/vim/256-xterm-24bit-rgb-color-chart.html
# %F{202}: orange
# %K{202}: background orange
# 255: white
# See the prompt expansion section in `info zsh` for more info
function user_prompt(){
# root printed on a red background
local USER_PROMPT="%(#.%K{160}%F{255}[root]%k%f.)"
echo "$USER_PROMPT"
# if [[ -n $SSH_CONNECTION ]]; then
# local host="${purple}%B%m%b${default}"
# host="%U${host}%u"
# echo "$host"
# fi
}
function job_prompt() {
local JOB_PROMPT="%(1j.%B%K{202}%F{220} %j %k%b.)" # Shows jobs number on an orange background if there are background jobs
echo "$JOB_PROMPT"
}
function shlvl_prompt() {
local SHLVL_PROMPT
if [[ -n "$BYOBU_PREFIX" ]]; then
SHLVL_PROMPT="%(3L.%K{161}%F{255}%B $((SHLVL-1)) %f%b%k.)" # Shows SHLVL on a magenta background if SHLVL > 1
else
SHLVL_PROMPT="%(2L.%K{161}%F{255}%B %L %f%b%k.)" # Shows SHLVL on a magenta background if SHLVL > 1
fi
echo "$SHLVL_PROMPT"
}
function path_prompt(){
# Shows last 3 items in path if there are more than 4
local PATH_PROMPT="%F{white}[%F{green}%(4~:…/%3~:%~)%F{white}]%f"
echo "$PATH_PROMPT"
}
# PREFIX/SUFFIX are added before/after `git_prompt_info`
ZSH_THEME_GIT_PROMPT_PREFIX="%f%{$fg[yellow]%} "
ZSH_THEME_GIT_PROMPT_SUFFIX="%{$reset_color%}"
ZSH_THEME_GIT_PROMPT_DIRTY=" %{$fg[white]%}%{$fg[red]%}x%{$reset_color%}"
ZSH_THEME_GIT_PROMPT_CLEAN=" %{$fg[white]%}%{$fg[green]%}√%{$reset_color%}"
# The following are part of `git_prompt_status`
# Rules:
# ? : untracked
# * : modified
# + : added
# $ : stashed
ZSH_THEME_GIT_PROMPT_STASHED="%B%F{32}$%b%f" # blue
# ZSH_THEME_GIT_PROMPT_MODIFIED="%{$fg[red]%}✗ " # this is equivalent to DIRTY, if DISABLE_UNTRACKED_FILES_DIRTY is set
ZSH_THEME_GIT_PROMPT_ADDED="%B%F{34}+%b%f" # green
ZSH_THEME_GIT_PROMPT_UNTRACKED="%B%F{red}?%b%f" # red
# The following are part of `git_remote_status`
# ZSH_THEME_GIT_PROMPT_EQUAL_REMOTE="%{$fg[green]%}="
ZSH_THEME_GIT_PROMPT_AHEAD_REMOTE="%F{255}>%f"
ZSH_THEME_GIT_PROMPT_BEHIND_REMOTE="%F{255}<%f"
ZSH_THEME_GIT_PROMPT_DIVERGED_REMOTE="%F{255}<>%f"
function virtualenv_info {
[ -z "$VIRTUAL_ENV" ] && return
local BOLD_PURPLE='%B%F{5}'
local CLEAR='%f%b'
local venv
venv="$(basename "$VIRTUAL_ENV")"
if [[ "$venv" == ".venv" ]]; then
venv="$(basename $(dirname "$VIRTUAL_ENV") )"
fi
echo -n "$BOLD_PURPLE"
echo -n " <$venv> "
echo -n "$CLEAR"
}
function git_prompt() {
if [[ -n "$(git status 2>/dev/null)" ]]; then
local GIT_PROMPT="%F{255}($(git_prompt_info)%B%F{255}|%f%b$(git_prompt_status)$(git_remote_status)%F{255})%f"
echo "$GIT_PROMPT"
else
echo ""
fi
}
function check_last_exit_code() {
local LAST_EXIT_CODE=$?
if [[ $LAST_EXIT_CODE -ne 0 ]]; then
local EXIT_CODE_PROMPT
EXIT_CODE_PROMPT+="%B%F{88}-$LAST_EXIT_CODE-%f%b"
echo "$EXIT_CODE_PROMPT"
fi
}
function return_code_RPS1() {
# For right-side prompt
local return_code="%(?..$(check_last_exit_code))" # for RPS1
echo "$return_code"
}
function ret_status() {
local ret_status="%(?:%B%F{28} →%f%b:%{$fg[red]%}x%{$reset_color%})"
echo "$ret_status"
}
_PROMPT_PROTO='$(virtualenv_info)$(user_prompt)$(path_prompt)$(git_prompt)$(job_prompt)$(shlvl_prompt)'
function prompt_too_long(){
local zero='%([BSUbfksu]|([FK]|){*})'
local stripped="$(echo ${(S%%)_PROMPT_PROTO//$~zero/} | sed "s,\x1B\[[0-9;]*[a-zA-Z],,g" ) "
local prompt_len=${#stripped}
local max_len=$(($COLUMNS/2))
if [[ $prompt_len -ge $max_len ]]; then
echo true
fi
}
PROMPT="$(echo "$_PROMPT_PROTO")"
NEWLINE=$'\n'
PROMPT+='${$(prompt_too_long)/true/${NEWLINE}}'
PROMPT+='$(ret_status) '
# Right prompt is just return code and time
RPS1='$(return_code_RPS1) %F{255}[%*]%f'

View File

@ -1,91 +1,20 @@
# vim:ft=zsh ts=2 sw=2 sts=2 # Check for update, set DISABLE_UPDATE_PROMPT=yes to disable the prompt and automatically update
export LANG=en_US.UTF-8 env DISABLE_UPDATE_PROMPT=$DISABLE_UPDATE_PROMPT DOTFILES="$DOTFILES" zsh -f "$DOTFILES/check_for_update.sh"
# theme-related variables # theme-related variables
export ZSH_CUSTOM="$DOTFILES"
export ZSH_THEME="brethil" export ZSH_THEME="brethil"
export DISABLE_UNTRACKED_FILES_DIRTY=true export DISABLE_UNTRACKED_FILES_DIRTY=true
export VIRTUAL_ENV_DISABLE_PROMPT=true export VIRTUAL_ENV_DISABLE_PROMPT=true
export PATH=$PATH:$HOME/bin # Source all other plugins
source <(antibody init)
export ZSH="$(antibody path robbyrussell/oh-my-zsh)"
antibody bundle < "$DOTFILES/antibody_plugins.txt"
( # main branch migration uname="$(uname -a)"
set -euo pipefail if [[ $uname == *"ARCH"* || $uname == *"MANJARO"* ]]; then
cd $DOTFILES antibody bundle < "$DOTFILES/antibody_plugins_arch.txt"
if [[ $(git branch --show-current) == "master" ]]; then
echo "Migrating to main branch..."
git fetch
git stash
git switch main
git stash pop
git branch -D master
echo "Migration done!"
fi fi
)
if [[ ! -d $DOTFILES/antidote ]]; then
git clone https://github.com/mattmc3/antidote.git ${DOTFILES}/antidote
fi
if [[ -d "$HOME/.cache/antibody" ]]; then
# antibody migration cleanup
rm -rf $HOME/.cache/antibody
fi
export ZSH_CACHE_DIR="${XDG_CACHE_HOME:-$HOME/.cache}/oh-my-zsh"
[[ -d $ZSH_CACHE_DIR ]] || mkdir -p $ZSH_CACHE_DIR/completions
# Lazy-load antidote from its functions directory.
fpath=($DOTFILES/antidote/functions/ $fpath)
autoload -Uz antidote
autoload -Uz compinit && compinit
autoload -Uz bashcompinit && bashcompinit
# Lazy-load antidote and generate the static load file only when needed # TODO: look into deferred loading with zsh-defer
zsh_plugins="$DOTFILES/zsh_plugins"
if [[ ! ${zsh_plugins}.zsh -nt ${zsh_plugins}.txt ]]; then
(
source $DOTFILES/antidote/antidote.zsh
echo "ZSH=$(antidote path ohmyzsh/ohmyzsh)" >${zsh_plugins}.zsh
antidote bundle <${zsh_plugins}.txt >>${zsh_plugins}.zsh
if (( $+commands[systemctl] )); then
antidote bundle robbyrussell/oh-my-zsh path:plugins/systemd >>${zsh_plugins}.zsh
fi
if (( $+commands[pacman] )); then
antidote bundle robbyrussell/oh-my-zsh path:plugins/archlinux >>${zsh_plugins}.zsh
elif (( $+commands[apt-get] )); then
antidote bundle robbyrussell/oh-my-zsh path:plugins/debian >>${zsh_plugins}.zsh
fi
)
fi
source ${zsh_plugins}.zsh
source "$DOTFILES/themes/brethil.zsh-theme"
# Setup completion style
source $DOTFILES/extras/completion_style.zsh
source $DOTFILES/extras/colors.zsh
source $DOTFILES/extras/fzf-tab-config.zsh
if (( $+commands[fd] )); then
export FZF_CTRL_T_COMMAND='fd'
else
export FZF_CTRL_T_COMMAND='find'
fi
export FZF_CTRL_T_OPTS=" --preview-window=right,60% --preview \"bash -c 'if [[ -d \"{}\" ]]; then tree -C \"{}\"; else bat --style=plain --color=always \"{}\"; fi'\" --bind 'ctrl-/:change-preview-window(right,70%|down,40%,border-horizontal|hidden|right)'"
if [[ $(fzf --version | cut -d. -f 2) -ge 52 ]]; then
# only available for fzf 0.52.0+ https://github.com/junegunn/fzf/releases/tag/0.52.0
export FZF_DEFAULT_OPTS="$FZF_DEFAULT_OPTS --highlight-line"
fi
ZSH_HIGHLIGHT_STYLES[comment]='fg=white,bg=gray,bold'
# Enable zsh autocorrection # Enable zsh autocorrection
setopt CORRECT_ALL setopt CORRECT_ALL
@ -101,104 +30,52 @@ setopt INC_APPEND_HISTORY
# Execute commands without verifying after prompt substitution (!!, !$, etc) # Execute commands without verifying after prompt substitution (!!, !$, etc)
setopt NO_HIST_VERIFY setopt NO_HIST_VERIFY
# Silence completion beeps
unsetopt LIST_BEEP
## Misc environment variables ## Misc environment variables
# https://www.xkcd.com/378/ # https://www.xkcd.com/378/
export EDITOR="vim" # if antibody_plugins.txt includes robbyrussell/oh-my-zsh path:plugins/vi-mode, this also sets `bindkey -v` # FIXME export EDITOR="vim" # if antibody_plugins.txt includes robbyrussell/oh-my-zsh path:plugins/vi-mode, this also sets `bindkey -v`
export VI_MODE_RESET_PROMPT_ON_MODE_CHANGE=true # refresh prompt on every mode change
# Fix delete (delete! not backspace) key # Fix delete (delete! not backspace) key
bindkey -a '^[[3~' delete-char bindkey -a '^[[3~' delete-char
export KEYTIMEOUT=50 # reduce the transition time between vim modes to 0.1s export KEYTIMEOUT=1 # reduce the transition time between vim modes to 0.1s
# bindkey -M vicmd 'V' edit-command-line # this remaps `vv` to `V` (but overrides `visual-mode`) # add this if the keytimeout is too slow
if ! grep -q "set editing-mode vi" $HOME/.inputrc &> /dev/null; then export HISTSIZE=100000
echo "set editing-mode vi" >> ~/.inputrc && echo "Warning: set up editing-mode ~/.inputrc" export LANG=en_US.UTF-8
fi export LC_ALL=en_US.UTF-8
export HISTSIZE=10000000
export SAVEHIST=10000000
# zsh-autosuggestions config
export ZSH_AUTOSUGGEST_STRATEGY=(history completion)
export ZSH_AUTOSUGGEST_COMPLETION_IGNORE='* \#*' # prevent completion for comments
# less options # less options
export LESS='-xRF-j12' # -j12: displays 12 lines before search results with / and ? export LESS='-xRF-j12' # -j12: displays 12 lines before search results with / and ?
if (( $+commands[bat] || $+commands[batcat] )); then if [[ "$(command -v bat)" ]]; then
export BAT_STYLE='grid,numbers,changes,snip' alias cat=bat
if (( $+commands[bat] )); then cmd=bat else cmd=batcat fi
alias cat=$cmd
export PAGER=$cmd
export BAT_PAGER="less $LESS" export BAT_PAGER="less $LESS"
export PAGER=bat
if [[ -n $THEME_PREFER_LIGHT ]]; then
export BAT_THEME="gruvbox-light"
else
export BAT_THEME="gruvbox-dark"
fi
## this breaks symlink testing with [ -h ], best not to activate it
# alias -g -- -h='-h 2>&1 | bat --language=help --style=plain'
alias bathelp="$cmd --language=help --style=plain"
alias -g -- --help='--help 2>&1 | bathelp '
fi fi
if [[ $SSH_CLIENT ]]; then if [[ $SSH_CLIENT ]]; then
export SSH_AUTH_SOCK=$HOME/.ssh/ssh_auth_sock export SSH_AUTH_SOCK=$HOME/.ssh/ssh_auth_sock
fi fi
# Automatically enable/disable virtualenv on chdir/step # pip completions
export DOTFILES_AUTOSWITCH_VIRTUALENV=1 if which pip &>/dev/null ; then
eval "$(pip completion --zsh)"
fi
alias esource='$EDITOR $HOME/.zshrc' alias esource='$EDITOR $HOME/.zshrc'
alias resource='source $HOME/.zshrc' alias resource='source $HOME/.zshrc'
alias dotedit='$EDITOR $DOTFILES/brethil_dotfile.sh' alias dotedit='$EDITOR $DOTFILES/brethil_dotfile.sh'
# Custom definitions files # Custom definitions files
alias funedit='$EDITOR ~/.dotfiles_functions' alias funedit='$EDITOR ~/.dotfiles_functions.sh'
alias aledit='$EDITOR ~/.dotfiles_aliases' alias aledit='$EDITOR ~/.dotfiles_aliases.sh'
export p="${HOME}/projects"
export g="${HOME}/git"
for defname in aliases functions ; do
for def in $DOTFILES/$defname/*zsh ; do
source $def
done
done
unset def defname
# Extras # Extras
functions_file=~/.dotfiles_functions functions_file=$DOTFILES/functions.sh # Function definitions
aliases_file=~/.dotfiles_aliases aliases_file=$DOTFILES/aliases.sh # Aliases definitions
ssh_file=~/.ssh_aliases colors_file=$DOTFILES/colors.sh # Colors definitions
( # migration of old format
if [[ -f ${functions_file}.sh ]]; then
echo "Migrating ${functions_file}.sh to ${functions_file}"
mv ${functions_file}{.sh,}
fi
if [[ -f ${aliases_file}.sh ]]; then
echo "Migrating ${aliases_file}.sh to ${aliases_file}"
mv ${aliases_file}{.sh,}
fi
)
# Source extras # Source extras
test -f "${functions_file}" && source "${functions_file}" if [ -f "$functions_file" ]; then source "$functions_file"; else echo "[brethil-dotfiles] Couldn't load functions: $functions_file"; fi
test -f "${aliases_file}" && source "${aliases_file}" if [ -f "$aliases_file" ]; then source "$aliases_file"; else echo "[brethil-dotfiles] Couldn't load aliases: $aliases_file"; fi
test -f "${ssh_file}" && source "${ssh_file}" if [ -f "$colors_file" ]; then source "$colors_file"; else echo "[brethil-dotfiles] Couldn't load colors: $colors_file";fi
# autoload -U compinit && compinit ### SETUP PATHS ####
# autoload -U bashcompinit && bashcompinit export PATH=$PATH:$HOME/bin
# Set DISABLE_DOTFILES_AUTOUPDATE=true to disable updates
source "${DOTFILES}/extras/check_for_update.zsh"

78
check_for_update.sh Executable file
View File

@ -0,0 +1,78 @@
#!/usr/bin/env zsh
#
# brethil, brutally copied from https://github.com/robbyrussell/oh-my-zsh/blob/master/tools/check_for_upgrade.sh
# This also tries to update amix's vimrc and runs "antigen update"
# 14 July 2017
zmodload zsh/datetime
function _current_epoch() {
echo $(( $EPOCHSECONDS / 60 / 60 / 24 ))
}
function _update_dotfiles_update() {
echo "LAST_EPOCH=$(_current_epoch)" >! ~/.dotfiles-update
}
function _upgrade_dotfiles() {
(cd $DOTFILES; git pull -q --rebase && echo "Succesfully upgraded dotfiles" || echo "Could not upgrade dotfiles.")
# amix's vimrc update
amix_vimrc=$HOME/.vim_runtime
if [[ -d $amix_vimrc ]]; then
# the update_plugins.py script makes the vim_runtime dir dirty, so we have to reset --hard
(cd $amix_vimrc && git reset --hard HEAD >/dev/null && git pull -q --rebase && echo "Upgraded amix's vimrc" || echo "Could not upgrade amix's vimrc" >&2)
(python $amix_vimrc/update_plugins.py >/dev/null || echo "upgraded amix's vimrc's plugins || "echo "Could not upgrade amix's vimrc's plugins" >&2)
else
echo "Could not upgrade amix's vimrc and plugins (missing .vim_runtime folder)" >&2
fi
antibody update
# update the zsh file
_update_dotfiles_update
}
epoch_target=$UPDATE_ZSH_DAYS
if [[ -z "$epoch_target" ]]; then
# Default to old behavior
epoch_target=13
fi
# Cancel upgrade if the current user doesn't have write permissions for the
# dotfiles directory.
[[ -w "$DOTFILES" ]] || return 0
# Cancel upgrade if git is unavailable on the system
whence git >/dev/null || return 0
# Clean up old lock files
find $DOTFILES/update.lock -mmin 60 -exec rm {} \; &>/dev/null
if mkdir "$DOTFILES/update.lock" 2>/dev/null; then
if [ -f ~/.dotfiles-update ]; then
. ~/.dotfiles-update
if [[ -z "$LAST_EPOCH" ]]; then
_update_dotfiles_update && return 0;
fi
epoch_diff=$(($(_current_epoch) - $LAST_EPOCH))
if [ $epoch_diff -gt $epoch_target ]; then
if [ "$DISABLE_UPDATE_PROMPT" = "true" ]; then
_upgrade_dotfiles
else
echo "[brethil dotfiles] Would you like to check for updates? [Y/n]: \c"
read line
if [[ "$line" == Y* ]] || [[ "$line" == y* ]] || [ -z "$line" ]; then
_upgrade_dotfiles
else
_update_dotfiles_update
fi
fi
fi
else
# create the dotfiles file
_update_dotfiles_update
fi
rmdir $DOTFILES/update.lock
fi

View File

@ -1,9 +1,3 @@
# ansi colors are pretty simple. In 256 color mode, for a given
# (r, g, b) tuple:
# \x1b[38;2;r;g;bm - foreground
# \x1b[48;2;r;g;bm - background
# ANSI COLOR ESCAPES # ANSI COLOR ESCAPES
# CLEAR # CLEAR
CLEAR='\e[0m' # CLEAR CLEAR='\e[0m' # CLEAR
@ -29,9 +23,6 @@ BCyan='\e[1;36m' # Cyan
BWhite='\e[1;37m' # White BWhite='\e[1;37m' # White
# Underline # Underline
if command -v tput &>/dev/null; then
UNDERLINE="$(tput smul)"
fi
UBlack='\e[4;30m' # Black UBlack='\e[4;30m' # Black
URed='\e[4;31m' # Red URed='\e[4;31m' # Red
UGreen='\e[4;32m' # Green UGreen='\e[4;32m' # Green
@ -94,34 +85,3 @@ LIGHTCYAN="\e[36m"; LIGHTRED="\033[31m"; LIGHTPURPLE="\033[35m";
YELLOW="\e[33m"; WHITE="\033[37m" YELLOW="\e[33m"; WHITE="\033[37m"
BACKGROUND_BLACK="\e[40"; BACKGROUND_RED="\033[41"; BACKGROUND_BLACK="\e[40"; BACKGROUND_RED="\033[41";
BACKGROUND_GREEN="\e[42"; BACKGROUND_YELLOW="\033[43m" BACKGROUND_GREEN="\e[42"; BACKGROUND_YELLOW="\033[43m"
## Color string with given color. Usage: `color $NAME "string"`, available colors below
function color
{
local color=$1
shift 1
echo -e "${color}$@${CLEAR}"
}
## These functions return a colored version of the input string. Usage: red "string"
function red
{
echo -e "$Red$@$CLEAR"
}
function green
{
echo -e "$Green$@$CLEAR"
}
function yellow
{
echo -e "$Yellow$@$CLEAR"
}
function blue
{
echo -e "$Blue$@$CLEAR"
}
function bold
{
echo -e "$BOLD$@$CLEAR"
}

View File

@ -1,18 +0,0 @@
FROM archlinux:latest
ENV TERM=xterm-256color
RUN --mount=type=cache,target=/var/cache/pacman \
pacman --noconfirm -Syu && pacman --noconfirm -Sy \
python \
openssh
# uncomment to hardcode ssh_host keys in the image
# RUN ssh-keygen -A
WORKDIR /root/.dotfiles
COPY . .
RUN cat dev/id_ed25519.pub >> /root/.ssh/authorized_keys
CMD ["bash", "dev/entrypoint.sh"]

View File

@ -1,20 +0,0 @@
FROM debian:unstable
ENV TERM=xterm-256color
RUN --mount=type=cache,target=/var/cache/apt \
apt-get update && apt-get install -y --no-install-recommends \
openssh-server \
python python3 \
&& rm -rf /etc/ssh/ssh_host_*
# ssh host keys are generated by entrypoint, remove rm /etc/ssh/ssh_host*
# to hardcode ssh host keys into the image
RUN mkdir /run/sshd
WORKDIR /root/.dotfiles
COPY . .
RUN cat dev/id_ed25519.pub >> /root/.ssh/authorized_keys
CMD ["bash", "dev/entrypoint.sh"]

View File

@ -1,68 +0,0 @@
SHELL=/bin/bash
ifndef VERBOSE
.SILENT:
endif
CLEAR="\033[0m"
BOLD="\033[1m"
GREEN="\033[32m"
RED="\033[31m"
BLUE="\033[34m"
WHITE="\033[37m"
.PHONY: clean list_targets build build-arch build-debian arch archlinux debian run ansible release
all: list_targets
list_targets:
echo "List of targets:"
@grep '^[^#[:space:]].*:' Makefile
debian: clean build-debian run
arch archlinux: clean build-arch run
build: build-arch
build-debian: Dockerfile.debian
docker build -t brethil/dotfiles:dev -f Dockerfile.debian ..
build-arch: Dockerfile.archlinux
docker build -t brethil/dotfiles:dev -f Dockerfile.archlinux ..
run: _run
echo -e ${GREEN} "***" ${CLEAR} Watching logs from the container. Hit Ctrl+C to stop watching.
docker logs -f dotfiles-dev
_run: clean build
# docker run -d --rm --name=dotfiles-dev -v ${PWD}/..:/root/.dotfiles:ro brethil/dotfiles:dev
docker run -d --rm --name=dotfiles-dev brethil/dotfiles:dev
echo -en ${GREEN} "***" ${CLEAR} Started container, listening on
echo -e ${BOLD}${WHITE} `docker inspect -f '{{range .NetworkSettings.Networks}}{{.IPAddress}}{{end}}' dotfiles-dev`:22 ${CLEAR}
echo -e ${BLUE} "***" ${CLEAR} Run \`make clean\` to stop and remove the container, \`make run\` to check the logs.
ansible: SHELL:=/bin/bash
ansible: ../playbook.yml _run
@ip_address=$$(docker inspect dotfiles-dev --format '{{.NetworkSettings.IPAddress}}'); \
if [[ -z "$$ip_address" ]]; then \
echo "ip address is not defined, is your container running?" >&2; \
exit 1; \
else \
sed -i "s/172.18.0.2/$$ip_address/" ansible-hosts; \
ANSIBLE_HOST_KEY_CHECKING=False ansible-playbook -i ansible-hosts ../playbook.yml; \
fi
release: build-arch ansible
docker commit -m "install and initialize dotfiles (ansible)" dotfiles-dev brethil/dotfiles:latest
docker tag brethil/dotfiles:latest brethil/dotfiles:`git rev-parse --short HEAD &2>/dev/null`
echo -e ${GREEN} "***" ${CLEAR} committed and tagged the \"dockerfiles-dev\" to brethil/dotfiles:latest and :`git rev-parse HEAD --short`
if ! git diff --quiet --exit-code; then \
docker tag brethil/dotfiles:latest brethil/dotfiles:dev && \
echo -e ${GREEN} "***" ${CLEAR} committed and tagged the \"dockerfiles-dev\" to brethil/dotfiles:dev; \
fi
clean:
echo -e ${GREEN} "***" ${CLEAR} Stopping and removing \"dockerfiles-dev\" container...
docker kill dotfiles-dev &>/dev/null &>/dev/null && echo -e ${GREEN} "***" ${CLEAR} Killed container: dotfiles-dev || echo -e ${BLUE} "***" ${CLEAR} no containers to stop
docker stop dotfiles-dev &>/dev/null && echo -e ${GREEN} "***" ${CLEAR} Removed container: dotfiles-dev || echo -e ${BLUE} "***" ${CLEAR} no containers to remove

View File

@ -1,57 +0,0 @@
# dev
This directory contains some useful dockerfiles/makefiles that can be used
to test the deployment ansible playbooks.
```bash
make arch # this builds a docker image based on archlinux and runs it
make debian # this builds a docker image based on debian and runs it
```
## Workflow
Start a builder in one shell:
```bash
while true; do make _run; done
```
Check for the docker IP of the started container:
```bash
docker inspect dotfiles-dev --format '{{.NetworkSettings.IPAddress}}'
```
Make sure that this matches the IP in [ansible-hosts](/dev/ansible-hosts)
Test the playbook:
```bash
ansible-playbook -v -i ansible-hosts ../playbook.yml
```
## Docker images
- Build: `make build-arch` or `make build-debian` to build the image.
- Run: `make run` to run the docker container. This bind-mounts `../` to
`/root/.dotfiles`, making it possible to test the repo in the container.
## Docker + Ansible
Run `dotfiles-dev` image using `make run`. This starts the container with
the local repository bind-mounted on `/root/.dotfiles`. To use a custom volume:
```bash
docker run -v <volume>:/root/dofiles`
```
Ansible can now be used to test the installation.
```bash
make ansible
```
## Releasing
Use `make release` to build an image from scratch, run it, install dotfiles
in the container using ansible, then commit the resulting container.

View File

@ -1,2 +0,0 @@
#!/bin/bash
ansible-galaxy collection install community.general # for git_config

View File

@ -1,2 +0,0 @@
[docker]
172.18.0.2 ansible_user=root ansible_python_interpreter=python3 alias=dotfiles_dev_container

View File

@ -1,8 +0,0 @@
[defaults]
forks = 10
strategy=free
pipelining = true
internal_poll_interval = 0.001
roles_path = ../ansible

View File

@ -1,5 +0,0 @@
#!/bin/bash
if [ ! -f /etc/ssh/ssh_host_ed25519_key.pub ]; then
ssh-keygen -A
fi
/usr/sbin/sshd -D -e

View File

@ -1 +0,0 @@
ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAILyIgoGSyuRjxvW+2SBWYJF2dMAVX+3d5h8TpKmIVpuk brethil@distruzione.org

Binary file not shown.

Before

Width:  |  Height:  |  Size: 27 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 45 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 249 KiB

View File

@ -1,10 +0,0 @@
#_tmux_sourced=1 exec tmux
if [[ -z $TMUX ]] && [[ -n $SSH_TTY ]]; then
session=tmux
if tmux has-session -t "$session" 2>/dev/null; then
exec tmux attach-session -t "$session"
else
exec tmux new-session -s "$session"
fi
fi

View File

@ -1,97 +0,0 @@
#!/usr/bin/env zsh
# brethil, brutally copied from https://github.com/robbyrussell/oh-my-zsh/blob/master/tools/check_for_upgrade.sh
# This also runs antibody update"
# First version: 14 July 2017
# Rebased on upstream: 08 December 2020
local DOTFILES_UPDATEFILE=${DOTFILES}/.dotfiles-update
# Migrate .dotfiles-update file to $DOTFILES
if [[ -f ~/.dotfiles-update && ! -f "${DOTFILES_UPDATEFILE}" ]]; then
mv ~/.dotfiles-update "${DOTFILES_UPDATEFILE}"
fi
# Cancel update if:
# - the automatic update is disabled.
# - git is unavailable on the system.
if [[ -n $DISABLE_DOTFILES_AUTOUPDATE ]] || ! command -v git &>/dev/null; then
return
fi
function current_epoch() {
zmodload zsh/datetime
echo $(( EPOCHSECONDS / 60 / 60 / 24 ))
}
function _update_dotfiles_update() {
echo "LAST_EPOCH=$(current_epoch)" >! "${DOTFILES_UPDATEFILE}"
}
function update_dotfiles() {
(cd $DOTFILES; git pull -q --rebase && echo "Succesfully upgraded dotfiles" || echo "Could not upgrade dotfiles.")
(cd $DOTFILES/antidote && git pull --rebase || echo "Could not upgrade antidote")
vim -c 'PlugUpdate|PlugClean|qa!'
# update the zsh file
_update_dotfiles_update
}
() {
if [[ -n $DOTFILES_FORCEUPDATE ]]; then
update_dotfiles;
return;
fi
local epoch_target mtime option LAST_EPOCH
# Remove lock directory if older than a day
zmodload zsh/datetime
zmodload -F zsh/stat b:zstat
if mtime=$(zstat +mtime "$DOTFILES/update.lock" 2>/dev/null); then
if (( (mtime + 3600 * 24) < EPOCHSECONDS )); then
command rm -f "$DOTFILES/update.lock"
fi
fi
# Check for lock directory
if ! command mkdir "$DOTFILES/update.lock" 2>/dev/null; then
return
fi
# Remove lock directory on exit. `return 1` is important for when trapping a SIGINT:
# The return status from the function is handled specially. If it is zero, the signal is
# assumed to have been handled, and execution continues normally. Otherwise, the shell
# will behave as interrupted except that the return status of the trap is retained.
trap "
unset -f current_epoch _update_dotfiles_update update_dotfiles &>/dev/null
command rmdir '$DOTFILES/update.lock' &>/dev/null
return 1
" EXIT INT QUIT
# Create or update .zsh-update file if missing or malformed
if ! source "${DOTFILES_UPDATEFILE}" 2>/dev/null || [[ -z "$LAST_EPOCH" ]]; then
_update_dotfiles_update
return
fi
# Number of days before trying to update again
epoch_target=${UPDATE_DOTFILES_DAYS:-5}
# Test if enough time has passed until the next update
if (( ( $(current_epoch) - $LAST_EPOCH ) < $epoch_target )); then
return
fi
# Ask for confirmation before updating unless disabled
if [[ "$DISABLE_UPDATE_PROMPT" = true ]]; then
update_dotfiles
else
echo -n "[brethil-dotfiles] Would you like to update? [Y/n] "
read -r -k 1 option
case "$option" in
[yY$'\n']) update_dotfiles ;;
[nN]) _update_dotfiles_update ;;
*) echo -n "[brethil dotfiles] Skipping. Update using \`dotfiles_selfupdate\`" && echo ;;
esac
fi
}
unset -f current_epoch update_dotfiles _update_dotfiles_update

View File

@ -1,83 +0,0 @@
# stolen from https://github.com/Phantas0s/.dotfiles/blob/master/zsh/completion.zsh
## General
# zstyle pattern for the completion
# :completion:<function>:<completer>:<command>:<argument>:<tag>
# Should be called before compinit
zmodload zsh/complist
# Use hjlk in menu selection (during completion)
# Doesn't work well with interactive mode
bindkey -M menuselect 'h' vi-backward-char
bindkey -M menuselect 'k' vi-up-line-or-history
bindkey -M menuselect 'j' vi-down-line-or-history
bindkey -M menuselect 'l' vi-forward-char
bindkey -M menuselect '^xg' clear-screen
bindkey -M menuselect '^xi' vi-insert # Insert
bindkey -M menuselect '^xh' accept-and-hold # Hold
bindkey -M menuselect '^xn' accept-and-infer-next-history # Next
bindkey -M menuselect '^xu' undo # Undo
#setopt GLOB_COMPLETE # Show autocompletion menu with globs
#setopt MENU_COMPLETE # Automatically highlight first element of completion menu
setopt AUTO_LIST # Automatically list choices on ambiguous completion.
## Zstyles
# Ztyle pattern
# :completion:<function>:<completer>:<command>:<argument>:<tag>
# Define completers
zstyle ':completion:*' completer _extensions _complete _approximate
# Use cache for commands using cache
zstyle ':completion:*' use-cache on
zstyle ':completion:*' cache-path "$HOME/.cache/zsh/.zcompcache"
# Complete the alias when _expand_alias is used as a function
zstyle ':completion:*' complete true
zle -C alias-expension complete-word _generic
bindkey '^A' alias-expension
zstyle ':completion:alias-expension:*' completer _expand_alias
# Allow you to select in a menu
zstyle ':completion:*' menu select
# Autocomplete options for cd instead of directory stack
zstyle ':completion:*' complete-options true
zstyle ':completion:*' file-sort modification
zstyle ':completion:*:*:*:*:corrections' format '%F{yellow}!- %d (errors: %e) -!%f'
zstyle ':completion:*:*:*:*:descriptions' format '%F{blue}-- %D %d --%f'
zstyle ':completion:*:*:*:*:messages' format ' %F{purple} -- %d --%f'
zstyle ':completion:*:*:*:*:warnings' format ' %F{red}-- no matches found --%f'
# zstyle ':completion:*:default' list-prompt '%S%M matches%s'
# Colors for files and directory
zstyle ':completion:*:*:*:*:default' list-colors ${(s.:.)LS_COLORS}
# Only display some tags for the command cd
zstyle ':completion:*:*:cd:*' tag-order local-directories directory-stack path-directories
# zstyle ':completion:*:complete:git:argument-1:' tag-order !aliases
# Required for completion to be in good groups (named after the tags)
zstyle ':completion:*' group-name ''
zstyle ':completion:*:*:-command-:*:*' group-order aliases builtins functions commands
# See ZSHCOMPWID "completion matching control"
zstyle ':completion:*' matcher-list '' 'm:{a-zA-Z}={A-Za-z}' 'r:|[._-]=* r:|=*' 'l:|=* r:|=*'
zstyle ':completion:*' keep-prefix true
zstyle -e ':completion:*:(ssh|scp|sftp|rsh|rsync):hosts' hosts 'reply=(${=${${(f)"$(cat {/etc/ssh_,~/.ssh/known_}hosts(|2)(N) /dev/null)"}%%[# ]*}//,/ })'
# kubectl
zstyle ':completion:*:*:kubectl:*' list-grouped false
# docker
zstyle ':completion:*:*:docker:*' option-stacking yes
zstyle ':completion:*:*:docker-*:*' option-stacking yes

View File

@ -1,25 +0,0 @@
# disable sort when completing options of any command
zstyle ':completion:complete:*:options' sort false
# use input as query string when completing zlua
zstyle ':fzf-tab:complete:_zlua:*' query-string input
# (experimental, may change in the future)
# some boilerplate code to define the variable `extract` which will be used later
# please remember to copy them
local extract="
# trim input(what you select)
local in=\${\${\"\$(<{f})\"%\$'\0'*}#*\$'\0'}
# get ctxt for current completion(some thing before or after the current word)
local -A ctxt=(\"\${(@ps:\2:)CTXT}\")
# real path
local realpath=\${ctxt[IPREFIX]}\${ctxt[hpre]}\$in
realpath=\${(Qe)~realpath}
"
# give a preview of commandline arguments when completing `kill`
zstyle ':completion:*:*:*:*:processes' command "ps -u $USER -o pid,user,comm,cmd -w -w"
zstyle ':fzf-tab:complete:kill:argument-rest' extra-opts --preview=$extract'ps --pid=$in[(w)1] -o cmd --no-headers -w -w' --preview-window=down:3:wrap
# give a preview of directory by exa when completing cd
zstyle ':fzf-tab:complete:cd:*' extra-opts --preview=$extract'exa -1 --color=always $realpath'

View File

@ -1,50 +0,0 @@
#!/usr/bin/env zsh
# Reads output from zprof.
# Usage:
# 1. add the following to the beginning of your zshrc
# if [[ -n $profiling ]]; then
# zmodload zsh/zprof
# zmodload zsh/datetime
# setopt PROMPT_SUBST
# PS4='+$EPOCHREALTIME %N:%i> '
#
# logfile=$(mktemp zsh_profile.XXXXXXXX)
# echo "Logging to $logfile"
# exec 3>&2 2>$logfile
#
# setopt XTRACE
# fi
# 2. add this to the end of your zshrc
# if [[ -n $profiling ]]; then
# unsetopt XTRACE
# exec 2>&3 3>&-
# zprof
# fi
# 3. zsh -i -c exit
# 4. sort_timings.zsh zsh_profile.* # or use the newly-created file
typeset -a lines
typeset -i prev_time=0
typeset prev_command
while read line; do
if [[ $line =~ '^.*\+([0-9]{10})\.([0-9]{6})[0-9]* (.+)' ]]; then
integer this_time=$match[1]$match[2]
if [[ $prev_time -gt 0 ]]; then
time_difference=$(( $this_time - $prev_time ))
lines+="$time_difference $prev_command"
fi
prev_time=$this_time
local this_command=$match[3]
if [[ ${#this_command} -le 80 ]]; then
prev_command=$this_command
else
prev_command="${this_command}..."
fi
fi
done < ${1:-/dev/stdin}
print -l ${(@On)lines} # | sort -h | vim -

View File

@ -1,4 +0,0 @@
#!/bin/bash
if test "$SSH_AUTH_SOCK" ; then
ln -sf $SSH_AUTH_SOCK ~/.ssh/ssh_auth_sock
fi

View File

@ -1,15 +0,0 @@
# Make sure SSH_AUTH_sock is symlinked
if test "$SSH_AUTH_SOCK" ; then
ln -sf $SSH_AUTH_SOCK ~/.ssh/ssh_auth_sock
fi
#_tmux_sourced=1 exec tmux
if [[ -z $TMUX ]] && [[ -n $SSH_TTY ]]; then
session=tmux
if tmux has-session -t "$session" 2>/dev/null; then
exec tmux attach-session -t "$session"
else
exec tmux new-session -s "$session"
fi
fi

View File

@ -1,18 +0,0 @@
# Make sure SSH_AUTH_sock is symlinked
if test "$SSH_AUTH_SOCK" ; then
ln -sf $SSH_AUTH_SOCK ~/.ssh/ssh_auth_sock
fi
#_tmux_sourced=1 exec tmux
if [[ -z $TMUX ]] && [[ -n $SSH_TTY ]]; then
set -x
session=tmux
if tmux has-session -t "$session" 2>/dev/null; then
exec tmux attach-session -t "$session"
else
tmux new-session -s "$session"
exec tmux attach-session -t "$session"
fi
fi

279
functions.sh Executable file
View File

@ -0,0 +1,279 @@
###########################
#### Function Definitions #
###########################
## Selfupdate
function dotfiles_selfupdate
{
(. $DOTFILES/check_for_update.sh && _upgrade_dotfiles)
}
## get cheat sheets for commands from cheat.sh. Usage: cheat commandname
function cheat
{
curl "https://cheat.sh/$1"
}
# get cheat sheets for commands matching $1
function cheatall
{
curl "https://cheat.sh/~$1"
}
# List all docker tags for an image
function dockertags
{
if [[ -z $(command -v jq) ]]; then
echo "jq not installed. Please install jq." 1>&2
return
fi
i=0
while [[ $? == 0 ]]; do
i=$(($i+1))
curl "https://registry.hub.docker.com/v2/repositories/library/$1/tags/?page=$i" 2>/dev/null | jq '."results"[]["name"]'
done
}
# watch with grc enabled
function watchgrc
{
watch -n 1 -c grc --colour=on "$@"
}
## Simple calculator. Usage: calc 1+1, calc 5/7, calc "sqrt(2)"
function calc
{
awk "BEGIN { print $* }"
}
## Make new directory and cd to that directory. Usage: mcd newfolder
function mcd
{
mkdir -p "$1"
cd $1
}
## Print full path of item in current directory
function ppath
{
echo "$PWD/$1"
}
## Color string with given color. Usage: color $colorname "string", available colors in colors.sh
function color
{
color=$1
set -x
shift 1
echo -e "$"$color"$@${CLEAR}\n"
set +x
}
## These functions return a colored version of the input string. Usage: red "string"
function red
{
echo -e "$Red$@$CLEAR"
}
function green
{
echo -e "$Green$@$CLEAR"
}
function blue
{
echo -e "$Blue$@$CLEAR"
}
## Flashes the screen until user presses a key
function flasher
{
while true; do printf "\e[?5h\007"; sleep 0.25; printf "\e[?5l"; read -s -n -t1 && break; done;
}
## Beep until user presses a key
function beeper
{
while true; do printf "\e[?5h\007"; sleep 0.25; printf "\e[?5l"; read -s -n -t1 && break; done;
}
## Simple http server for current directory (or path)
function httpserver
{
(
if [[ -d $1 ]]; then
cd "$1" && echo "Starting webserver in $(realpath $1)/" || echo "directory: $1 does not exist" >&2 || exit 1
else
echo "Starting webserver in $PWD/"
fi
open "http://localhost:8000" &>/dev/null &
if [[ "$(command -v python3)" ]]; then
python=python3
else
python=python
fi
$python -m http.server 8000
)
}
alias webserver='httpserver'
## Upload something using the transfer.sh service. Usage: transfer filename
function transfer
{
basefile=$(basename "$1" | sed -e 's/[^a-zA-Z0-9._-]/-/g')
out=$(curl --progress-bar --upload-file "$1" "https://transfer.sh/$basefile")
echo -e "Done, file at:\t$out"
if [[ $(uname) == "Darwin" ]]; then
echo "$out" | pbcopy
else
echo "$out"
fi
}
## If connecting through ssh and reverse forwarding port 2222 (ssh -R 2222:localhost:22 ), this function allows to copy the files back to the machine one is connecting from by typing 'mecp filename' (configure the username for "localhost" in ~/.ssh/config or add an username)
function mecp
{
rsync -r -P -e "ssh -p 2222" -R "$@" localhost:~/Desktop/
}
## generate a password using pwgen, generate_password 20 generates a 20 characters long password
function generate_password
{
pwgen -1sycn $1
}
## Generate a password from dev urandom using only printable characters
function genpwd
{
if [[ $1 ]]; then
strlen=$1
else
strlen=32
fi
# All characters excluding backlash
env LC_CTYPE=C tr -dc '[:graph]\' < /dev/urandom | fold -w $strlen | head -n 1
}
if [[ "$(uname)" == "Darwin" ]]; then
## Copy output of previous command to termbin.com (command line pastebin) and put in in clipboard
function termbin
{
nc termbin.com 9999 | pbcopy && echo -n "$(pbpaste) --> in clipboard"
}
else
## Copy output of previous command to termbin.com (command line pastebin)
function termbin
{
nc termbin.com 9999
}
fi
## List defined functions in $DOTFILES/functions.sh
function list_functions
{
grep --color=no -A 1 '^##' $DOTFILES/functions.sh | sed -E 's/function (.*)/\1/g'
}
###########################
## MAC SPECIFIC #
###########################
if [[ "$(uname)" == "Darwin" ]]; then
## Create a RAM disk. Default size 1GB. If supplied, first argument defines the RAM disk size in GB
function ramdisk
{
if [[ -e $1 ]]; then
sizeingb=$1
else
sizeingb=1
fi
# Numsectors is size in bytes / 512 (sector size in bytes)
name='RAM_disk'
sizeinbytes=$(($sizeingb*1000**3))
NUMSECTORS=$(($sizeinbytes/512))
mydev=$(hdiutil attach -nomount ram://$NUMSECTORS )
# strip whitespace (hdiutil outputs a lot of spaces/tabs along with the device name)
mydev=$(echo "$mydev"| xargs echo)
newfs_hfs "$mydev"
mkdir -p "/tmp/$name"
mount -t hfs "$mydev" "/tmp/$name"
echo "RAM Disk mounted: /tmp/$name"
echo "To eject (destroy) RAM disk, use:"
echo " $ diskutil eject $mydev"
}
## Open a pdf version of the man in Preview
function man2pdf
{
man -t "$1" | open -f -a Preview
}
## Open Man in separate (different-looking) window
function nman
{
if [ $# -eq 1 ] ; then
open "x-man-page://$1"
elif [ $# -eq 2 ] ; then
open "x-man-page://$1/$2"
fi
}
fi
### end of mac-specific functions
pipupdate(){
set -x
if [[ "$1" == "user" ]]; then
user_flags='--user'
shift
fi
if [[ -n "$@" ]]; then
pip="$1"
shift
flags="$*"
echo "pip command is: '$pip $flags'"
if ! command -v "$pip" ; then
echo "Given command ($1) does not exist." 1>&2
return
fi
else
pip='python'
flags='-m pip'
echo "Using default pip: $pip $flags"
fi
for package in $($pip $flags freeze $user_flags --local | grep -v '^\-e' | cut -d = -f 1) ; do
$pip $flags install "$user_flags" -U "$package"
done
set +x
}
# unzip file to directory with the same name of the zip file (without extension)
function unzipd {
zip_file="$1"
filename=$(basename -- "$zip_file")
extension="${filename##*.}"
name="${filename%.*}"
unzip -d "$name" "$zip_file"
}
# remove local branches which have been merged into master
function git_prune_branches(){
git branch --merged master | grep -v '^[ * ]*master$' | xargs git branch -d
}
fvim() {
if [[ -n "$@" ]]; then
vim `fzf -q $@`
else
vim `fzf`
fi
}
# dotfiles user functions
if [[ -f $HOME/.dotfiles_functions ]]; then
source "$HOME/.dotfiles_functions"
fi

View File

@ -1,4 +0,0 @@
# functions
Place custom functions definitions in this folder, with a `.zsh` extension.
These files will be sourced on startup

View File

@ -1,43 +0,0 @@
function switch-asciinema-user
{
local conf_dir="$HOME/.config/asciinema"
local current_id=$(basename $(readlink -f ${conf_dir}/install-id ))
function get_ids {
find ${conf_dir} -name 'install-id-*' -exec basename {} \;
}
if [[ $1 == "-l" || $1 == "--list" ]]; then
echo "$(color $BOLD Available ids): (current = $(color $UNDERLINE ${current_id}))"
for _id in $(get_ids); do
echo " $(green ➡️) ${_id}"
done
return
fi
local ids=$(get_ids)
local query
local new_id
if [[ -n "$@" ]]; then
query="-q $@"
fi
new_id=$(echo $ids| fzf --height=$(($(wc -l <<< $ids)+2)) ${query} )
if [[ -z $new_id ]]; then
yellow "Keeping curent id ($(color $UNDERLINE ${current_id}))"
return
fi
if [[ "$new_id" == "$current_id" ]]; then
yellow "id $new_id is already set."
return
fi
local id_file="${conf_dir}/${new_id}"
if [[ ! -f ${id_file} ]]; then
red "${id_file} does not exist"
return
fi
ln -sf "${id_file}" "${conf_dir}/install-id" && \
green "Set \"$new_id\"." || \
red "Could not set id \"$new_id\". (run with -l for a list of available profiles)"
}

View File

@ -1,125 +0,0 @@
# vim:ft=zsh ts=2 sw=2 sts=2
#
# Miscellaneous git helpers
# Create a gitignore for the given argument (e.g. python, cpp, etc)
function gi() { curl -sL https://www.toptal.com/developers/gitignore/api/$@; }
# Completion helper, from requires __completion_wrapper from `misc.zsh`
__git_completion_wrapper() {
# Wrapper for `__git_*` completion functions
# Can be used to force loading of specialized git completions
# When defining custom commands. See below for usage examples.
__completion_wrapper $1 _git
}
# remove local branches which have been merged into master/main
function git-prune-branches(){
local main=$(git_main_branch)
git branch --merged $main | grep -v '^[ * ]*'$main'$' | xargs git branch -d
}
# sort branches by latest commit
function git-sort-branch-by-usage(){
git for-each-ref --sort=committerdate refs/heads/ --format='%(refname:short)'
}
# switch to a recent branch
function git-switch-recent-branch(){
git switch $1
}
compdef "__git_completion_wrapper __git_recent_branches" git-switch-recent-branch
function git-commit-show() {
git log --graph --color=always --format="%C(auto)%h%d %s %C(black)%C(bold)%cr" $@ |
fzf --ansi --no-sort --reverse --tiebreak=index --preview \
'f() {
set -- $(echo -- "$@" | grep -o "[a-f0-9]\{7\}")
[ $# -eq 0 ] || git show --color=always $1
}
f {}' \
--bind "j:down,k:up,alt-j:preview-down,alt-k:preview-up,ctrl-f:preview-page-down,ctrl-b:preview-page-up,q:abort,ctrl-m:execute:
(grep -o '[a-f0-9]\{7\}' | head -1 |
xargs -I % sh -c 'git show --color=always % | less -R') << 'FZF-EOF'
{} FZF-EOF" \
--preview-window=right:60%
}
compdef "__git_completion_wrapper __git_recent_commits" git-commit-show
function git-fixup() {
git commit --fixup=$1
git -c sequence.editor=true rebase --interactive --autosquash $1^
}
compdef "__git_completion_wrapper __git_recent_commits" git-fixup
function git-diff-branch() {
git diff $@
}
compdef "__git_completion_wrapper __git_branch_names" git-diff-branch
function git-show-changes(){
git log --reverse HEAD^..
}
# oh-my-zsh has some aliases which we might want to override
# with functions
function _disable_alias() {
[[ -n $(alias "$1") ]] && unalias "$1"
}
_disable_alias gco
function gco() {
if [[ "$#" -ge 1 ]]; then
g checkout $@
elif [[ "$#" -eq 0 ]]; then
local selected
selected=$(git branch --format "%(refname)" | cut -d / -f 3- | fzf)
if [[ -n $selected ]]; then
git checkout "$selected"
else
echo "Nothing selected"
fi
fi
}
compdef "__git_completion_wrapper _git-checkout" gco
_disable_alias gcor
function gcor() {
if [[ "$#" -ge 1 ]]; then
git checkout $@
elif [[ "$#" -eq 0 ]]; then
git checkout --track $(gbr | fzf)
fi
}
_disable_alias gbd
function gbd() {
if [[ "$#" -ge 1 ]]; then
g branch -d $@
elif [[ "$#" -eq 0 ]]; then
g branch -d $(gb | fzf -m)
fi
}
compdef "__git_completion_wrapper __git_recent_branches" gbd
_disable_alias gbD
function gbD() {
if [[ "$#" -ge 1 ]]; then
git branch -D $@
elif [[ "$#" -eq 0 ]]; then
git branch -D $(git branch | fzf -m)
fi
}
compdef "__git_completion_wrapper __git_recent_branches" gbD

View File

@ -1,19 +0,0 @@
function fuzzyman() {
local preview_cmd
preview_cmd='command man {+1} 2>/dev/null | bat --style=plain --language=man --color=always'
apropos_args=$@
if [[ -z $apropos_args ]]; then
apropos_args="."
fi
man $(command man -k "${apropos_args}" \
| fzf \
--preview="${preview_cmd}" \
--preview-window=right,60% \
| awk '{print $1}'
)
}
compdef _man fuzzyman=man

View File

@ -1,349 +0,0 @@
###########################
#### Function Definitions #
###########################
## Selfupdate
function dotfiles_selfupdate
{
(DOTFILES_FORCEUPDATE=1 source $DOTFILES/extras/check_for_update.zsh || echo "[dotfiles_selfupdate] failed")
}
## get cheat sheets for commands from cheat.sh. Usage: cheat commandname
function cheat
{
curl "https://cheat.sh/$1"
}
# get cheat sheets for commands matching $1
function cheatall
{
curl "https://cheat.sh/~$1"
}
# List all docker tags for an image
function dockertags
{
if [[ -z $(command -v jq) ]]; then
echo "jq not installed. Please install jq." 1>&2
return
fi
i=0
while [[ $? == 0 ]]; do
i=$(($i+1))
curl "https://registry.hub.docker.com/v2/repositories/library/$1/tags/?page=$i" 2>/dev/null | jq '."results"[]["name"]'
done
}
# watch with grc enabled
function watchgrc
{
watch -n 1 -c grc --colour=on "$@"
}
## Simple calculator. Usage: calc 1+1, calc 5/7, calc "sqrt(2)"
function calc
{
awk "BEGIN { print $* }"
}
function warning {
echo -e "${Yellow}Warning:$CLEAR $@" >&2
}
function error {
echo -e "${Red}Error:$CLEAR $@" >&2
}
function info {
echo -e "${Green}Info:$CLEAR $@"
}
## Flashes the screen until user presses a key
function flasher
{
while true; do printf "\e[?5h\007"; sleep 0.25; printf "\e[?5l"; read -s -n -t1 && break; done;
}
## Beep until user presses a key
function beeper
{
while true; do printf "\e[?5h\007"; sleep 0.25; printf "\e[?5l"; read -s -n -t1 && break; done;
}
# set an alarm in seconds, minutes, hours
function alarm {
if [[ -z $1 ]]; then
echo "Usage: alarm 5[s]|5m|1h"
return 1
fi
local t
if [[ $1 = *"m" ]]; then
t=$((${1/m/}*60))
extra="($1)"
elif [[ $1 = *"h" ]]; then
t=$((${1/h/}*3600))
extra="($1)"
elif [[ $1 = *"s" ]]; then
t=${1/s/}
else
t=$1
fi
echo "Setting a timer for $1 $extra"
sleep $t && beeper
}
## Simple http server for current directory (or path)
function httpserver
{
(
if [[ -d $1 ]]; then
cd "$1" && echo "Starting webserver in $(realpath $1)/" || echo "directory: $1 does not exist" >&2 || exit 1
else
echo "Starting webserver in $PWD/"
fi
open "http://localhost:8000" &>/dev/null &
python -m http.server 8000
)
}
alias webserver='httpserver'
## Upload something using the 0x0.st service. Usage: upload [filename|url]
function upload
{
local url
if echo "$@" | grep -E -s -q "^http[s]://"; then
url=true
fi
if [[ $url == true ]]; then
out="$(curl -F"url=$@" https://0x0.st)"
else
out=$(curl --progress-bar -F"file=@$@" "https://0x0.st/")
fi
if [[ $? -ne 0 ]]; then
echo -e "Failed uploading $@:\n $out" >&2
return
fi
echo -e "Done, file at:\t$out"
if [[ $(uname) == "Darwin" ]]; then
clipboard="pbcopy"
elif command -v wl-copy &>/dev/null; then
clipboard="wl-copy"
elif command -v xclip &>/dev/null ; then
clipboard="xclip"
else
clipboard="cat"
fi
echo -en "$out" | $clipboard
}
## If connecting through ssh and reverse forwarding port 2222 (ssh -R 2222:localhost:22 ), this function allows to copy the files back to the machine one is connecting from by typing 'mecp filename' (configure the username for "localhost" in ~/.ssh/config or add an username)
function mecp
{
rsync -r -P -e "ssh -p 2222" -R "$@" localhost:~/Desktop/
}
## generate a password using pwgen, generate_password 20 generates a 20 characters long password
function generate_password
{
pwgen -1sycn $1
}
## Generate a password from dev urandom using only printable characters
function genpwd
{
if [[ $1 ]]; then
strlen=$1
else
strlen=32
fi
# All characters excluding backlash
env LC_CTYPE=C tr -dc '[:graph]\' < /dev/urandom | fold -w $strlen | head -n 1
}
## List defined functions in $DOTFILES/functions.sh
function list_functions
{
grep --color=no -A 1 '^##' $DOTFILES/functions/*.zsh| sed -E 's/function (.*)/\1/g'
}
# MacOS only
if [[ "$(uname)" == "Darwin" ]]; then
## Create a RAM disk. Default size 1GB. If supplied, first argument defines the RAM disk size in GB
function ramdisk
{
if [[ -e $1 ]]; then
sizeingb=$1
else
sizeingb=1
fi
# Numsectors is size in bytes / 512 (sector size in bytes)
name='RAM_disk'
sizeinbytes=$(($sizeingb*1000**3))
NUMSECTORS=$(($sizeinbytes/512))
mydev=$(hdiutil attach -nomount ram://$NUMSECTORS )
# strip whitespace (hdiutil outputs a lot of spaces/tabs along with the device name)
mydev=$(echo "$mydev"| xargs echo)
newfs_hfs "$mydev"
mkdir -p "/tmp/$name"
mount -t hfs "$mydev" "/tmp/$name"
echo "RAM Disk mounted: /tmp/$name"
echo "To eject (destroy) RAM disk, use:"
echo " $ diskutil eject $mydev"
}
fi
# unzip file to directory with the same name of the zip file (without extension)
function unzipd {
zip_file="$1"
filename=$(basename -- "$zip_file")
extension="${filename##*.}"
name="${filename%.*}"
unzip -d "$name" "$zip_file"
}
fvim() {
if [[ -n "$@" ]]; then
vim `fzf -q $@`
else
vim `fzf`
fi
}
# retry command until it succeeds (waiting one second or $RETRY_INTERVAL)
function retry() {
until $@; do sleep ${RETRY_INTERVAL:-1}; done
}
__completion_wrapper(){
# Wrapper for completion functions.
# These can be used to force loading of all completions
# for the given command in order to access specialized
# completion functions
local _completion_function=$1
local _completion_base=$2
if ! command -v $_completion_function &>/dev/null; then
$_completion_base
fi
$_completion_function
}
if command -v pacman &>/dev/null ; then
pacbins() {
pacman -Ql $1 | sed -n -e 's/.*\/bin\///p' | tail -n +2
}
_pacbins(){
# fix completion
__completion_wrapper _pacman_completions_installed_packages _pacman
}
compdef _pacbins pacbins
fi
if command -v rustc &>/dev/null
then
rexplain() {
rustc --explain $@ | bat --language=rust -
}
fi
if command -v fzf &>/dev/null ; then
falias() {
alias | fzf $@ | cut -d= -f 1
}
fi
make_backup() {
name="$1"
backup_name="backup_$1_$(date +%Y-%m-%d).tar.gz"
echo "Backing up to $backup_name"
tar -czf "$backup_name" "$1"
echo "done"
}
function find_by_mtime() {
find $@ -printf "%T+ %p\n" | sort
}
function mangrep() {
if [[ -z "$@" ]]; then
echo "Usage: $0 <pattern> <command>"
echo "Opens man page for <command> at the first match for <pattern>"
return
fi
pattern=$1
cmd=$2
if [[ -z "$cmd" ]]; then
man "$cmd"
return
fi
MANPAGER="less -p \"$pattern\"" man "$cmd"
}
# watches the given file and executes the given action whenever the file is changed. Usage: watch_file <file> <command>
function watch_file() {
if ! which inotifywait 2>&1 &>/dev/null ; then echo "$0 requires inotifywait"; return 1; fi
[[ -z "$1" ]] && echo "Usage: $0 <file> <action>" && return 1
local file=$1
shift
[[ -z "$@" ]] && echo "Usage: $0 <file> <action>" && return 1
local action="$@"
local _bg_job_pid
local TRAPINT(){
if [[ -n ${_bg_job_pid} ]]; then
kill -9 ${_bg_job_pid}
fi
yellow '\nQuitting.'
break;
}
{
set +m # disable job control messages
while true; do
zsh -c "$action" &
_bg_job_pid=$!
disown
echo -e "$Cyan ==> Running \"$action\" with pid=${_bg_job_pid}$CLEAR"
# block until the file has been written to
inotifywait -e close_write "$file" &>/dev/null
# the job might have failed, ignore errors
kill -9 ${_bg_job_pid} &>/dev/null || true
done
} always {
# remove ctrl-c trap
unset -f TRAPINT
set -m # restore job control messages
}
}
# use watch and force color with grc
function watchc() {
watch --differences --interval 1 --color grc --colour=on $@
}
# highlight functions with when calling which
function which(){
if ! (($+commands[bat])); then
builtin which $@
else
builtin which $@ | bat --language=zsh
fi
}

View File

@ -1,9 +0,0 @@
if ! command -v pacman &>/dev/null; then return; fi
function pacpreview() {
if ! command -v fzf &>/dev/null; then
echo "Requires fzf! Quitting"
return 1
fi
pacman -Slq | fzf --multi --preview 'grc --colour=on pacman -Si {1}' | xargs -ro sudo pacman -S
}

View File

@ -1,82 +0,0 @@
mkvenv(){
local source_venv force_create venv_name
while getopts "sf" opt; do
case $opt in
s|source) source_venv=y ;;
f|force) force_create=y ;;
*) echo "Unknown option: $opt"; return 1 ;;
esac
done
shift $(($OPTIND-1))
if [[ -n $1 ]]; then
venv_name=$1
shift
else
venv_name=.venv
fi
# any other arguments are passed on to the `venv` module as flags/arguments
if [[ -e ${venv_name} ]]; then
if [[ -n ${force_create} ]]; then
if [[ -n $VIRTUAL_ENV ]]; then # deactivate venv if enabled
deactivate && warning "Deactivated existing virtualenv" || red "Could not run deactivate";
fi
rm -rf ${venv_name} && warning "Deleted existing virtualenv."
else
error "$(color $BOLD .venv) already exists. Run with -f to recreate it." >&2
return 1
fi
fi
info "Creating virtualenv ${venv_name}... "
if ! python -m virtualenv $@ ${venv_name} ; then
error "Failed to create virtualenv. Is virtualenv installed? Try:\n $ pip install virtualenv"
return 1
fi
if [[ -z ${source_venv} ]]; then
echo -n " done. Enable? [Y/n] "
read source_venv
else
echo ""
fi
if [[ $source_venv != "n" ]]; then
source ${venv_name}/bin/activate && \
echo -e "$(color $BOLD Enabled!) 🐍 $(color $BOLD$PURPLE $(python --version | cut -d " " -f2 )) ($(color $BOLD$GREEN $(pip --version | cut -d " " -f -2)))"
fi
}
function enable_venv() {
local root
local activate
root=$(git rev-parse --show-toplevel 2>/dev/null)
if [[ -z $root ]]; then root=$PWD; fi
activate="$root/.venv/bin/activate"
if [[ -f "$activate" ]]; then
source "$activate"
fi
}
function disable_venv() {
if [[ -z ${VIRTUAL_ENV} ]]; then
return
fi
if [[ ! "$PWD" =~ $(dirname $VIRTUAL_ENV)}* ]]; then
echo "Deactivating venv..."
deactivate
fi
}
if [[ -n $DOTFILES_AUTOSWITCH_VIRTUALENV ]]; then
add-zsh-hook chpwd enable_venv
add-zsh-hook chpwd disable_venv
enable_venv
fi

View File

@ -1,22 +0,0 @@
#!/bin/zsh
function start_tracing {
zmodload zsh/zprof
zmodload zsh/datetime
setopt PROMPT_SUBST
PS4+='+$EPOCHREALTIME %N:%i> '
logfile=$(mktemp --tmpdir zsh_profile.XXXXXXXX)
echo "logging to $logfile"
exec 3>&2 2>$logfile
setopt XTRACE
}
function stop_tracing {
unsetopt XTRACE
exec 2>&3 3>&-
zprof | tee zprof_out.log | vim -c "set buftype=nofile" -
zmodload -u zsh/zprof
zmodload -u zsh/datetime
}

View File

@ -1,18 +0,0 @@
# open vim with a scratch window that can be discarded on exit.
vimscratch() {
local args
# if running in a pipe, use stdin (-) as arg.
# -t checks if the given FD is a terminal
if [ ! -t 0 ] ; then
stdin_arg="-"
fi
set +x
if [[ -n "$1" ]]; then
filetype=$1
shift
vim -c "set buftype=nofile" -c "set filetype=$filetype" $@ $stdin_arg
else
vim -c "set buftype=nofile" $filetype_arg $@ $stdin_arg
fi
}

View File

@ -1,278 +0,0 @@
# Copyright (c) 2009 rupa deadwyler. Licensed under the WTFPL license, Version 2
# maintains a jump-list of the directories you actually use
#
# INSTALL:
# * put something like this in your .bashrc/.zshrc:
# . /path/to/z.sh
# * cd around for a while to build up the db
# * PROFIT!!
# * optionally:
# set $_Z_CMD in .bashrc/.zshrc to change the command (default z).
# set $_Z_DATA in .bashrc/.zshrc to change the datafile (default ~/.z).
# set $_Z_MAX_SCORE lower to age entries out faster (default 9000).
# set $_Z_NO_RESOLVE_SYMLINKS to prevent symlink resolution.
# set $_Z_NO_PROMPT_COMMAND if you're handling PROMPT_COMMAND yourself.
# set $_Z_EXCLUDE_DIRS to an array of directories to exclude.
# set $_Z_OWNER to your username if you want use z while sudo with $HOME kept
#
# USE:
# * z foo # cd to most frecent dir matching foo
# * z foo bar # cd to most frecent dir matching foo and bar
# * z -r foo # cd to highest ranked dir matching foo
# * z -t foo # cd to most recently accessed dir matching foo
# * z -l foo # list matches instead of cd
# * z -e foo # echo the best match, don't cd
# * z -c foo # restrict matches to subdirs of $PWD
# * z -x # remove the current directory from the datafile
# * z -h # show a brief help message
[ -d "${_Z_DATA:-$HOME/.z}" ] && {
echo "ERROR: z.sh's datafile (${_Z_DATA:-$HOME/.z}) is a directory."
}
_z() {
local datafile="${_Z_DATA:-$HOME/.z}"
# if symlink, dereference
[ -h "$datafile" ] && datafile=$(readlink "$datafile")
# bail if we don't own ~/.z and $_Z_OWNER not set
[ -z "$_Z_OWNER" -a -f "$datafile" -a ! -O "$datafile" ] && return
_z_dirs () {
[ -f "$datafile" ] || return
local line
while read line; do
# only count directories
[ -d "${line%%\|*}" ] && echo "$line"
done < "$datafile"
return 0
}
# add entries
if [ "$1" = "--add" ]; then
shift
# $HOME and / aren't worth matching
[ "$*" = "$HOME" -o "$*" = '/' ] && return
# don't track excluded directory trees
if [ ${#_Z_EXCLUDE_DIRS[@]} -gt 0 ]; then
local exclude
for exclude in "${_Z_EXCLUDE_DIRS[@]}"; do
case "$*" in "$exclude"*) return;; esac
done
fi
# maintain the data file
local tempfile="$datafile.$RANDOM"
local score=${_Z_MAX_SCORE:-9000}
_z_dirs | awk -v path="$*" -v now="$(date +%s)" -v score=$score -F"|" '
BEGIN {
rank[path] = 1
time[path] = now
}
$2 >= 1 {
# drop ranks below 1
if( $1 == path ) {
rank[$1] = $2 + 1
time[$1] = now
} else {
rank[$1] = $2
time[$1] = $3
}
count += $2
}
END {
if( count > score ) {
# aging
for( x in rank ) print x "|" 0.99*rank[x] "|" time[x]
} else for( x in rank ) print x "|" rank[x] "|" time[x]
}
' 2>/dev/null >| "$tempfile"
# do our best to avoid clobbering the datafile in a race condition.
if [ $? -ne 0 -a -f "$datafile" ]; then
command rm -f "$tempfile"
else
[ "$_Z_OWNER" ] && command chown $_Z_OWNER:"$(id -ng $_Z_OWNER)" "$tempfile"
command mv -f "$tempfile" "$datafile" || command rm -f "$tempfile"
fi
# tab completion
elif [ "$1" = "--complete" -a -s "$datafile" ]; then
_z_dirs | awk -v q="$2" -F"|" '
BEGIN {
q = substr(q, 3)
if( q == tolower(q) ) imatch = 1
gsub(/ /, ".*", q)
}
{
if( imatch ) {
if( tolower($1) ~ q ) print $1
} else if( $1 ~ q ) print $1
}
' 2>/dev/null
else
# list/go
local echo fnd last list opt typ
while [ "$1" ]; do case "$1" in
--) while [ "$1" ]; do shift; fnd="$fnd${fnd:+ }$1";done;;
-*) opt=${1:1}; while [ "$opt" ]; do case ${opt:0:1} in
c) fnd="^$PWD $fnd";;
e) echo=1;;
h) echo "${_Z_CMD:-z} [-cehlrtx] args" >&2; return;;
l) list=1;;
r) typ="rank";;
t) typ="recent";;
x) sed -i -e "\:^${PWD}|.*:d" "$datafile";;
esac; opt=${opt:1}; done;;
*) fnd="$fnd${fnd:+ }$1";;
esac; last=$1; [ "$#" -gt 0 ] && shift; done
[ "$fnd" -a "$fnd" != "^$PWD " ] || list=1
# if we hit enter on a completion just go there
case "$last" in
# completions will always start with /
/*) [ -z "$list" -a -d "$last" ] && builtin cd "$last" && return;;
esac
# no file yet
[ -f "$datafile" ] || return
local cd
cd="$( < <( _z_dirs ) awk -v t="$(date +%s)" -v list="$list" -v typ="$typ" -v q="$fnd" -F"|" '
function frecent(rank, time) {
# relate frequency and time
dx = t - time
return int(10000 * rank * (3.75/((0.0001 * dx + 1) + 0.25)))
}
function output(matches, best_match, common) {
# list or return the desired directory
if( list ) {
if( common ) {
printf "%-10s %s\n", "common:", common > "/dev/stderr"
}
cmd = "sort -n >&2"
for( x in matches ) {
if( matches[x] ) {
printf "%-10s %s\n", matches[x], x | cmd
}
}
} else {
if( common && !typ ) best_match = common
print best_match
}
}
function common(matches) {
# find the common root of a list of matches, if it exists
for( x in matches ) {
if( matches[x] && (!short || length(x) < length(short)) ) {
short = x
}
}
if( short == "/" ) return
for( x in matches ) if( matches[x] && index(x, short) != 1 ) {
return
}
return short
}
BEGIN {
gsub(" ", ".*", q)
hi_rank = ihi_rank = -9999999999
}
{
if( typ == "rank" ) {
rank = $2
} else if( typ == "recent" ) {
rank = $3 - t
} else rank = frecent($2, $3)
if( $1 ~ q ) {
matches[$1] = rank
} else if( tolower($1) ~ tolower(q) ) imatches[$1] = rank
if( matches[$1] && matches[$1] > hi_rank ) {
best_match = $1
hi_rank = matches[$1]
} else if( imatches[$1] && imatches[$1] > ihi_rank ) {
ibest_match = $1
ihi_rank = imatches[$1]
}
}
END {
# prefer case sensitive
if( best_match ) {
output(matches, best_match, common(matches))
exit
} else if( ibest_match ) {
output(imatches, ibest_match, common(imatches))
exit
}
exit(1)
}
')"
if [ "$?" -eq 0 ]; then
if [ "$cd" ]; then
if [ "$echo" ]; then echo "$cd"; else builtin cd "$cd"; fi
fi
else
return $?
fi
fi
}
if command -v fzf &>/dev/null; then
# use fzf with z, from https://github.com/junegunn/fzf/wiki/Examples#integration-with-z
z() {
[ $# -gt 0 ] && _z "$*" && return
cd "$(_z -l 2>&1 | fzf --height 40% --nth 2.. --reverse --inline-info +s --tac --query "${*##-* }" | sed 's/^[0-9,.]* *//')"
}
zz() {
cd "$(_z -l 2>&1 | sed 's/^[0-9,.]* *//' | fzf -q "$_last_z_args")"
}
else
alias ${_Z_CMD:-z}='_z 2>&1'
fi
[ "$_Z_NO_RESOLVE_SYMLINKS" ] || _Z_RESOLVE_SYMLINKS="-P"
if type compctl >/dev/null 2>&1; then
# zsh
[ "$_Z_NO_PROMPT_COMMAND" ] || {
# populate directory list, avoid clobbering any other precmds.
if [ "$_Z_NO_RESOLVE_SYMLINKS" ]; then
_z_precmd() {
(_z --add "${PWD:a}" &)
: $RANDOM
}
else
_z_precmd() {
(_z --add "${PWD:A}" &)
: $RANDOM
}
fi
[[ -n "${precmd_functions[(r)_z_precmd]}" ]] || {
precmd_functions[$(($#precmd_functions+1))]=_z_precmd
}
}
_z_zsh_tab_completion() {
# tab completion
local compl
read -l compl
reply=(${(f)"$(_z --complete "$compl")"})
}
compctl -U -K _z_zsh_tab_completion _z
elif type complete >/dev/null 2>&1; then
# bash
# tab completion
complete -o filenames -C '_z --complete "$COMP_LINE"' ${_Z_CMD:-z}
[ "$_Z_NO_PROMPT_COMMAND" ] || {
# populate directory list. avoid clobbering other PROMPT_COMMANDs.
grep "_z --add" <<< "$PROMPT_COMMAND" >/dev/null || {
PROMPT_COMMAND="$PROMPT_COMMAND"$'\n''(_z --add "$(command pwd '$_Z_RESOLVE_SYMLINKS' 2>/dev/null)" 2>/dev/null &);'
}
}
fi

View File

@ -1,6 +1,6 @@
# vi:syntax=gitconfig # vi:syntax=gitconfig
#[core] # DEPRECATED: excludesfile should be in ~/.config/git/ignore [core]
#excludesfile = ~/.gitignore excludesfile = ~/.gitignore
#[init] #[init]
# templatedir = ~/.git_template # templatedir = ~/.git_template
@ -11,17 +11,16 @@ rebase = true
[merge] [merge]
ff = only ff = only
tool = vimdiff tool = vimdiff2
[mergetool] [mergetool]
keepBackup = false keepBackup = false
[diff] [diff]
tool = vimdiff tool = vimdiff2
[difftool] [difftool]
prompt=true prompt=true
[rebase] [rebase]
autostash = true autostash = true
autosquash = true autosquash = true
@ -31,9 +30,7 @@ squash = true
abbrevcommit = true abbrevcommit = true
[format] [format]
#pretty = format:%C(yellow)commit %h%Cred%d %Creset%nAuthor: %Cblue%>(12)%an%n%CgreenDate: %ar%Creset%n%n%B
[alias] [alias]
showtool = "!showci () { rev=${1:-HEAD}; git difftool $rev~1 $rev; }; showci $1" showtool = "!showci () { rev=${1:-HEAD}; git difftool $rev~1 $rev; }; showci $1"
mylog = "log --pretty='format:👉 %C(yellow)commit: %h%C(auto)%d %Creset%nAuthor: %C(auto,cyan)%>(12)%an (%aE)%n%C(reset)Date: %C(auto,green)%ar%Creset%nContent: %s'"
flog = "!flog() { git log --oneline $@ | fzf --multi --preview 'git -p show --color=always {+1}' --preview-window=right,60% | awk '{print $1}'; }; flog"
taglist = "tag --list --sort=-creatordate --format=\"%(authordate:relative)%09│ %(refname:short)\""

View File

@ -1,7 +0,0 @@
.venv
tags
node_modules
target
build
dist
.vagrant

189
install.sh Executable file
View File

@ -0,0 +1,189 @@
#!/bin/bash
## brethil's dotfiles installation script
## 20 June 2016
# Get the location for the dotfiles
DOTFILES=$PWD
PACKAGES="vim zsh antibody git grc ccze bmon mtr tmux byobu htop"
function setup_git {
# set up some git stuff
git config --global include.path $DOTFILES/gitconfig
}
function install_vimrc {
# TODO: check if vim-plug is installed
if [ -f "$HOME/.vimrc" ]; then
mv "$HOME/.vimrc"{,.bak} && echo "Backed up old vimrc"
fi
ln -s "$DOTFILES/.vimrc" "$HOME/.vimrc"
}
function setup_ackrc {
ln -s "$DOTFILES/ackrc" "$HOME/.ackrc"
}
function setup_ipython {
python -m pip install pip ipython || python -m pip install --user pip ipython
ipython -c "1+1" # run ipython once so that we are sure that the profile directories exist
ln -s "$DOTFILES/ipython/profile_default/ipython_config.py" "$HOME/.ipython/profile_default/"
ln -s "$DOTFILES/ipython/profile_default/startup" "$HOME/.ipython/profile_default/startup"
}
# Add an ssh config file with:
# - Connection multiplexer for faster multiple connections
# - Keep connections alive (avoid timeout disconnections)
function create_ssh_config {
echo "# Configuring ssh..."
ssh_config="$HOME/.ssh/config"
if [ ! -f $HOME/.ssh/id_rsa ]; then
echo "Creating ssh key (4096bit)..."
echo "Enter ssh-key comment (leave empty for default: user@host)"
read comment
if [[ $comment ]]; then
ssh-keygen -t ed25519 -C "$comment"
else
ssh-keygen -t ed25519
fi
# fix permissions
chmod 0700 "$HOME/.ssh"
fi
if [[ -f $ssh_config ]]; then
until [[ $modifyssh == "y" || $modifyssh == "n" ]]; do
echo "Do you want to modify the existing ssh config? (New values will be appended) (y/n)"
read modifyssh
done
fi
exec 3>&1 # save stdout file descriptor
# add the ssh rc that symlinks the used SSH_AUTH_SOCK. This will be executed on every ssh login.
# The idea is that if the user is logging in using ssh -A, the symlink will point to the correct
# location of the ssh auth socket and the remote ssh agent will be used.
# SSH_AUTH_SOCK is declared in brethil_dotfile.sh
exec 1>>~/.ssh/rc
echo '#!/bin/bash'
echo 'if test "$SSH_AUTH_SOCK" ; then'
echo ' ln -sf $SSH_AUTH_SOCK ~/.ssh/ssh_auth_sock'
echo 'fi '
chmod 755 ~/.ssh/rc
exec 1>>$ssh_config # redirect everything below to the $ssh_config file
if [[ "$modifyssh" == "n" ]]; then
echo "Did not modify $ssh_config."
exec 1>&3 # restore stdout
return
fi
echo "# brethil's dotfiles setup start"
echo 'TCPKeepAlive=yes'
echo 'ServerAliveCountMax=6'
echo
echo "## Uncomment to enable compression for all ssh sessions"
echo '#Compression=yes'
echo
echo '## Uncomment the following to enable ssh ControlMaster and ssh session persistence'
echo '#ControlMaster autoask # ask for confirmation before using a shared connection'
echo '#ControlMaster auto # do not ask for confirmation'
echo '#ControlPath ~/.ssh/%r@%h:%p'
echo '#ControlPersist yes'
echo
echo 'Host *'
echo ' ServerAliveInterval 300'
echo
echo '## Enable the following if you want to use the rmate textmate remote'
echo "#Host *"
echo "# RemoteForward 52698 localhost:52698"
echo
echo '## Enable the following if you want to use a reverse ssh tunnel to use mecp command on remote hosts'
echo "#Host *"
echo "# Remoteforward 2222 localhost:22"
echo
echo '# end of brethil dotfiles setup #'
exec 1>&3 # restore stdout
echo ".ssh/ssh_config configured. Edit it to enable custom options:"
echo "- Compression"
echo "- Remote forwarding remote:2222->localhost:22 (revere tunnel to scp back to the original host using mecp)"
echo "# End of ssh config."
}
function fix_annoyances {
## Fix scrolling in byobu
if [[ $(uname) == "Darwin" ]]; then
sed -i '' 's/set -g terminal-overrides/#set -g terminal-overrides/' /usr/share/byobu/profiles/tmux
else
sed -i 's/set -g terminal-overrides/#set -g terminal-overrides/' /usr/share/byobu/profiles/tmux
fi
# remove ls from the grc.zsh config: # TODO: fix this on MacOS
sed 's|ls \\|#ls \\|' /etc/grc.zsh
# TODO: add iptables, docker to grc.zsh
}
# First setup
function brethil_dotfiles_setup {
antibody &>/dev/null || (echo "Please install antibody then continue." 1>&2 && echo "Other useful packages: $PACKAGES" && exit)
bin="$HOME/bin"
projects="$HOME/projects"
git="$HOME/git"
mkdir -p "$bin" "$projects" "$git" && echo "Created dirs $bin, $projects, $git"
# prepare .zshrc
cp "$HOME/.zshrc"{,.pre-brethil-dotfiles}
exec 3>&1 # save stdout
exec 1>>"$HOME/.zshrc"
echo -e "\n\n# brethil's dotfiles:"
echo "export DOTFILES=$DOTFILES"
echo "source \$DOTFILES/brethil_dotfile.sh"
echo -e "# End of brethil's dotfiles\n\n"
exec 1>&3 # restore stdout
antibody bundle "$DOTFILES/antibody_plugins.txt"
antibody update
fix_annoyances
setup_vim
# Create ssh config
create_ssh_config
# git config
setup_git
# ipython profile
setup_ipython
# pdbpp rc
setup_pdbprc
# ackrc
setup_ackrc
ZSH="$(antibody path robbyrussell/oh-my-zsh)"
ln -s "$DOTFILES/brethil.zsh-theme" "${ZSH}/themes/" # TODO: improve this
ln -s "$DOTFILES/brethil-minimal.zsh-theme" "${ZSH}/themes/"
}
function main(){
set -e
set -o pipefail
# Setup
# brethil_dotfiles_setup
source "$DOTFILES/colors.sh"
echo -e "$BOLD$GREEN Install complete!"
echo ""
echo "$WHITE Set \$DOTFILES to $DOTFILES"
echo -e "$RED Functions definitions:$WHITE \$DOTFILES/functions.sh\n\tyou can add your own functions in ~/.dotfiles_functions"
echo -e "$RED Aliases definitions:$WHITE \$DOTFILES/aliases.sh\n\tyou can add your own aliases in ~/.dotfiles_aliases)"
echo -e "$RED Colors definitions:$WHITE \$DOTFILES/colors.sh"
echo -e "$CLEAR"
echo "More zsh plugins can be added using antibody, adding them at \$DOTFILES/antibody_plugins.txt"
echo "Type '. ~/.zshrc' or 'exec zsh -l' to source the new configuration."
}
main

View File

@ -1,5 +1,3 @@
config = get_config() c.TerminalInteractiveShell.editing_mode = "vi"
c.TerminalInteractiveShell.mouse_support = True # prevents from selecting text
config.TerminalInteractiveShell.editing_mode = "vi" c.TerminalInteractiveShell.true_color = True
config.TerminalInteractiveShell.mouse_support = True # prevents from selecting text
config.TerminalInteractiveShell.true_color = True

View File

@ -1,3 +0,0 @@
import os
os.environ["PAGER"] = "bat --style=plain"

View File

@ -1,25 +1,53 @@
import os
import pdb import pdb
from pygments.styles import get_style_by_name if False:
if os.getenv("THEME_PREFER_LIGHT"):
pygments_style = "gruvbox-light"
else:
pygments_style = "gruvbox-dark"
class Config(pdb.DefaultConfig):
# prompt = "(Pdb++) "
use_pygments = True
pygments_formatter_class = "pygments.formatters.TerminalTrueColorFormatter"
pygments_formatter_kwargs = {"style": get_style_by_name(pygments_style)}
editor = "vim"
if __name__ == "__main__":
from pygments.styles import get_all_styles from pygments.styles import get_all_styles
all_styles = get_all_styles() all_styles = get_all_styles()
print(list(all_styles))
all_styles = [
"default",
"emacs",
"friendly",
"colorful",
"autumn",
"murphy",
"manni",
"monokai",
"perldoc",
"pastie",
"borland",
"trac",
"native",
"fruity",
"bw",
"vim",
"vs",
"tango",
"rrt",
"xcode",
"igor",
"paraiso-light",
"paraiso-dark",
"lovelace",
"algol",
"algol_nu",
"arduino",
"rainbow_dash",
"abap",
"solarized-dark",
"solarized-light",
"sas",
"stata",
"stata-light",
"stata-dark",
"inkpot",
]
class Config(pdb.DefaultConfig):
sticky_by_default = True
pygments_formatter_class = "pygments.formatters.TerminalTrueColorFormatter"
pygments_formatter_kwargs = {"style": "solarized-dark"}
use_pygments = True
editor = "vim"

View File

@ -1,9 +0,0 @@
---
- hosts: all
vars:
archlinux: ansible_facts['os_family'] == "Archlinux"
roles:
- dotfiles
- { role: aur_packages, when: archlinux, tags: ["aur", "aur-packages"] }

View File

@ -1,95 +0,0 @@
# vim:ft=zsh ts=2 sw=2 sts=2
# brethil oh-my-zsh theme
# See "EXPANSION OF PROMPT SEQUENCES" in `man zshmisc`
# Note: Most of the expansions/color sequences can be tested using `print -P`
# prints hostname on an orange background if on an ssh connection, adds username if root
local user='%(!.%K{160}%F{255}%B%n%b%k%f.)' # prints 'root' on a red background if user is root
local host='%K{202}%B%F{255}%m%f%k%b' # bold host name on an orange background
local open_bracket='%(!.[.)'
local close_bracket='%(!.].)'
local at='%(!.@.)'
local user_prompt
if [[ -n $SSH_CONNECTION ]]; then
user_prompt="[${user}${at}${host}]"
else
user_prompt="${open_bracket}${user}${close_bracket}"
fi
local job_prompt="%(1j.%B%K{202}%F{220} %j %k%b.)"
local shlvl_prompt
# Shows SHLVL on a magenta background if SHLVL > 1 (2 if in a tmux session)
if [[ -z "$TMUX" ]]; then
shlvl_prompt="%(2L.%K{161}%F{255}%B %L %f%b%k.)"
else
shlvl_prompt="%(3L.%K{161}%F{255}%B $((SHLVL-1)) %f%b%k.)"
fi
# Shows last 3 items in path if there are more than 4
local path_prompt='[%F{green}%(4~:…/%3~:%~)%f]'
# PREFIX/SUFFIX are added before/after `git_prompt_info`
ZSH_THEME_GIT_PROMPT_PREFIX=" %f%{$fg[yellow]%} "
ZSH_THEME_GIT_PROMPT_SUFFIX="%{$reset_color%} |"
ZSH_THEME_GIT_PROMPT_DIRTY=" %{$fg[white]%}%{$fg[red]%}x%{$reset_color%}"
ZSH_THEME_GIT_PROMPT_CLEAN=" %{$fg[white]%}%{$fg[green]%}√%{$reset_color%}"
# The following are part of `git_prompt_status`
# Rules:
# ? : untracked
# * : modified
# + : added
# $ : stashed
ZSH_THEME_GIT_PROMPT_STASHED="%B%F{32}$%b%f" # blue
# ZSH_THEME_GIT_PROMPT_MODIFIED="%{$fg[red]%}✗ " # this is equivalent to DIRTY, if DISABLE_UNTRACKED_FILES_DIRTY is set
ZSH_THEME_GIT_PROMPT_ADDED="%B%F{34}+%b%f" # green
ZSH_THEME_GIT_PROMPT_UNTRACKED="%B%F{red}?%b%f" # red
# The following are part of `git_remote_status`
# ZSH_THEME_GIT_PROMPT_EQUAL_REMOTE="%{$fg[green]%}="
ZSH_THEME_GIT_PROMPT_AHEAD_REMOTE=">"
ZSH_THEME_GIT_PROMPT_BEHIND_REMOTE="<"
ZSH_THEME_GIT_PROMPT_DIVERGED_REMOTE="<>"
local BOLD_PURPLE='%B%F{5}'
local CLEAR='%f%b'
local venv
function virtualenv_info {
[ -z "$VIRTUAL_ENV" ] && return
venv="$(basename "$VIRTUAL_ENV")"
if [[ "$venv" == ".venv" ]]; then
venv="$(basename $(dirname "$VIRTUAL_ENV") )"
fi
# bold (%B) purple (%F{5})
echo -n " %B%F{5}<$venv>%b%f "
}
local git_prompt='$(git_prompt_info)$(git_prompt_status)$(git_remote_status)'
local return_code_RPS1='%(?..%B%F{88}-$?-%f%b)'
local success="%B%F{28} →%f%b"
local failure="%B%{$fg[red]%} x%b%{$reset_color%}"
local prompt_with_previous_return_status="%(?:$success:$failure) "
function prompt_too_long(){
# prints a newline if less than $COLUMNS/2 characters remain to the right margin, see end of `man zshmisc`
echo "%-$((COLUMNS/2))(l..\n)"
}
## oh-my-zsh vi-mode plugins indicators:
export MODE_INDICATOR="[%B%K{red}nav%k%b]" # red background
export INSERT_MODE_INDICATOR="[%B%K{28}ins%k%b]" # green background
# put it all together
PROMPT='$(virtualenv_info)'"${user_prompt}${path_prompt}${git_prompt}${job_prompt}${shlvl_prompt}$(prompt_too_long)${prompt_with_previous_return_status}"
# Right prompt is just return code and time
RPS1="${return_code_RPS1}"'$(vi_mode_prompt_info)[%*]'

105
tmux.conf
View File

@ -1,105 +0,0 @@
set-option -ga mouse
# https://github.com/seebi/tmux-colors-solarized/blob/master/tmuxcolors-256.conf
set-option -g status-style bg=colour235,fg=colour136,default # bg=base02, fg=yellow
# default window title colors
set-window-option -g window-status-style fg=colour244,bg=default,dim # fg=base0
# active window title colors
set-window-option -g window-status-current-style fg=colour166,bg=default,bright # fg=orange
# pane border
set-option -g pane-border-style fg=colour235 #fg=base02
set-option -g pane-active-border-style fg=colour240 #fg=base01
# message text
set-option -g message-style bg=colour235,fg=colour166 # bg=base02, fg=orange
# pane number display
set-option -g display-panes-active-colour colour33 #blue
set-option -g display-panes-colour colour166 #orange
# clock
set-window-option -g clock-mode-colour green #green
set -g history-limit 10000
set -g status-interval 1
set -g status-justify centre # center align window list
set -g status-left-length 20
set -g status-right-length 140
set -g status-left '#[fg=green]#H #[fg=black]• #[fg=green,bright]#(uname -r | cut -c 1-6)#[default]'
set -g status-right '#[fg=green,bg=default,bright]#(tmux-mem-cpu-load) #[fg=red,dim,bg=default]#(uptime | cut -f 4-5 -d " " | cut -f 1 -d ",") #[fg=white,bg=default]%a%l:%M:%S %p#[default] #[fg=blue]%Y-%m-%d'
# C-b is not acceptable -- Vim uses it
set-option -g prefix C-a
bind-key C-a last-window
# # Start numbering at 1
# set -g base-index 1
# Allows for faster key repetition
set -s escape-time 0
set-option -sg escape-time 0
# Rather than constraining window size to the maximum size of any client
# connected to the *session*, constrain window size to the maximum size of any
# client connected to *that window*. Much more reasonable.
setw -g aggressive-resize on
# Allows us to use C-a a <command> to send commands to a TMUX session inside
# another TMUX session
bind-key a send-prefix
# Activity monitoring
# setw -g monitor-activity on
set -g visual-activity on
# hjkl pane traversal
bind h select-pane -L
bind j select-pane -D
bind k select-pane -U
bind l select-pane -R
bind-key C command-prompt -p "Name of new window: " "new-window -n '%%'"
# reload config
bind r source-file ~/.tmux.conf \; display-message "Config reloaded"
# auto window rename
set-window-option -g automatic-rename
# https://github.com/edkolev/dots/blob/master/tmux.conf
# Updates for tmux 1.9's current pane splitting paths.
# Colors
# How to use true colors in vim under tmux? #1246 for 2.6 and higher
# https://github.com/tmux/tmux/issues/1246:
# set -g default-terminal "tmux-256color"
# set -ga terminal-overrides ",*256col*:Tc"
# 2.5 and lower:
# set -g default-terminal "screen-256color"
# True color settings, see https://jdhao.github.io/2018/10/19/tmux_nvim_true_color/ for the details.
set -g default-terminal "xterm-256color"
# If terminal supports true color, use the following options.
set -ga terminal-overrides ",xterm-256color*:Tc"
setw -g mode-keys vi
# use vim-like keys for splits and windows
bind-key v split-window -h -c "#{pane_current_path}"
bind-key s split-window -v -c "#{pane_current_path}"
bind-key h select-pane -L
bind-key j select-pane -D
bind-key k select-pane -U
bind-key l select-pane -R
bind-key t swap-window -t +1
bind-key T swap-window -t -1
bind-key S choose-window 'join-pane -v -s "%%"'
bind-key V choose-window 'join-pane -h -s "%%"'
bind-key W choose-window 'swap-window -t "%%"'
bind A command-prompt "rename-window \"%%\""
bind C customize-mode

View File

@ -252,5 +252,3 @@ emacs -batch -l dunnet
# BINARY CLOCK! # BINARY CLOCK!
watch -n 1 'echo "obase=2;`date +%s`" | bc' watch -n 1 'echo "obase=2;`date +%s`" | bc'
# dbus introspection
busctl -j --user introspect org.freedesktop.Notifications "/fr/emersion/Mako"

View File

@ -10,8 +10,8 @@ function! WinZoomToggle() abort
wincmd | wincmd |
let w:WinZoomIsZoomed = 1 let w:WinZoomIsZoomed = 1
elseif w:WinZoomIsZoomed == 1 elseif w:WinZoomIsZoomed == 1
execute 'resize ' . w:WinZoomOldHeight execute "resize " . w:WinZoomOldHeight
execute 'vertical resize ' . w:WinZoomOldWidth execute "vertical resize " . w:WinZoomOldWidth
let w:WinZoomIsZoomed = 0 let w:WinZoomIsZoomed = 0
endif endif
endfunction endfunction
@ -42,8 +42,8 @@ endfunction
" Don't close window, when deleting a buffer " Don't close window, when deleting a buffer
command! Bclose call <SID>BufcloseCloseIt() command! Bclose call <SID>BufcloseCloseIt()
function! <SID>BufcloseCloseIt() function! <SID>BufcloseCloseIt()
let l:currentBufNum = bufnr('%') let l:currentBufNum = bufnr("%")
let l:alternateBufNum = bufnr('#') let l:alternateBufNum = bufnr("#")
if buflisted(l:alternateBufNum) if buflisted(l:alternateBufNum)
buffer # buffer #
@ -51,35 +51,30 @@ function! <SID>BufcloseCloseIt()
bnext bnext
endif endif
if bufnr('%') == l:currentBufNum if bufnr("%") == l:currentBufNum
new new
endif endif
if buflisted(l:currentBufNum) if buflisted(l:currentBufNum)
execute('bdelete! '.l:currentBufNum) execute("bdelete! ".l:currentBufNum)
endif endif
endfunction endfunction
function! CmdLine(str) function! CmdLine(str)
call feedkeys(':' . a:str) call feedkeys(":" . a:str)
endfunction
" Call Git show on the selected text (must be a git ref)
function! GitShowVisual() range
execute 'Git show ' . @*
endfunction endfunction
function! VisualSelection(direction, extra_filter) range function! VisualSelection(direction, extra_filter) range
let l:saved_reg = @" let l:saved_reg = @"
execute 'normal! vgvy' execute "normal! vgvy"
let l:pattern = escape(@', "\\/.*'$^~[]") let l:pattern = escape(@", "\\/.*'$^~[]")
let l:pattern = substitute(l:pattern, '\n$', '', '') let l:pattern = substitute(l:pattern, "\n$", "", "")
if a:direction ==# 'ack' if a:direction == 'gv'
call CmdLine("Ack '" . l:pattern . "' " ) call CmdLine("Ack '" . l:pattern . "' " )
elseif a:direction ==# 'replace' elseif a:direction == 'replace'
call CmdLine('%s' . '/'. l:pattern . '/') call CmdLine("%s" . '/'. l:pattern . '/')
endif endif
let @/ = l:pattern let @/ = l:pattern
@ -88,63 +83,5 @@ endfunction
function! GitStatus() function! GitStatus()
let [a,m,r] = GitGutterGetHunkSummary() let [a,m,r] = GitGutterGetHunkSummary()
echo printf('+%d ~%d -%d', a, m, r) return printf('+%d ~%d -%d', a, m, r)
endfunction endfunction
command! GitStatus call GitStatus()
" Redirect command into scratch buffer. Stolen from romainl
function! Redir(cmd, rng, start, end)
for win in range(1, winnr('$'))
if getwinvar(win, 'scratch')
execute win . 'windo close'
endif
endfor
if a:cmd =~? '^!'
let cmd = a:cmd =~?' %'
\ ? matchstr(substitute(a:cmd, ' %', ' ' . expand('%:p'), ''), '^!\zs.*')
\ : matchstr(a:cmd, '^!\zs.*')
if a:rng == 0
let output = systemlist(cmd)
else
let joined_lines = join(getline(a:start, a:end), '\n')
let cleaned_lines = substitute(shellescape(joined_lines), "'\\\\''", "\\\\'", 'g')
let output = systemlist(cmd . ' <<< $' . cleaned_lines)
endif
else
redir => output
execute a:cmd
redir END
let output = split(output, "\n")
endif
vnew
let w:scratch = 1
setlocal buftype=nofile bufhidden=wipe nobuflisted noswapfile
call setline(1, output)
endfunction
command! -nargs=1 -complete=command -bar -range Redir silent call Redir(<q-args>, <range>, <line1>, <line2>)
" Gets the man page for the given command
function! Man(cmd)
vnew
let w:scratch=1
setlocal buftype=nofile bufhidden=wipe nobuflisted noswapfile filetype=man nonumber norelativenumber
let output = system('env COLUMNS=80 man ' . a:cmd)
call setline(1, split(output, '\n'))
endfunction
command! -nargs=1 -complete=shellcmd Vert Man silent call Man(<q-args>)
" Execute the given command and print it in a scratch buffer
function! Cmd(cmd)
let output = system(a:cmd)
vnew
let w:scratch=1
" setlocal buftype=nofile bufhidden=wipe nobuflisted noswapfile
setlocal buftype=popup bufhidden=wipe nobuflisted noswapfile
setlocal nonumber norelativenumber
call setline(1, split(output, '\n'))
endfunction
command! -nargs=1 -complete=shellcmd Cmd silent call Cmd(<q-args>)

View File

@ -1,232 +1,106 @@
"""" PLUGINS CONFIGURATION """" PLUGINS CONFIGURATION
let g:ack_default_options = " --cc --cpp --shell --python --html --js --vue"
" ALE configuration " ALE configuration
"
let g:ale_python_auto_poetry = 1
let g:ale_set_balloons = 1 " enable tooltips let g:ale_set_balloons = 1 " enable tooltips
let g:ale_fixers = { let g:ale_fixers = {
\ '*': ['remove_trailing_lines', 'trim_whitespace'], \ '*': ['remove_trailing_lines', 'trim_whitespace'],
\ 'bash': ['shfmt'], \ 'bash': ['shfmt'],
\ 'sh': ['shfmt'],
\ 'json': ['prettier'], \ 'json': ['prettier'],
\ 'c': ['clang-format'],
\ 'cpp': ['clang-format'], \ 'cpp': ['clang-format'],
\ 'cmake': ['cmakeformat'],
\ 'css': ['prettier'], \ 'css': ['prettier'],
\ 'html': ['prettier'], \ 'html': ['prettier'],
\ 'kotlin': ['ktlint'],
\ 'markdown': ['prettier'], \ 'markdown': ['prettier'],
\ 'terraform': ['terraform'], \ 'java': ['eclipselsp'],
\ 'yaml': ['prettier'], \ 'yaml': ['prettier'],
\ 'python': ['ruff_format'], \ 'python': ['black', 'isort'],
\ 'go': ['gofmt', 'goimports'], \ 'go': ['gofmt', "goimports"],
\ 'rust': ['rustfmt'], \ 'rust': ['rustfmt'],
\ 'sql': ['pgformatter'], \ "javascript": ["prettier", "eslint"],
\ 'java': ['clang-format'], \ "vue": ["prettier", "eslint"]
\ 'javascript': ['prettier', 'eslint'],
\ 'vue': ['prettier', 'eslint'],
\} \}
let g:ale_fixers_aliases = {'vue': ['vue', 'javascript'], 'arduino': 'cpp'} let g:ale_fixers_aliases = {'vue': ['vue', 'javascript']}
let g:ale_arduino_ccls_executable = 'ccls' let g:ale_python_bandit_options = "-c banditrc"
let g:ale_arduino_ccls_init_options = {} " let g:ale_python_pylint_options = "--rcfile pylintrc --disable=W0511" " if the rcfile does not exist, pylint will exit without linting
let g:ale_python_pylint_options = "--disable=W0511"
let g:ale_popup_menu_enabled = 1 let g:ale_cpp_clang_options = '-std=c++17 -Wall -Wpedantic'
let g:ale_python_bandit_options = '-c banditrc' let g:ale_cpp_gcc_options = '-std=c++17 -Wall -Wpedantic'
let g:ale_python_pylint_options = '-j0 --disable=W0511'
let g:ale_python_mypy_options = '--ignore-missing-imports'
" let g:ale_cpp_clang_options = '-std=c++17 -Wall -Wpedantic'
" let g:ale_cpp_gcc_options = '-std=c++17 -Wall -Wpedantic'
let g:ale_rust_cargo_use_clippy = 1
let g:ale_linters = { let g:ale_linters = {
\ 'bash': ['bash-language-server', 'bashlint', 'shellcheck'], \ 'bash': ['bashlint', "shellcheck"],
\ 'dockerfile': ['hadolint'], \ 'dockerfile': ["hadolint"],
\ 'zsh': ['bashlint', 'shellcheck'], \ 'zsh': ['bashlint', "shellcheck"],
\ 'c': ['ccls', 'clangd'], \ 'python': ['pyls', 'pylint', 'bandit'],
\ 'cpp': ['clangd'],
\ 'qml': ['qmllint'],
\ 'python': ['pylsp', 'mypy', 'ruff'],
\ 'go': ['gopls', 'gobuild'], \ 'go': ['gopls', 'gobuild'],
\ 'rust': ['analyzer', 'cargo'], \ 'rust': ['analyzer', 'rustc'],
\ 'yaml': ['yamllint'], \ 'yaml': ['yamllint'],
\ 'javascript': ['yarn lint', 'eslint'], \ 'javascript': ["yarn lint", "eslint", "vls"]
\ 'xml': ['android'],
\ 'groovy': ['android'],
\ 'java': ['eclipselsp', 'android'],
\ 'kotlin': ['android', 'ktlint', 'languageserver'],
\ 'vue': ['volar', 'eslint']
\} \}
let g:ale_linter_aliases = {'vue': ['vue', 'javascript']}
let g:ale_linter_aliases = {'vue': ['vue', 'javascript'], 'arduino': 'cpp'} let g:ale_set_quickfix=1
let g:ale_set_loclist=0
" disable gradle signs/loclist as they conflict with ALE (vim-android)
let g:gradle_loclist_show = 0
let g:gradle_show_signs = 0
let g:ale_java_eclipselsp_path = '~/git/eclipse.jdt.ls'
let g:ale_yaml_yamllint_options = '--config .editorconfig'
let g:ale_open_list = 0 let g:ale_open_list = 0
let g:ale_keep_list_window_open = 1 let g:ale_keep_list_window_open = 1
let g:ale_lint_on_save = 1 let g:ale_lint_on_save = 1
let g:ale_lint_on_enter = 1 " let g:ale_lint_on_enter = 0 " uncomment if you do not want to lint files on open
let g:ale_lint_on_insert_leave = 1 let g:ale_lint_on_insert_leave = 1
let g:ale_lint_on_text_changed = 0 " let g:ale_lint_on_text_changed = 1
let g:ale_lint_delay = 2500 " lint 2.5 seconds after text has changed let g:ale_lint_delay = 2500 " lint 2.5 seconds after text has changed
augroup androiddev
" avoid death by gradle
autocmd! FileType java,kotlin let g:ale_lint_on_insert_leave = 0
augroup END
let g:ale_fix_on_save = 1 let g:ale_fix_on_save = 1
let g:ale_cursor_detail=1
let g:ale_detail_to_floating_preview = 1
let g:ale_completion_enabled = 1 let g:ale_completion_enabled = 1
" let g:ale_completion_autoimport = 1 " let g:ale_completion_autoimport = 1
let g:ale_lsp_show_message_severity = 'information'
let g:ale_lsp_suggestions = 1
let g:ale_rename_tsserver_find_in_comment = 1
let g:ale_sign_priority = 99 let g:ale_sign_priority = 99
let g:ale_sign_error = 'xx' let g:ale_sign_error = "xx"
let g:ale_sign_warning = '>>' let g:ale_sign_warning = ">>"
let g:ale_sign_info = '--' let g:ale_sign_info = "--"
"let g:ale_sign_style_error = "let g:ale_sign_style_error =
"let g:ale_sign_style_warning = "let g:ale_sign_style_warning =
highlight link ALEVirtualTextError ALEError
highlight link ALEVirtualTextWarning ALEWarning
let g:ale_virtualtext_column = "45%"
let g:ale_virtualtext_single = 0 " show all errors
let g:ale_virtualtext_prefix= "[%linter%] %code: %"
let g:ale_exclude_highlights = [
\ 'line too long',
\]
packadd termdebug "useless shit
augroup rust
autocmd!
autocmd BufRead *.rs let g:ale_set_highlights = 0
augroup END
let g:ale_completion_symbols = {
\ 'text': '',
\ 'method': '',
\ 'function': '',
\ 'constructor': '',
\ 'field': '',
\ 'variable': '',
\ 'class': '',
\ 'interface': '',
\ 'module': '',
\ 'property': '',
\ 'unit': 'unit',
\ 'value': 'val',
\ 'enum': '',
\ 'keyword': 'keyword',
\ 'snippet': '',
\ 'color': 'color',
\ 'file': '',
\ 'reference': 'ref',
\ 'folder': '',
\ 'enum member': '',
\ 'constant': '',
\ 'struct': '',
\ 'event': 'event',
\ 'operator': '',
\ 'type_parameter': 'type param',
\ '<default>': 'v'
\ }
" Fix some gitgutter stuff " Fix some gitgutter stuff
let g:gitgutter_enabled = 1 let g:gitgutter_enabled = 1
let g:gitgutter_sign_allow_clobber = 0 " do not allow gitgutter to overwrite signs let g:gitgutter_sign_allow_clobber = 0 " do not allow gitgutter to overwrite signs
let g:gitgutter_sign_priority = 50 let g:gitgutter_sign_priority = 50
" let g:gitgutter_set_sign_backgrounds = 1
" let g:gitgutter_override_sign_column_highlight = 0
" highlight clear GitGutterAdd GitGutterChange GitGutterModified GitGutterDelete SignColumn
highlight SignColumn ctermbg=none
highlight GitGutterAdd ctermbg=none ctermfg=2
highlight GitGutterChange ctermbg=none ctermfg=3
highlight GitGutterDelete ctermbg=none ctermfg=1
highlight GitGutterChangeDelete ctermbg=none ctermfg=1
let g:gitgutter_sign_added = '+' let g:gitgutter_sign_added = '+'
let g:gitgutter_sign_modified = '~' let g:gitgutter_sign_modified = '~'
let g:gitgutter_sign_modified_removed = 'x' let g:gitgutter_sign_modified_removed = 'x'
" Airline config " Improve vimdiff colors (deprecated, this was useful for the twilight256 colorscheme)
" set laststatus=2 " highlight DiffAdd cterm=bold ctermfg=10 ctermbg=17 gui=none guifg=bg guibg=Red
" highlight DiffDelete cterm=bold ctermfg=10 ctermbg=17 gui=none guifg=bg guibg=Red
" highlight DiffChange cterm=bold ctermfg=10 ctermbg=17 gui=none guifg=bg guibg=Red
" highlight DiffText cterm=bold ctermfg=10 ctermbg=88 gui=none guifg=bg guibg=Red
set laststatus=2
let g:airline#extensions#tabline#enabled = 1 let g:airline#extensions#tabline#enabled = 1
let g:airline#extensions#tabline#show_splits = 1
" let g:airline#extensions#tabline#tab_nr_type = 2
let g:airline#extensions#tabline#buffer_idx_mode = 1
nmap <leader>1 <Plug>AirlineSelectTab1
nmap <leader>2 <Plug>AirlineSelectTab2
nmap <leader>3 <Plug>AirlineSelectTab3
nmap <leader>4 <Plug>AirlineSelectTab4
nmap <leader>5 <Plug>AirlineSelectTab5
nmap <leader>6 <Plug>AirlineSelectTab6
nmap <leader>7 <Plug>AirlineSelectTab7
nmap <leader>8 <Plug>AirlineSelectTab8
nmap <leader>9 <Plug>AirlineSelectTab9
nmap <leader>0 <Plug>AirlineSelectTab0
nmap <leader>- <Plug>AirlineSelectPrevTab
nmap <leader>+ <Plug>AirlineSelectNextTab
let g:airline_theme='gruvbox' let g:airline_theme='gruvbox'
if !exists('g:airline_symbols') " default is '☰' and it sucks
let g:airline_symbols = {} let g:airline_symbols.linenr = ''
endif " powerline symbols
let g:airline_left_sep = '' let g:airline_left_sep = ''
let g:airline_left_alt_sep = '' let g:airline_left_alt_sep = ''
let g:airline_right_sep = '' let g:airline_right_sep = ''
let g:airline_right_alt_sep = '' let g:airline_right_alt_sep = ''
let g:airline_symbols.branch = '' let g:airline_symbols.branch = ''
let g:airline_symbols.readonly = '' let g:airline_symbols.readonly = ''
let g:airline_symbols.colnr = ':' " let g:airline_symbols.linenr = '☰'
let g:airline_symbols.linenr = '' " let g:airline_symbols.maxlinenr = ''
let g:airline_symbols.maxlinenr = '' let g:airline_symbols.dirty='⚡'
let g:airline_section_y = ''
let g:airline#extensions#tagbar#enabled = 1
let g:airline_section_x=' %{tagbar#currenttag("%s", "", "f")}'
let g:airline#extensions#tagbar#flags = 's'
let g:airline#extensions#tagbar#searchmethod = 'scoped-stl'
" only these functions will only be defined when lightline#gradle#... funtions
" are defined, which happens when vim-android is loaded
if exists('lightline#gradle#running')
call airline#parts#define_function(
\ 'gradle-running',
\ 'lightline#gradle#running'
\)
call airline#parts#define_function(
\ 'gradle-errors',
\ 'lightline#gradle#errors'
\)
call airline#parts#define_function(
\ 'gradle-warnings',
\ 'lightline#gradle#warnings'
\)
call airline#parts#define_function(
\ 'gradle-project',
\ 'lightline#gradle#project'
\)
let g:airline_section_x= airline#section#create_right([
\ 'filetype',
\ 'gradle-running',
\ 'gradle-errors',
\ 'gradle-warnings'
\])
let g:gradle_glyph_gradle = ''
let g:gradle_glyph_android = ''
let g:gradle_glyph_error = ''
let g:gradle_glyph_warning = ''
let g:gradle_glyph_building = ''
endif
" These are the default mappings for vim-multi-cursor " These are the default mappings for vim-multi-cursor
let g:multi_cursor_start_word_key = '<C-n>' let g:multi_cursor_start_word_key = '<C-n>'
@ -245,53 +119,9 @@ let g:indent_guides_start_level = 2
let g:indent_guides_guide_size = 1 let g:indent_guides_guide_size = 1
"" Gutentags" let g:ctrlp_custom_ignore = {
let g:gutentags_cache_dir = expand('~/.vim/ctags_cache/') \ 'dir': '\v(target|build|dist|.venv)$',
\ 'file': '\v\.(exe|so|dll)$',
let g:gutentags_file_list_command = { \ 'link': 'some_bad_symbolic_links',
\ 'markers': {
\ '.git': 'git ls-files',
\ '.hg': 'hg files',
\ },
\ } \ }
let g:gutentags_generate_on_empty_buffer = 1 let g:ctrlp_user_command = ['.git', 'cd %s && git ls-files -co --exclude-standard']
let g:gutentags_ctags_exclude = ['build', 'dist', '*css', '*json', '*yaml', '*md', '.venv', '*rst']
let g:gutentags_ctags_extra_args = ['--tag-relative=always', ]
"" nerdtree
let NERDTreeIgnore=['__pycache__']
" ultisnips
let g:UltiSnipsExpandTrigger='<tab>'
let g:UltiSnipsJumpForwardTrigger='<c-j>'
let g:UltiSnipsJumpBackwardTrigger='<c-k>'
let g:UltiSnipsEditSplit='context'
"" Fzf
let g:fzf_layout = { 'window': { 'width': 1, 'height': 0.9 } }
let g:fzf_colors =
\ { 'fg': ['fg', 'Normal'],
\ 'bg': ['bg', 'Normal'],
\ 'hl': ['fg', 'Comment'],
\ 'fg+': ['fg', 'CursorLine', 'CursorColumn', 'Normal'],
\ 'bg+': ['bg', 'CursorLine', 'CursorColumn'],
\ 'hl+': ['fg', 'Statement'],
\ 'info': ['fg', 'PreProc'],
\ 'border': ['fg', 'Ignore'],
\ 'prompt': ['fg', 'Conditional'],
\ 'pointer': ['fg', 'Exception'],
\ 'marker': ['fg', 'Keyword'],
\ 'spinner': ['fg', 'Label'],
\ 'header': ['fg', 'Comment'] }
autocmd! FileType fzf
autocmd FileType fzf set laststatus=0 noshowmode noruler
\| autocmd BufLeave <buffer> set laststatus=2 showmode ruler
let g:goyo_width='85%'
let g:goyo_linenr=1
" vim-go
" let g:go_doc_balloon = 1
let g:go_doc_keywordprg_enabled=0

View File

@ -11,12 +11,10 @@ call plug#begin('~/.vim/vim-plug')
Plug 'tpope/vim-sensible' Plug 'tpope/vim-sensible'
" Colorscheme " Colorscheme
Plug 'https://github.com/morhetz/gruvbox' Plug 'https://github.com/morhetz/gruvbox'
" Csv files 🤦
Plug 'https://github.com/mechatroner/rainbow_csv', { 'for': 'csv' }
" Asynchronous Linting Engine " Asynchronous Linting Engine
Plug 'https://github.com/dense-analysis/ale' Plug 'https://github.com/dense-analysis/ale'
" Open files/recent files/tags quickly
Plug 'https://github.com/ctrlpvim/ctrlp.vim'
" Git " Git
Plug 'https://github.com/tpope/vim-fugitive' Plug 'https://github.com/tpope/vim-fugitive'
" Comment shit easily " Comment shit easily
@ -26,36 +24,25 @@ Plug 'https://github.com/scrooloose/nerdtree', { 'on': 'NERDTreeToggle' }
" status line " status line
Plug 'vim-airline/vim-airline' Plug 'vim-airline/vim-airline'
Plug 'vim-airline/vim-airline-themes' Plug 'vim-airline/vim-airline-themes'
" Tags integration
Plug 'https://github.com/preservim/tagbar'
" Insert parentheses in pairs " Insert parentheses in pairs
Plug 'https://github.com/jiangmiao/auto-pairs' Plug 'https://github.com/jiangmiao/auto-pairs'
Plug 'https://github.com/amix/open_file_under_cursor.vim' Plug 'https://github.com/amix/open_file_under_cursor.vim'
" Multi cursor " Multi cursor
Plug 'https://github.com/mg979/vim-visual-multi' Plug 'https://github.com/mg979/vim-visual-multi'
" Easily explore open buffers
Plug 'https://github.com/vim-scripts/bufexplorer.zip'
" Search
Plug 'https://github.com/mileszs/ack.vim'
" Yank history " Yank history
Plug 'https://github.com/maxbrunsfeld/vim-yankstack' Plug 'https://github.com/maxbrunsfeld/vim-yankstack'
" Mark indentation level " Mark indentation level
Plug 'https://github.com/nathanaelkane/vim-indent-guides' Plug 'https://github.com/nathanaelkane/vim-indent-guides'
Plug 'https://github.com/majutsushi/tagbar'
if executable('meson') " snipmate
Plug 'https://github.com/igankevich/mesonic' Plug 'https://github.com/MarcWeber/vim-addon-mw-utils'
endif Plug 'https://github.com/tomtom/tlib_vim'
Plug 'https://github.com/garbas/vim-snipmate'
" fzf
Plug 'junegunn/fzf'
Plug 'junegunn/fzf.vim'
" Open tags with fzf's :Tags
if executable('ctags')
Plug 'https://github.com/ludovicchabant/vim-gutentags.git'
endif
" snippets
if has('python3')
Plug 'https://github.com/SirVer/ultisnips'
Plug 'https://github.com/honza/vim-snippets'
endif
" Git gutter line " Git gutter line
Plug 'https://github.com/airblade/vim-gitgutter' Plug 'https://github.com/airblade/vim-gitgutter'
@ -66,56 +53,16 @@ Plug 'https://github.com/junegunn/goyo.vim'
Plug 'https://github.com/mgedmin/coverage-highlight.vim' Plug 'https://github.com/mgedmin/coverage-highlight.vim'
"Languages "Languages
Plug 'https://github.com/bfrg/vim-cpp-modern', {'for': 'cpp'} Plug 'https://github.com/rust-lang/rust.vim'
Plug 'epheien/termdbg', {'for': ['c', 'cpp']} Plug 'https://github.com/vim-scripts/nginx.vim'
Plug 'https://github.com/plasticboy/vim-markdown'
Plug 'https://github.com/cespare/vim-toml'
if executable('cargo') Plug 'epheien/termdbg'
Plug 'https://github.com/rust-lang/rust.vim', {'for': 'rust'}
endif
Plug 'https://github.com/vim-scripts/nginx.vim', {'for': 'nginx'}
Plug 'https://github.com/plasticboy/vim-markdown', {'for': 'markdown'}
Plug 'https://github.com/cespare/vim-toml', {'for': 'toml'}
Plug 'https://github.com/vim-scripts/iptables', {'for': 'iptables'}
if executable('vite')
" TODO: check if plugin is still up-to-date
Plug 'https://github.com/leafoftree/vim-vue-plugin', {'for': 'vue'}
endif
if executable('terraform')
Plug 'https://github.com/hashivim/vim-terraform', {'for': 'terraform'}
endif
if executable('go')
Plug 'https://github.com/fatih/vim-go', {'for': 'go'}
endif
if executable('adb') && executable('gradle')
Plug 'https://github.com/udalov/kotlin-vim', {'for': 'kotlin'}
Plug 'https://github.com/hsanson/vim-android', {'for': 'java'}
endif
if executable('qml')
Plug 'https://github.com/peterhoeg/vim-qml', {'for': 'qml'}
endif
if executable('pytest')
Plug 'https://github.com/alfredodeza/pytest.vim', {'for': 'python'}
endif
" Colorize hex codes and/or color strings
Plug 'https://github.com/chrisbra/Colorizer'
" No RGB, no party " No RGB, no party
let vim_razer = expand('~/projects_razer/vim-razer') let vim_razer = expand('~/projects_razer/vim-razer')
if isdirectory(vim_razer) if isdirectory(vim_razer)
Plug vim_razer Plug vim_razer
endif endif
if g:uname ==? 'Linux'
Plug 'https://github.com/HiPhish/info.vim'
endif
call plug#end() call plug#end()
" Install plugins if missing
if ! isdirectory(expand('~/.vim/vim-plug'))
PlugInstall
endif

View File

@ -1,166 +1,115 @@
"""" Leader shortcuts """" Leader shortcuts
let mapleader = ','
let mapleader = ","
" also use space as leader " also use space as leader
map <Space> <leader> nmap <Space> <leader>
nmap <leader>w :w!<CR> nmap <leader>w :w!<CR>
command! W execute 'w !sudo tee % > /dev/null' <bar> edit! command! W execute 'w !sudo tee % > /dev/null' <bar> edit!
" nmap <leader>W :w!<CR> " nmap <leader>W :w!<CR>
" config editing "Reload vimrc on config change
map <leader>e :vsplit ~/.vimrc<CR> map <leader>e :e! ~/.vimrc<CR>
map <leader>ef :vsplit $DOTFILES/vim/functions.vim<CR> " FIXME: This results in some weird conflict with lightline
map <leader>ec :vsplit $DOTFILES/vim/plugins_config.vim<CR> autocmd! bufwritepost ~/.vimrc source ~/.vimrc
map <leader>es :vsplit $DOTFILES/vim/shortcuts.vim<CR> autocmd! bufwritepost $DOTFILES/vim/* source ~/.vimrc
map <leader>ep :vsplit $DOTFILES/vim/plugs.vim<CR>
" Quickly open a markdown buffer for scribble " Quickly open a markdown buffer for scribble
map <leader>x :e ~/buffer.md<CR> map <leader>x :e ~/buffer.md<CR>
map <leader>xx :e ~/projects/work/buffer.md<CR>
" Toggle paste mode on and off " Toggle paste mode on and off
nmap <leader>pp :setlocal paste!<CR> nmap <leader>pp :setlocal paste!<CR>
" Re-select the text block just pasted " Re-select the text block just pasted
nnoremap <Leader>vv V`] nnoremap <Leader>vv V`]
" Easy tab navigation with <leader>T
nmap <leader>Tn :tabnext<CR>
nmap <leader>TN :tabnew<CR>
nmap <leader>Tp :tabprev<CR>
nmap <leader>Tc :tabclose<CR>
nmap <C-W>n :tabnext<CR>
nmap <C-W>p :tabprev<CR>
nmap <C-W>N :tabnew<CR>
" move betweween functions/methods/classes definition,
" [m moves to the start of the previous method, ]m to the start of the next
" zz centers the result
map <Leader>] ]mzz
map <Leader>[ [mzz
" open quickfix " open quickfix
nmap <leader>cc :botright cope<CR> nmap <leader>cc :botright cope<CR>
" open loclist
nmap <leader>ll :botright lope<CR>
" close quickfix (also see <leader>C below) " close quickfix (also see <leader>C below)
nmap <leader>cx :hide<CR> nmap <leader>cx :hide<CR>
nmap <leader>co ggVGy:tabnew<CR>:set syntax=qf<CR>pgg nmap <leader>co ggVGy:tabnew<CR>:set syntax=qf<CR>pgg
" next cope error " next cope error
map <leader>N :cnext<CR> map <leader>cn :cn<CR>
" previous cope error " previous cope error
map <leader>P :cprevious<CR> map <leader>cp :cp<CR>
"disable highlighting current search word map <silent> <leader><CR> :noh<CR> "disable highlighting for current word
map <silent> <leader><CR> :noh<CR> map <leader>ss :setlocal spell!<CR>
map <leader>S :setlocal spell!<CR>
nnoremap <leader>M :bel copen<bar>silent make <bar>redraw!<CR> nnoremap <leader>mk :bel copen<bar>silent (cargo run) !<bar>redraw!<CR>
nnoremap <leader>wz :call WinZoomToggle()<CR> nnoremap <leader>wz :call WinZoomToggle()<CR>
nnoremap <leader>q :close<CR> nmap \ :Explore<CR>
nnoremap <leader>C :close<CR>
nnoremap <leader>B :Bclose<CR> nnoremap <leader>B :Bclose<CR>
nnoremap <leader>Q :close!<CR> nnoremap <leader>k :Ack<Space>
nnoremap <leader>k :Rg<CR>
"" Fugitive "" Fugitive
nnoremap <leader>/ :vert Git<CR> nnoremap <leader>/ :Git<CR>
nnoremap <leader>\ :0Git<CR> nnoremap <leader>g :Git<CR>
nnoremap <leader>d :Gvdiffsplit<CR> nnoremap <leader>gd :Git diff<CR>
nnoremap <leader>b :Git blame<CR>
nnoremap <leader>gp :Git push<CR> nnoremap <leader>gp :Git push<CR>
nnoremap <leader>gl :Commits<CR> nnoremap <leader>M :Git commit<CR>
nnoremap <leader>gL :BCommits<CR>
nnoremap <leader>gc :Git commit<CR>
nnoremap <leader>gpf :Git push --force-with-lease<CR> nnoremap <leader>gpf :Git push --force-with-lease<CR>
"" Gitutter "" Gitutter
nnoremap <leader>u :GitGutterBufferToggle<CR> nnoremap <leader>u :GitGutterBufferToggle<CR>
nnoremap <leader>L :GitGutterLineHighlightsToggle<CR> nnoremap <leader>L :GitGutterLineHighlightsToggle<CR>
nnoremap <leader>gp :GitGutterPrevHunk<CR> nmap <leader>hn <Plug>(GitGutterNextHunk)
nnoremap <leader>gn :GitGutterNextHunk<CR> nmap <leader>hp <Plug>(GitGutterPrevHunk)
nnoremap <leader>gs :GitGutterStageHunk<CR>
nnoremap <leader>gu :GitGutterUndoHunk<CR>
"" Ale
"" Coverage Highlight
nnoremap <leader>H :HighlightCoverageForAll<CR>
" Ale
nmap <silent> <C-k> <Plug>(ale_previous_wrap) nmap <silent> <C-k> <Plug>(ale_previous_wrap)
nmap <silent> <C-j> <Plug>(ale_next_wrap) nmap <silent> <C-j> <Plug>(ale_next_wrap)
nmap <leader>R :ALERepeatSelection<CR>
nmap <leader>sv :ALEGoToDefinition -vsplit<CR> nmap <leader>sv :ALEGoToDefinition -vsplit<CR>
nmap <leader>sh :ALEGoToDefinition -split<CR> nmap <leader>sh :ALEGoToDefinition -split<CR>
nmap <leader>st :ALEGoToDefinition -tab<CR> nmap <leader>st :ALEGoToDefinition -tab<CR>
nmap <leader>A :ALEGoToDefinition<CR> nmap <leader>A :ALEGoToDefinition<CR>
nmap <leader>n :ALEFindReferences -quickfix <bar> copen<CR> nmap <leader>n :ALEFindReferences<CR>
nmap <leader>h :ALEHover<CR> nmap <leader>h :ALEHover<CR>
nmap <leader>r :ALERename<CR> nmap <leader>r :ALERename<CR>
nmap <leader>` :ALELint<CR> map <leader>` :ALELint<CR>
nmap <leader>F :ALEFix<CR>
nmap <leader>D :ALEToggle<CR> " call ack when pressing gv in visual
vnoremap <silent> gv :call VisualSelection('gv', '')<CR>
map <leader>nn :NERDTreeToggle<CR> map <leader>nn :NERDTreeToggle<CR>
map <leader>o :BufExplorer<CR>
"" fzf.vim "" CtrlP
" Quickly find and open a recently opened file " Quickly find and open a recently opened file
map <leader>o :Buffers<CR> " let g:ctrlp_map = '<C-f>'
map <leader>j :GFiles<CR> map <C-b> :CtrlPBuffer<CR>
map <leader>J :Files<CR> map <leader>j :CtrlP<CR>
map <leader>b :CtrlPBuffer<CR>
map <leader>f :CtrlPMRUFiles<CR>
map <leader>t :CtrlPTag<CR>
map <leader>f :History<CR>
map <leader>T :BTags<CR>
map <leader>t :Tags<CR>
map <leader>l :Lines<CR>
" FIXME: Not using CtrlP anymore, replace this with fzf
""map <leader>c :CtrlPQuickfix<CR>
map <leader>s :Snippets<CR>
map <leader>; :Commands<CR>
map <leader>m :Maps<CR>
"" Indent Guides let s:uname=''
map <leader>I :IndentGuidesToggle<CR> let s:uname = system('uname | tr -d "\n"') " Get platform name (stripping the trailing newline)
map <leader>i :set cursorcolumn!<CR> if s:uname == "Darwin"
"" Goyo
nmap <leader>zz :Goyo<CR>
""" Tagbar
nmap <F8> :TagbarToggle<CR>
""Misc stuff
if g:uname ==? 'Darwin'
"" Mac specific stuff "" Mac specific stuff
elseif g:uname ==? 'Linux' elseif s:uname == "linux"
"" Linux specific stuff "" Linux specific stuff
xnoremap "+y y:call system("wl-copy", @")<cr> " Wayland clipboard fix https://github.com/vim/vim/issues/5157
map "+p :<C-U>let @"=substitute(system('wl-paste --no-newline'), '<C-v><C-m>', '', 'g') \| exec 'normal! ' . v:count1 . 'p'<cr> xnoremap "+y :call system("wl-copy", @")<CR>
nnoremap "+p :let @"=substitute(system("wl-paste --no-newline"), '<C-v><C-m>', '', 'g')<cr>p
xnoremap "*y :call system("wl-copy --primary", @")<CR>
nnoremap "*p :let @"=substitute(system("wl-paste --no-newline --primary"), '<C-v><C-m>', '', 'g')<cr>p
else else
"" Unknown platform "" Unkown platform
endif endif
" Add shortcuts to yank/paste to unnamed/unnamedplus clipboards " Add shortcuts to yank/paste to unnamed/unnamedplus clipboards
map <Leader>y "+y noremap <Leader>y "*y
map <Leader>p "+p noremap <Leader>p "*p
map <Leader>yp <Plug>yankstack_substitute_older_paste noremap <Leader>Y "+y
map <leader>yn <Plug>yankstack_substitute_newer_paste noremap <Leader>P "+p
" Insert a python breakpoint
let @b = 'obreakpoint(€kr€ýa0j'
" visual mode mappings
vnoremap <silent> <leader>k :call VisualSelection('LAck', '')<CR>
vnoremap <silent> <leader>gs :call GitShowVisual()<CR>
vnoremap <silent> <leader>r :call VisualSelection('replace', '')<CR>
nnoremap K :exe "Rg " . expand("<cword>")<cr>
nnoremap GL :exe "Git log -L:" . expand("<cword>") . ":" . expand("%")<cr>
autocmd FileType python nnoremap T :Pytest function --pdb<CR>
" Ultisnips
map <Leader>ue :UltiSnipsEdit<cr>
nmap <F5> <ESC>:Gradle assembleDebug<CR> " A friggin python breakpoint. Invoke with @b "FIXME: make this decent
nmap <F6> <ESC>:AndroidInstall debug<CR> let @b = 'A breakpoint()€ýajkj0'
nmap <F7> <ESC>:AndroidLaunch debug<CR>
" Tagbar
nmap <F8> :TagbarToggle<CR>

123
vim/vimrc
View File

@ -1,5 +1,3 @@
let g:uname = system('uname | tr -d "\n"') " Get platform name (stripping the trailing newline)
" Install all plugins " Install all plugins
source $DOTFILES/vim/plugs.vim source $DOTFILES/vim/plugs.vim
@ -7,38 +5,16 @@ source $DOTFILES/vim/plugs.vim
set encoding=utf-8 set encoding=utf-8
scriptencoding utf-8 scriptencoding utf-8
"" Style " Style
" enable truecolor mode
if has('termguicolors')
set termguicolors
else
let &t_8f = "\<Esc>[38:2:%lu:%lu:%lum"
let &t_8b = "\<Esc>[48:2:%lu:%lu:%lum"
endif
if !empty($THEME_PREFER_LIGHT)
set background=light
else
set background=dark set background=dark
endif
let g:gruvbox_contrast_dark='hard'
let g:gruvbox_sign_column='bg0'
" Show some gui colors in term
let g:gruvbox_guisp_fallback='bg'
colorscheme gruvbox colorscheme gruvbox
" General stuff " General stuff
set nowrap set nowrap
set mouse=a set mouse=a
set mousemodel=popup_setpos " allow for ALE code actions
if has('mouse_sgr') " fixes unclickable panes after a specific column (~220?)
set ttymouse=sgr
else
set ttymouse=xterm2
end
set relativenumber number set relativenumber number
set foldlevelstart=3 foldmethod=indent nofoldenable "without foldenable all folds are open at startup" set foldlevelstart=3 foldmethod=syntax nofoldenable "without nofoldenable all folds are closed at startup"
set ttymouse=xterm2 " fix mouse when used in tmux/byobu https://unix.stackexchange.com/q/50733
set nobackup nowb noswapfile " no need for backups of every file set nobackup nowb noswapfile " no need for backups of every file
set history=10000 set history=10000
@ -53,87 +29,14 @@ set lazyredraw
set ignorecase smartcase " ignore case on search but be smart about it set ignorecase smartcase " ignore case on search but be smart about it
set hlsearch "highlight search results (using *) set hlsearch "highlight search results (using *)
set expandtab shiftwidth=4 tabstop=4 "always use spaces set shiftwidth=4 tabstop=4
" Completion menu config (see :h completopt)
set completeopt=menu,menuone,noselect,noinsert
" Show completion suggestions in popups instead of preview window
set completeopt+=popup
" Highlight the line the cursor is on
set cursorline
" Minimum fold size
set foldminlines=3
" Timeout for combined keymaps (half a sec)
set timeoutlen=500
" keep history the last 1000 opened files, 200 commands and 50 search
" patterns. `h` persists bookmarks across sessions
set viminfo='1000,<200,s50,h
autocmd FileType qf,ll setlocal wrap "quickfix,loclist
"autocmd FileType markdown setlocal wrap spell spelllang=it,en
autocmd FileType yaml,yml setlocal shiftwidth=2 softtabstop=2 expandtab autocmd FileType yaml,yml setlocal shiftwidth=2 softtabstop=2 expandtab
autocmd FileType vue setlocal shiftwidth=2 softtabstop=2 expandtab
autocmd FileType go setlocal noexpandtab makeprg=go\ build
autocmd FileType rust set makeprg=cargo\ build
autocmd FileType python set keywordprg="pydoc"
syntax match jsonComment "//.*"
syntax match jsonComment "\(/\*\)\|\(\*/\)"
hi def link jsonComment Comment
augroup dvc
au BufRead dvc.yaml let b:ale_fix_on_save=0
au BufRead *.dvc let b:ale_fix_on_save=0
au BufRead *.dvc set filetype=yaml
augroup END
augroup ansible
au BufRead,BufNewFile */playbooks/*.yml set filetype=yaml.ansible
augroup END
augroup githubactions
au BufRead,BufNewFile */.github/*/*.y{,a}ml
\ let b:ale_linters = {'yaml': ['actionlint'] }
augroup END
augroup iptables
au BufRead,BufNewFile rules.v[46],*.rules setlocal filetype=iptables
augroup END
augroup vimconfig
" Reload vimrc on config change
autocmd! bufwritepost ~/.vimrc source ~/.vimrc
autocmd! bufwritepost $DOTFILES/vim/vimrc source ~/.vimrc
autocmd! bufwritepost $DOTFILES/vim/shortcuts.vim source ~/.vimrc
" Install/Update plugs on change
autocmd! bufwritepost $DOTFILES/vim/plugs.vim PlugInstall
autocmd! bufwritepost $DOTFILES/vim/plugs.vim PlugUpdate
augroup END
if has('persistent_undo')
let undo_dir=$HOME . '/.vim/undo'
if !isdirectory(undo_dir)
call mkdir(undo_dir , 'p', 0700)
endif
let &undodir=undo_dir
set undofile
endif
augroup dotgit
" Return to last edit position when opening files (from amix's vimrc) " Return to last edit position when opening files (from amix's vimrc)
au BufReadPost * if ! exists('b:dotgitFolder') | if line("'\"") > 1 && line("'\"") <= line("$") | exe "normal! g'\"" | endif au BufReadPost * if line("'\"") > 1 && line("'\"") <= line("$") | exe "normal! g'\"" | endif
" set a marker to avoid returning to the previous position in .git folders
" (avoids returning to previous position for COMMIT_EDITMSG etc ) " Remap VIM 0 to first non-blank character
au BufReadPost */.git/* let b:dotgitFolder = 1 " map 0 ^
" do not apply fixers to patches
au BufReadPost .git/*.diff let b:ale_fix_on_save=0
augroup END
" Bash like keys for the command line " Bash like keys for the command line
cnoremap <C-A> <Home> cnoremap <C-A> <Home>
@ -143,10 +46,12 @@ cnoremap <C-K> <C-U>
cnoremap <C-P> <Up> cnoremap <C-P> <Up>
cnoremap <C-N> <Down> cnoremap <C-N> <Down>
try
set undodir=~/.vim/temp_dirs/undodir
set undofile
catch
endtry
source $DOTFILES/vim/plugins_config.vim source $DOTFILES/vim/plugins_config.vim
source $DOTFILES/vim/shortcuts.vim source $DOTFILES/vim/shortcuts.vim
source $DOTFILES/vim/functions.vim source $DOTFILES/vim/functions.vim
if filereadable('.vimrc.local')
source .vimrc.local
endif

View File

@ -1,24 +0,0 @@
# vim:ft=zsh
djui/alias-tips
ohmyzsh/ohmyzsh path:lib
ohmyzsh/ohmyzsh path:plugins/ansible
ohmyzsh/ohmyzsh path:plugins/bgnotify
ohmyzsh/ohmyzsh path:plugins/colored-man-pages
ohmyzsh/ohmyzsh path:plugins/common-aliases
ohmyzsh/ohmyzsh path:plugins/docker
ohmyzsh/ohmyzsh path:plugins/docker-compose
ohmyzsh/ohmyzsh path:plugins/fzf
ohmyzsh/ohmyzsh path:plugins/git
ohmyzsh/ohmyzsh path:plugins/golang
ohmyzsh/ohmyzsh path:plugins/grc
ohmyzsh/ohmyzsh path:plugins/pip
ohmyzsh/ohmyzsh path:plugins/pyenv
ohmyzsh/ohmyzsh path:plugins/pylint
ohmyzsh/ohmyzsh path:plugins/sudo
ohmyzsh/ohmyzsh path:plugins/vagrant
ohmyzsh/ohmyzsh path:plugins/vi-mode
zsh-users/zsh-autosuggestions
zsh-users/zsh-completions
zsh-users/zsh-syntax-highlighting
joshskidmore/zsh-fzf-history-search
ryutok/rust-zsh-completions