summaryrefslogtreecommitdiffstats
path: root/bashrc
blob: 063ccd2bbf05e8d8cfd92f93aabefa95caaa5c4c (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
# ~/.bashrc: executed by bash(1) for non-login shells.
# see /usr/share/doc/bash/examples/startup-files (in the package bash-doc)
# for examples

# as advised by https://manpages.debian.org/buster/gpg-agent/gpg-agent.1.en.html
GPG_TTY=$(tty)
export GPG_TTY

# If not running interactively, don't do anything
case $- in
    *i*) ;;
      *) return;;
esac

export GDK_SCALE=2
export GDK_DPI_SCALE=0.5
export QT_AUTO_SCREEN_SET_FACTOR=0
export QT_SCALE_FACTOR=2
export QT_FONT_DPI=96

# secrets
source ~/secrets

# don't put duplicate lines or lines starting with space in the history.
# See bash(1) for more options
HISTCONTROL=ignoreboth

# append to the history file, don't overwrite it
shopt -s histappend

# for setting history length see HISTSIZE and HISTFILESIZE in bash(1)
HISTSIZE=1000
HISTFILESIZE=2000

# check the window size after each command and, if necessary,
# update the values of LINES and COLUMNS.
shopt -s checkwinsize

# If set, the pattern "**" used in a pathname expansion context will
# match all files and zero or more directories and subdirectories.
#shopt -s globstar

# make less more friendly for non-text input files, see lesspipe(1)
#[ -x /usr/bin/lesspipe ] && eval "$(SHELL=/bin/sh lesspipe)"

# set variable identifying the chroot you work in (used in the prompt below)
if [ -z "${debian_chroot:-}" ] && [ -r /etc/debian_chroot ]; then
    debian_chroot=$(cat /etc/debian_chroot)
fi

# set a fancy prompt (non-color, unless we know we "want" color)
case "$TERM" in
    xterm-color|*-256color) color_prompt=yes;;
esac

# uncomment for a colored prompt, if the terminal has the capability; turned
# off by default to not distract the user: the focus in a terminal window
# should be on the output of commands, not on the prompt
#force_color_prompt=yes

if [ -n "$force_color_prompt" ]; then
    if [ -x /usr/bin/tput ] && tput setaf 1 >&/dev/null; then
	# We have color support; assume it's compliant with Ecma-48
	# (ISO/IEC-6429). (Lack of such support is extremely rare, and such
	# a case would tend to support setf rather than setaf.)
	color_prompt=yes
    else
	color_prompt=
    fi
fi

if [ "$color_prompt" = yes ]; then
    PS1='${debian_chroot:+($debian_chroot)}\[\033[01;32m\]\u@\h\[\033[00m\]:\[\033[01;34m\]\w\[\033[00m\]\$ '
else
    PS1='${debian_chroot:+($debian_chroot)}\u@\h:\w\$ '
fi
unset color_prompt force_color_prompt

# If this is an xterm set the title to user@host:dir
case "$TERM" in
xterm*|rxvt*)
    PS1="\[\e]0;${debian_chroot:+($debian_chroot)}\u@\h: \w\a\]$PS1"
    ;;
*)
    ;;
esac

# enable color support of ls and also add handy aliases
if [ -x /usr/bin/dircolors ]; then
    test -r ~/.dircolors && eval "$(dircolors -b ~/.dircolors)" || eval "$(dircolors -b)"
    alias ls='ls --color=auto'
    #alias dir='dir --color=auto'
    #alias vdir='vdir --color=auto'

    alias grep='grep --color=auto'
    #alias fgrep='fgrep --color=auto'
    #alias egrep='egrep --color=auto'
fi

# colored GCC warnings and errors
#export GCC_COLORS='error=01;31:warning=01;35:note=01;36:caret=01;32:locus=01:quote=01'

# some more ls aliases
alias ll='ls -l'
alias la='ls -A'
alias l='ls -CF'

# Alias definitions.
# You may want to put all your additions into a separate file like
# ~/.bash_aliases, instead of adding them here directly.
# See /usr/share/doc/bash-doc/examples in the bash-doc package.

if [ -f ~/.bash_aliases ]; then
    . ~/.bash_aliases
fi

# enable programmable completion features (you don't need to enable
# this, if it's already enabled in /etc/bash.bashrc and /etc/profile
# sources /etc/bash.bashrc).
if ! shopt -oq posix; then
  if [ -f /usr/share/bash-completion/bash_completion ]; then
    . /usr/share/bash-completion/bash_completion
  elif [ -f /etc/bash_completion ]; then
    . /etc/bash_completion
  fi
fi

# todoist-cli completion
source "$HOME/bin/todoist_fzf.sh"
alias ftodoist="todoist --namespace --project-namespace list | fzf --preview 'todoist show {1}' | cut -d ' ' -f 1 | tr '\n' ' '"

# aliases
alias chromium="flatpak run com.github.Eloston.UngoogledChromium > /dev/null 2>&1 &"
alias gloga='git log --oneline --decorate --graph --all'
alias batnote='batnote-source-code'
alias am='append_to_masterlist'
alias vi='vim'
alias ls='ls --color=auto'
alias h='hey_openai'
alias hd='openai_data'
alias xclip='xclip -selection c'
alias notes="cd ~/Documents/Notes/"
alias blog="cd ~/code/html/yulqen.org/"
alias bud="cd ~/Budget/hledger/hledger/"
alias getip="curl ifconfig.me"
alias tprojects="task rc.list.all.projects=1 projects"
alias tworkprojects='task _unique project|grep "w\."'
alias thomeprojects='task _unique project|grep "h\."'
alias ttags="task rc.list.all.tags=1 tags"
alias tkilled="task +killlist list"
alias ttagged="task tags.any: list"
alias tuntagged="task tags.none: list"
alias ttoday="task ml_due_or_scheduled_today"
alias tl="/home/lemon/Documents/Notes/todo/todo.sh list"
alias t="task"
alias khal="$HOME/src/virtualenvs/khal-venv/bin/khal"
alias vdirsyncer="$HOME/src/virtualenvs/khal-venv/bin/vdirsyncer"
alias khard="$HOME/src/virtualenvs/khal-venv/bin/khard"
alias thisweek='khal list today 5days -d google_timebox'
alias tcomptoday='task end.after:today-1d completed'
alias passwrap='pass-fzf.bash'
alias nvim='~/.local/bin/nvim'
alias rem1='ssh bobbins rem -c+a1 -w170 -m'
alias rem2='ssh bobbins rem -c+a2 -w170 -m'
alias _hl_bal_lastmonth='hledger bal --period "this month" --depth 3 Expenses'

# Environment variables
export LEDGER_FILE="$HOME/Budget/hledger/hledger/budget.ledger"
#export TERM="screen-256color" arch wiki says not to set this here.
export LESS="-iMRS -x2"
export NOTES_DIR="$HOME/Documents/Notes"
export RANGER_LOAD_DEFAULT_RC="FALSE"
export FZF_DEFAULT_COMMAND="rg --files --hidden --glob '!.git' "
#export FZF_DEFAULT_COMMAND='ag -l --path-to-ignore ~/.ignore --nocolor --hidden -g ""'
export FZF_CTRL_T_COMMAND="$FZF_DEFAULT_COMMAND"
export FZF_ALT_C_COMMAND="$FZF_DEFAULT_COMMAND"
export FZF_DEFAULT_OPTS="--preview='bat --color=always {}' --bind shift-up:preview-page-up,shift-down:preview-page-down --color info:108,prompt:109,spinner:108,pointer:168,marker:168"

# fzf
source /usr/share/doc/fzf/examples/key-bindings.bash

# fzf command history from https://github.com/junegunn/fzf/wiki/examples#command-history

bind '"\C-r": "\C-x1\e^\er"'
bind -x '"\C-x1": __fzf_history';

__fzf_history ()
{
__ehc $(history | fzf --tac --tiebreak=index | perl -ne 'm/^\s*([0-9]+)/ and print "!$1"')
}

__ehc()
{
if
        [[ -n $1 ]]
then
        bind '"\er": redraw-current-line'
        bind '"\e^": magic-space'
        READLINE_LINE=${READLINE_LINE:+${READLINE_LINE:0:READLINE_POINT}}${1}${READLINE_LINE:+${READLINE_LINE:READLINE_POINT}}
        READLINE_POINT=$(( READLINE_POINT + ${#1} ))
else
        bind '"\er":'
        bind '"\e^":'
fi
}

# fkill - kill processes - list only the ones you can kill. Modified the earlier script.
fkill() {
    local pid 
    if [ "$UID" != "0" ]; then
        pid=$(ps -f -u $UID | sed 1d | fzf -m | awk '{print $2}')
    else
        pid=$(ps -ef | sed 1d | fzf -m | awk '{print $2}')
    fi  

    if [ "x$pid" != "x" ]
    then
        echo $pid | xargs kill -${1:-9}
    fi  
}

# fco_preview - checkout git branch/tag, with a preview showing the commits between the tag/branch and HEAD
fco_preview() {
  local tags branches target
  branches=$(
    git --no-pager branch --all \
      --format="%(if)%(HEAD)%(then)%(else)%(if:equals=HEAD)%(refname:strip=3)%(then)%(else)%1B[0;34;1mbranch%09%1B[m%(refname:short)%(end)%(end)" \
    | sed '/^$/d') || return
  tags=$(
    git --no-pager tag | awk '{print "\x1b[35;1mtag\x1b[m\t" $1}') || return
  target=$(
    (echo "$branches"; echo "$tags") |
    fzf --no-hscroll --no-multi -n 2 \
        --ansi --preview="git --no-pager log -150 --pretty=format:%s '..{2}'") || return
  git checkout $(awk '{print $2}' <<<"$target" )
}

# fshow - git commit browser
fshow() {
  git log --graph --color=always \
      --format="%C(auto)%h%d %s %C(black)%C(bold)%cr" "$@" |
  fzf --ansi --no-sort --reverse --tiebreak=index --bind=ctrl-s:toggle-sort \
      --bind "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"
}

# ftags - search ctags
ftags() {
  local line
  [ -e tags ] &&
  line=$(
    awk 'BEGIN { FS="\t" } !/^!/ {print toupper($4)"\t"$1"\t"$2"\t"$3}' tags |
    cut -c1-80 | fzf --nth=1,2
  ) && ${EDITOR:-vim} $(cut -f3 <<< "$line") -c "set nocst" \
                                      -c "silent tag $(cut -f2 <<< "$line")"
}

# tm - create new tmux session, or switch to existing one. Works from within tmux too. (@bag-man)
# `tm` will allow you to select your tmux session via fzf.
# `tm irc` will attach to the irc session (if it exists), else it will create it.

tm() {
  [[ -n "$TMUX" ]] && change="switch-client" || change="attach-session"
  if [ $1 ]; then
    tmux $change -t "$1" 2>/dev/null || (tmux new-session -d -s $1 && tmux $change -t "$1"); return
  fi
  session=$(tmux list-sessions -F "#{session_name}" 2>/dev/null | fzf --exit-0) &&  tmux $change -t "$session" || echo "No sessions found."
}

tmuxkillf() {
    local sessions
    sessions="$(tmux ls | fzf --exit-0 --multi)" || return $?
    local i
    for i in "${sessions[@]}"
    do
        if [[ $i =~ ([^:]*):.* ]]; then
            echo "Killing ${BASH_REMATCH[1]}"
            tmux kill-session -t "${BASH_REMATCH[1]}"
        fi
    done
}

fman() {
    man -k . | fzf -q "$1" --prompt='man> '  --preview $'echo {} | tr -d \'()\' | awk \'{printf "%s ", $2} {print $1}\' | xargs -r man | col -bx | bat -l man -p --color always' | tr -d '()' | awk '{printf "%s ", $2} {print $1}' | xargs -r man
}
# Get the colors in the opened man page itself
export MANPAGER="sh -c 'col -bx | bat -l man -p --paging always'"


# Functions

##############################################################
# Quick way to create a new blog post with Hugo from wherever
# on the filesystem.
# Used ChatGPT to get the substitution and escaping correct.
# Called with a single string argument.
# ############################################################

function newpost() {
  if [[ $# -ne 1 ]]; then echo "Give me the title!"; return; fi
  title="$1"
  # convert title to lowercase and replace spaces with hyphens for the slug
  slug=$(echo "$title" | tr '[:upper:]' '[:lower:]' | tr ' ' '-')
  # create the new post file with Hugo
  cd $HOME/code/html/yulqen.org
  post_path="content/blog/$slug.md"
  hugo new "$post_path"
  # update the front matter with the original title string
  echo "Looking for $post_path..."
  awk -v title="$title" '{gsub(/title: .*/, "title: \""title"\"")}1' "$post_path" > tmp && mv tmp "$post_path"
  vim $post_path
}

###################################################################
# To output in cat, just call todj.
# To enable editing the files in vim, call todj vim.
# You can use less or any other tool to display the text if you wish
# Arguments:
# 	None
#	Output:
#		Writes to stdout or opens program passed as first argument
###################################################################
todj () {
  CMD=${1:-"cat"}
  $CMD $(find /home/lemon/Documents/Notes/journal/home -name "*$(date '+%Y-%m-%d')*")
}

#########################################################################
# This function takes two arguments as strings. The idea is to enable
# passing file data into the function, such as a csv file or some code.
# Call like this openai_data "Please optimise the following function in
# python" "$(</path/to/file)" This is supposed to be a good way to read a
# file's contents in bash
# Arguments:
# 	Text prompt
#		File contents
#	Output:
#		Writes to stdout
#########################################################################
openai_data() {
  if [[ $# -ne 2 ]]; then echo "Give me two params!"; return; fi

		text_prompt="$1"
    data="$2"
    prompt="${text_prompt}: ${data}"
    json=$(jq -n --arg p "$data" '{model: "gpt-3.5-turbo", messages: [{role: "user", content: $p}], temperature: 0.7}')
    local gpt=$(curl https://api.openai.com/v1/chat/completions -s \
    -H "Content-Type: application/json" \
    -H "Authorization: Bearer $OPENAI_KEY" \
    -H "OpenAI-Organization: $OPENAI_ORG_ID" \
    -d "$json")
    echo $gpt | jq -r '.choices[0].message.content'
}

################################################################################
# A straight forward request to the OpenAI GPT-3 model.
# Takes a single string argument and returns a simple response.
# hey_openai "What is the best way to open and interate through a file in Perl?"
# Arguments:
# 	Text prompt
#	Output:
#		Writes to stdout
################################################################################
hey_openai() {
		prompt="$1"
    local gpt=$(curl https://api.openai.com/v1/chat/completions -s \
    -H "Content-Type: application/json" \
    -H "Authorization: Bearer $OPENAI_KEY" \
    -H "OpenAI-Organization: $OPENAI_ORG_ID" \
    -d "{
        \"model\": \"gpt-3.5-turbo\",
        \"messages\": [{\"role\": \"user\", \"content\": \"$prompt\"}],
        \"temperature\": 0.7
    }")
    echo $gpt | jq -r '.choices[0].message.content'
}

append_to_masterlist() {
  ml=~/Documents/Notes/todo/masterlist.txt
  echo "$1" >> "$ml"
  cat "$ml"
}

# Colors for ls - yellow directories
# export LS_COLORS="$LS_COLORS:di=1;33"
# Install Ruby Gems to ~/gems
export GEM_HOME="$HOME/gems"


# note() {
#   printf "%s\n" "$(date +"%Y-%m-%d: ") $1" >> notes.txt
# }

# log() {
#   printf "%s\n" "$(date +"%Y-%m-%d: ") $*" >> ~/Documents/Notes/Scratch/scratchpad.md
# }

log() {
  printf "%s\n" "$(date +"%Y-%m-%d %A: ") $*" >> ~/Documents/Notes/Scratch/scratchpad.txt
}

doo() {
  printf "%s\n" "- [ ] $*" >> ~/Documents/Notes/Scratch/scratchpad.txt
}

idea() {
  printf "%s\n" "IDEA: $*" >> ~/Documents/Notes/Scratch/scratchpad.txt
}

# Setting PATH
export PATH=~/bin/:$PATH
export PATH=~/.local/bin/:$PATH
export PATH=$PATH:/usr/local/go/bin
export PATH=$PATH:~/.local/share/JetBrains/Toolbox/scripts
export PATH=/var/lib/flatpak/exports/bin:$PATH

PATH="/home/lemon/perl5/bin${PATH:+:${PATH}}"; export PATH;
PERL5LIB="/home/lemon/perl5/lib/perl5${PERL5LIB:+:${PERL5LIB}}"; export PERL5LIB;
PERL_LOCAL_LIB_ROOT="/home/lemon/perl5${PERL_LOCAL_LIB_ROOT:+:${PERL_LOCAL_LIB_ROOT}}"; export PERL_LOCAL_LIB_ROOT;
PERL_MB_OPT="--install_base \"/home/lemon/perl5\""; export PERL_MB_OPT;
PERL_MM_OPT="INSTALL_BASE=/home/lemon/perl5"; export PERL_MM_OPT;
. "$HOME/.cargo/env"