Browse Source

moved confs

master
Robin Thoni 9 years ago
commit
7b72f2377e

+ 70
- 0
bash_aliases View File

@@ -0,0 +1,70 @@
1
+alias alert='notify-send --urgency=low -i "$([ $? = 0 ] && echo terminal || echo error)" "$(history|tail -n1|sed -e '\''s/^\s*[0-9]\+\s*//;s/[;&|]\s*alert$//'\'')"'
2
+
3
+alias cls="clear"
4
+alias nano="nano -K"
5
+alias l="/bin/ls --color"
6
+alias ll="/bin/ls --color -l"
7
+alias lla="/bin/ls --color -l -a"
8
+alias ls="/bin/ls -a --color"
9
+alias lock="i3lock"
10
+alias traceroute="traceroute -n"
11
+alias reload="source ~/.bashrc"
12
+alias wakeserv4="wakeonlan -i 192.168.1.255 00:1f:d0:db:d9:c8"
13
+alias shutserv4="ssh serv4 shutdown -h 0"
14
+alias shut="sudo shutdown -h 0"
15
+alias shutms="shutserv4 && shut"
16
+alias service="sudo service"
17
+alias ifconfig="sudo ifconfig"
18
+alias ip="sudo ip"
19
+alias killall="sudo killall"
20
+alias mount="sudo mount"
21
+alias umount="sudo umount"
22
+alias apt-get="sudo apt-get"
23
+alias apt-cache="sudo apt-cache"
24
+alias de="dhcp eth0"
25
+alias update-rc.d="sudo update-rc.d"
26
+alias status="git status"
27
+alias commit="git commit"
28
+alias push="git push"
29
+alias py="python"
30
+alias usbip="sudo usbip"
31
+alias modprobe="sudo modprobe"
32
+alias wifi="sudo rfkill unblock wifi;sudo service wicd start; wicd-curses"
33
+alias stopwifi="sudo service wicd stop; rfkill block wifi"
34
+alias wifite="sudo wifite -wept 10000 -wpst 10000"
35
+alias date="sudo date"
36
+alias route="sudo route"
37
+alias bashrc="vim ~/.bashrc; source ~/.bashrc"
38
+alias rc="vim ~/.bashrc; source ~/.bashrc"
39
+alias restart="shutdown -r 0"
40
+alias dd="sudo dd"
41
+alias ddstatus="sudo pkill --signal USR1 \"^dd$\""
42
+alias ddstatusc="while :; do ddstatus; sleep 2; done"
43
+alias reboot="sudo reboot"
44
+alias teamviewer="service teamviewerd start; teamviewer"
45
+alias stopteamviewer="service teamviewerd stop"
46
+alias mounts2="sudo mount /serv2"
47
+alias umounts2="sudo umount /serv2"
48
+alias mounts4="sudo mount /serv4"
49
+alias umounts4="sudo umount /serv4"
50
+alias cryptsetup="sudo cryptsetup"
51
+alias crypt="cryptsetup"
52
+alias arp-scan="sudo arp-scan"
53
+alias arpe="arp-scan -I eth0"
54
+alias arpw="arp-scan -I wlan0"
55
+alias ping="ping -n"
56
+alias vpnint="service openvpn restart g75-internet"
57
+alias vpnintstop="service openvpn stop g75-internet"
58
+alias vpnbe="service openvpn restart g75-betaclean"
59
+alias vpnbestop="service openvpn stop g75-betaclean"
60
+alias youtube-mp3="youtube-dl --extract-audio --audio-format mp3"
61
+alias pull="git pull --rebase"
62
+alias st="git status"
63
+alias m=make
64
+alias svim="sudo vim"
65
+alias 3d="sudo /etc/3DxWare/daemon/3dxsrv -d usb"
66
+alias u=up
67
+alias p="ping 8.8.8.8"
68
+alias pe="ping epigate.epimafia.fr"
69
+alias telnet='telnet -e ^['
70
+alias gparted="sudo gparted"

+ 204
- 0
bashrc View File

@@ -0,0 +1,204 @@
1
+# ~/.bashrc: executed by bash(1) for non-login shells.
2
+# see /usr/share/doc/bash/examples/startup-files (in the package bash-doc)
3
+# for examples
4
+
5
+# If not running interactively, don't do anything
6
+
7
+#if [ $(tty) = "/dev/tty1" ]
8
+#then
9
+#  startx
10
+#fi
11
+
12
+case $- in
13
+    *i*) ;;
14
+      *) return;;
15
+esac
16
+
17
+source ~/.git-prompt.sh
18
+
19
+# don't put duplicate lines or lines starting with space in the history.
20
+# See bash(1) for more options
21
+HISTCONTROL=ignoreboth
22
+
23
+# append to the history file, don't overwrite it
24
+shopt -s histappend
25
+
26
+# for setting history length see HISTSIZE and HISTFILESIZE in bash(1)
27
+HISTSIZE=1000
28
+HISTFILESIZE=2000
29
+
30
+# check the window size after each command and, if necessary,
31
+# update the values of LINES and COLUMNS.
32
+shopt -s checkwinsize
33
+
34
+# If set, the pattern "**" used in a pathname expansion context will
35
+# match all files and zero or more directories and subdirectories.
36
+#shopt -s globstar
37
+
38
+# make less more friendly for non-text input files, see lesspipe(1)
39
+[ -x /usr/bin/lesspipe ] && eval "$(SHELL=/bin/sh lesspipe)"
40
+
41
+# set variable identifying the chroot you work in (used in the prompt below)
42
+if [ -z "${debian_chroot:-}" ] && [ -r /etc/debian_chroot ]; then
43
+    debian_chroot=$(cat /etc/debian_chroot)
44
+fi
45
+
46
+# set a fancy prompt (non-color, unless we know we "want" color)
47
+case "$TERM" in
48
+    xterm-color) color_prompt=yes;;
49
+esac
50
+
51
+# uncomment for a colored prompt, if the terminal has the capability; turned
52
+# off by default to not distract the user: the focus in a terminal window
53
+# should be on the output of commands, not on the prompt
54
+force_color_prompt=yes
55
+
56
+if [ -n "$force_color_prompt" ]; then
57
+    if [ -x /usr/bin/tput ] && tput setaf 1 >&/dev/null; then
58
+	# We have color support; assume it's compliant with Ecma-48
59
+	# (ISO/IEC-6429). (Lack of such support is extremely rare, and such
60
+	# a case would tend to support setf rather than setaf.)
61
+	color_prompt=yes
62
+    else
63
+	color_prompt=
64
+    fi
65
+fi
66
+
67
+if [ "$color_prompt" = yes ]; then
68
+  PS1='\[\e[01;31m\]$(_ps1_exit_status)\[\e[0m\]${debian_chroot:+($debian_chroot)}\u@\h:'"\[\e[01;34m\]\w\[\e[0m\]\[\e[01;32m\]"'$(__git_ps1 " [%s]")'"\[\e[0m\]\$ "
69
+else
70
+  PS1='$?${debian_chroot:+($debian_chroot)}\u@\h:\w$(__git_ps1)\$ '
71
+fi
72
+unset color_prompt force_color_prompt
73
+
74
+# If this is an xterm set the title to user@host:dir
75
+case "$TERM" in
76
+xterm*|rxvt*)
77
+    PS1="\[\e]0;${debian_chroot:+($debian_chroot)}\u@\h: \w\a\]$PS1"
78
+    ;;
79
+*)
80
+    ;;
81
+esac
82
+
83
+# enable color support of ls and also add handy aliases
84
+if [ -x /usr/bin/dircolors ]; then
85
+    test -r ~/.dircolors && eval "$(dircolors -b ~/.dircolors)" || eval "$(dircolors -b)"
86
+    alias ls='ls --color=auto'
87
+    #alias dir='dir --color=auto'
88
+    #alias vdir='vdir --color=auto'
89
+
90
+    alias grep='grep --color=auto'
91
+    alias fgrep='fgrep --color=auto'
92
+    alias egrep='egrep --color=auto'
93
+fi
94
+
95
+# some more ls aliases
96
+alias ll='ls -alF'
97
+alias la='ls -A'
98
+alias l='ls -CF'
99
+
100
+# Add an "alert" alias for long running commands.  Use like so:
101
+#   sleep 10; alert
102
+
103
+# Alias definitions.
104
+# You may want to put all your additions into a separate file like
105
+# ~/.bash_aliases, instead of adding them here directly.
106
+# See /usr/share/doc/bash-doc/examples in the bash-doc package.
107
+
108
+if [ -f ~/.bash_aliases ]; then
109
+    . ~/.bash_aliases
110
+fi
111
+
112
+# enable programmable completion features (you don't need to enable
113
+# this, if it's already enabled in /etc/bash.bashrc and /etc/profile
114
+# sources /etc/bash.bashrc).
115
+if ! shopt -oq posix; then
116
+  if [ -f /usr/share/bash-completion/bash_completion ]; then
117
+    . /usr/share/bash-completion/bash_completion
118
+  elif [ -f /etc/bash_completion ]; then
119
+    . /etc/bash_completion
120
+  fi
121
+fi
122
+export PATH="$PATH:/sbin:/usr/sbin/:/usr/local/bin/android-studio/bin/:/home/robin/Android/Sdk/platform-tools/:/usr/local/bin/intellij/bin/"
123
+
124
+reg_ip='([0-9]{1,3}\.){3}[0-9]{1,3}'
125
+reg_mac='([0-9a-f]{2}:){5}[0-9a-f]{2}'
126
+
127
+_ps1_exit_status()
128
+{
129
+  status=$?
130
+  if [ ${status} -ne 0 ]
131
+  then
132
+    echo "${status} "
133
+  fi
134
+}
135
+
136
+proj()
137
+{
138
+    if [ $# -eq 0 ]
139
+    then
140
+        cd ~/projets
141
+        ls
142
+    elif [ $# -ge 1 ]
143
+    then
144
+        cd ~/projets/*-$1
145
+        if [ $# -ge 2 ]
146
+        then
147
+            cd $2
148
+        fi
149
+    fi
150
+}
151
+
152
+_proj_completion()
153
+{
154
+
155
+    cur=${COMP_WORDS[COMP_CWORD]}
156
+    if [ $COMP_CWORD -eq 1 ]
157
+    then
158
+        COMPREPLY=($(compgen -W "$(/bin/ls -d ~/projets/* | /usr/bin/env grep -oP "\-\K(.*)")" "$cur"))
159
+    elif [ $COMP_CWORD -eq 2 ]
160
+    then
161
+        p=${COMP_WORDS[COMP_CWORD-1]}
162
+        COMPREPLY=($(compgen -W "$(/bin/ls -d ~/projets/*${p}/* | /usr/bin/env grep -oP "\K[^/]+$")" "$cur"))
163
+    else
164
+        COMPREPLY=()
165
+    fi
166
+}
167
+
168
+dhcp()
169
+{
170
+    if [ $# -eq 0 ]
171
+    then
172
+        echo "Usage: $0 interface [args]" >&2
173
+    else
174
+        iface="$1"
175
+        shift
176
+        sudo ifconfig ${iface} up; sudo dhclient -pf /var/run/dhclient.${iface}.pid ${iface} $@
177
+    fi
178
+}
179
+
180
+up()
181
+{
182
+  if [ $# -eq 0 ]
183
+  then
184
+    cd ..
185
+  else
186
+    if echo "$1" | grep -E "[0-9]+" 1>/dev/null 2>/dev/null
187
+    then
188
+      i=$1
189
+      while [ $i -gt 0 ]
190
+      do
191
+        cd ..
192
+        i=$(($i - 1))
193
+      done
194
+    else
195
+      echo "Usage: $0 count" >&2
196
+      echo "count: number of directory to up" >&2
197
+    fi
198
+  fi
199
+}
200
+
201
+complete -F _proj_completion proj
202
+export NNTPSERVER=news.epita.fr
203
+
204
+. ~/.bash_aliases

+ 484
- 0
git-prompt.sh View File

@@ -0,0 +1,484 @@
1
+# bash/zsh git prompt support
2
+#
3
+# Copyright (C) 2006,2007 Shawn O. Pearce <spearce@spearce.org>
4
+# Distributed under the GNU General Public License, version 2.0.
5
+#
6
+# This script allows you to see repository status in your prompt.
7
+#
8
+# To enable:
9
+#
10
+#    1) Copy this file to somewhere (e.g. ~/.git-prompt.sh).
11
+#    2) Add the following line to your .bashrc/.zshrc:
12
+#        source ~/.git-prompt.sh
13
+#    3a) Change your PS1 to call __git_ps1 as
14
+#        command-substitution:
15
+#        Bash: PS1='[\u@\h \W$(__git_ps1 " (%s)")]\$ '
16
+#        ZSH:  setopt PROMPT_SUBST ; PS1='[%n@%m %c$(__git_ps1 " (%s)")]\$ '
17
+#        the optional argument will be used as format string.
18
+#    3b) Alternatively, for a slightly faster prompt, __git_ps1 can
19
+#        be used for PROMPT_COMMAND in Bash or for precmd() in Zsh
20
+#        with two parameters, <pre> and <post>, which are strings
21
+#        you would put in $PS1 before and after the status string
22
+#        generated by the git-prompt machinery.  e.g.
23
+#        Bash: PROMPT_COMMAND='__git_ps1 "\u@\h:\w" "\\\$ "'
24
+#          will show username, at-sign, host, colon, cwd, then
25
+#          various status string, followed by dollar and SP, as
26
+#          your prompt.
27
+#        ZSH:  precmd () { __git_ps1 "%n" ":%~$ " "|%s" }
28
+#          will show username, pipe, then various status string,
29
+#          followed by colon, cwd, dollar and SP, as your prompt.
30
+#        Optionally, you can supply a third argument with a printf
31
+#        format string to finetune the output of the branch status
32
+#
33
+# The repository status will be displayed only if you are currently in a
34
+# git repository. The %s token is the placeholder for the shown status.
35
+#
36
+# The prompt status always includes the current branch name.
37
+#
38
+# In addition, if you set GIT_PS1_SHOWDIRTYSTATE to a nonempty value,
39
+# unstaged (*) and staged (+) changes will be shown next to the branch
40
+# name.  You can configure this per-repository with the
41
+# bash.showDirtyState variable, which defaults to true once
42
+# GIT_PS1_SHOWDIRTYSTATE is enabled.
43
+#
44
+# You can also see if currently something is stashed, by setting
45
+# GIT_PS1_SHOWSTASHSTATE to a nonempty value. If something is stashed,
46
+# then a '$' will be shown next to the branch name.
47
+#
48
+# If you would like to see if there're untracked files, then you can set
49
+# GIT_PS1_SHOWUNTRACKEDFILES to a nonempty value. If there're untracked
50
+# files, then a '%' will be shown next to the branch name.  You can
51
+# configure this per-repository with the bash.showUntrackedFiles
52
+# variable, which defaults to true once GIT_PS1_SHOWUNTRACKEDFILES is
53
+# enabled.
54
+#
55
+# If you would like to see the difference between HEAD and its upstream,
56
+# set GIT_PS1_SHOWUPSTREAM="auto".  A "<" indicates you are behind, ">"
57
+# indicates you are ahead, "<>" indicates you have diverged and "="
58
+# indicates that there is no difference. You can further control
59
+# behaviour by setting GIT_PS1_SHOWUPSTREAM to a space-separated list
60
+# of values:
61
+#
62
+#     verbose       show number of commits ahead/behind (+/-) upstream
63
+#     name          if verbose, then also show the upstream abbrev name
64
+#     legacy        don't use the '--count' option available in recent
65
+#                   versions of git-rev-list
66
+#     git           always compare HEAD to @{upstream}
67
+#     svn           always compare HEAD to your SVN upstream
68
+#
69
+# By default, __git_ps1 will compare HEAD to your SVN upstream if it can
70
+# find one, or @{upstream} otherwise.  Once you have set
71
+# GIT_PS1_SHOWUPSTREAM, you can override it on a per-repository basis by
72
+# setting the bash.showUpstream config variable.
73
+#
74
+# If you would like to see more information about the identity of
75
+# commits checked out as a detached HEAD, set GIT_PS1_DESCRIBE_STYLE
76
+# to one of these values:
77
+#
78
+#     contains      relative to newer annotated tag (v1.6.3.2~35)
79
+#     branch        relative to newer tag or branch (master~4)
80
+#     describe      relative to older annotated tag (v1.6.3.1-13-gdd42c2f)
81
+#     default       exactly matching tag
82
+#
83
+# If you would like a colored hint about the current dirty state, set
84
+# GIT_PS1_SHOWCOLORHINTS to a nonempty value. The colors are based on
85
+# the colored output of "git status -sb" and are available only when
86
+# using __git_ps1 for PROMPT_COMMAND or precmd.
87
+
88
+# check whether printf supports -v
89
+__git_printf_supports_v=
90
+printf -v __git_printf_supports_v -- '%s' yes >/dev/null 2>&1
91
+
92
+# stores the divergence from upstream in $p
93
+# used by GIT_PS1_SHOWUPSTREAM
94
+__git_ps1_show_upstream ()
95
+{
96
+	local key value
97
+	local svn_remote svn_url_pattern count n
98
+	local upstream=git legacy="" verbose="" name=""
99
+
100
+	svn_remote=()
101
+	# get some config options from git-config
102
+	local output="$(git config -z --get-regexp '^(svn-remote\..*\.url|bash\.showupstream)$' 2>/dev/null | tr '\0\n' '\n ')"
103
+	while read -r key value; do
104
+		case "$key" in
105
+		bash.showupstream)
106
+			GIT_PS1_SHOWUPSTREAM="$value"
107
+			if [[ -z "${GIT_PS1_SHOWUPSTREAM}" ]]; then
108
+				p=""
109
+				return
110
+			fi
111
+			;;
112
+		svn-remote.*.url)
113
+			svn_remote[$((${#svn_remote[@]} + 1))]="$value"
114
+			svn_url_pattern="$svn_url_pattern\\|$value"
115
+			upstream=svn+git # default upstream is SVN if available, else git
116
+			;;
117
+		esac
118
+	done <<< "$output"
119
+
120
+	# parse configuration values
121
+	for option in ${GIT_PS1_SHOWUPSTREAM}; do
122
+		case "$option" in
123
+		git|svn) upstream="$option" ;;
124
+		verbose) verbose=1 ;;
125
+		legacy)  legacy=1  ;;
126
+		name)    name=1 ;;
127
+		esac
128
+	done
129
+
130
+	# Find our upstream
131
+	case "$upstream" in
132
+	git)    upstream="@{upstream}" ;;
133
+	svn*)
134
+		# get the upstream from the "git-svn-id: ..." in a commit message
135
+		# (git-svn uses essentially the same procedure internally)
136
+		local -a svn_upstream
137
+		svn_upstream=($(git log --first-parent -1 \
138
+					--grep="^git-svn-id: \(${svn_url_pattern#??}\)" 2>/dev/null))
139
+		if [[ 0 -ne ${#svn_upstream[@]} ]]; then
140
+			svn_upstream=${svn_upstream[${#svn_upstream[@]} - 2]}
141
+			svn_upstream=${svn_upstream%@*}
142
+			local n_stop="${#svn_remote[@]}"
143
+			for ((n=1; n <= n_stop; n++)); do
144
+				svn_upstream=${svn_upstream#${svn_remote[$n]}}
145
+			done
146
+
147
+			if [[ -z "$svn_upstream" ]]; then
148
+				# default branch name for checkouts with no layout:
149
+				upstream=${GIT_SVN_ID:-git-svn}
150
+			else
151
+				upstream=${svn_upstream#/}
152
+			fi
153
+		elif [[ "svn+git" = "$upstream" ]]; then
154
+			upstream="@{upstream}"
155
+		fi
156
+		;;
157
+	esac
158
+
159
+	# Find how many commits we are ahead/behind our upstream
160
+	if [[ -z "$legacy" ]]; then
161
+		count="$(git rev-list --count --left-right \
162
+				"$upstream"...HEAD 2>/dev/null)"
163
+	else
164
+		# produce equivalent output to --count for older versions of git
165
+		local commits
166
+		if commits="$(git rev-list --left-right "$upstream"...HEAD 2>/dev/null)"
167
+		then
168
+			local commit behind=0 ahead=0
169
+			for commit in $commits
170
+			do
171
+				case "$commit" in
172
+				"<"*) ((behind++)) ;;
173
+				*)    ((ahead++))  ;;
174
+				esac
175
+			done
176
+			count="$behind	$ahead"
177
+		else
178
+			count=""
179
+		fi
180
+	fi
181
+
182
+	# calculate the result
183
+	if [[ -z "$verbose" ]]; then
184
+		case "$count" in
185
+		"") # no upstream
186
+			p="" ;;
187
+		"0	0") # equal to upstream
188
+			p="=" ;;
189
+		"0	"*) # ahead of upstream
190
+			p=">" ;;
191
+		*"	0") # behind upstream
192
+			p="<" ;;
193
+		*)	    # diverged from upstream
194
+			p="<>" ;;
195
+		esac
196
+	else
197
+		case "$count" in
198
+		"") # no upstream
199
+			p="" ;;
200
+		"0	0") # equal to upstream
201
+			p=" u=" ;;
202
+		"0	"*) # ahead of upstream
203
+			p=" u+${count#0	}" ;;
204
+		*"	0") # behind upstream
205
+			p=" u-${count%	0}" ;;
206
+		*)	    # diverged from upstream
207
+			p=" u+${count#*	}-${count%	*}" ;;
208
+		esac
209
+		if [[ -n "$count" && -n "$name" ]]; then
210
+			__git_ps1_upstream_name=$(git rev-parse \
211
+				--abbrev-ref "$upstream" 2>/dev/null)
212
+			if [ $pcmode = yes ]; then
213
+				# see the comments around the
214
+				# __git_ps1_branch_name variable below
215
+				p="$p \${__git_ps1_upstream_name}"
216
+			else
217
+				p="$p ${__git_ps1_upstream_name}"
218
+				# not needed anymore; keep user's
219
+				# environment clean
220
+				unset __git_ps1_upstream_name
221
+			fi
222
+		fi
223
+	fi
224
+
225
+}
226
+
227
+# Helper function that is meant to be called from __git_ps1.  It
228
+# injects color codes into the appropriate gitstring variables used
229
+# to build a gitstring.
230
+__git_ps1_colorize_gitstring ()
231
+{
232
+	if [[ -n ${ZSH_VERSION-} ]]; then
233
+		local c_red='%F{red}'
234
+		local c_green='%F{green}'
235
+		local c_lblue='%F{blue}'
236
+		local c_clear='%f'
237
+	else
238
+		# Using \[ and \] around colors is necessary to prevent
239
+		# issues with command line editing/browsing/completion!
240
+		local c_red='\[\e[31m\]'
241
+		local c_green='\[\e[32m\]'
242
+		local c_lblue='\[\e[1;34m\]'
243
+		local c_clear='\[\e[0m\]'
244
+	fi
245
+	local bad_color=$c_red
246
+	local ok_color=$c_green
247
+	local flags_color="$c_lblue"
248
+
249
+	local branch_color=""
250
+	if [ $detached = no ]; then
251
+		branch_color="$ok_color"
252
+	else
253
+		branch_color="$bad_color"
254
+	fi
255
+	c="$branch_color$c"
256
+
257
+	z="$c_clear$z"
258
+	if [ "$w" = "*" ]; then
259
+		w="$bad_color$w"
260
+	fi
261
+	if [ -n "$i" ]; then
262
+		i="$ok_color$i"
263
+	fi
264
+	if [ -n "$s" ]; then
265
+		s="$flags_color$s"
266
+	fi
267
+	if [ -n "$u" ]; then
268
+		u="$bad_color$u"
269
+	fi
270
+	r="$c_clear$r"
271
+}
272
+
273
+# __git_ps1 accepts 0 or 1 arguments (i.e., format string)
274
+# when called from PS1 using command substitution
275
+# in this mode it prints text to add to bash PS1 prompt (includes branch name)
276
+#
277
+# __git_ps1 requires 2 or 3 arguments when called from PROMPT_COMMAND (pc)
278
+# in that case it _sets_ PS1. The arguments are parts of a PS1 string.
279
+# when two arguments are given, the first is prepended and the second appended
280
+# to the state string when assigned to PS1.
281
+# The optional third parameter will be used as printf format string to further
282
+# customize the output of the git-status string.
283
+# In this mode you can request colored hints using GIT_PS1_SHOWCOLORHINTS=true
284
+__git_ps1 ()
285
+{
286
+	local pcmode=no
287
+	local detached=no
288
+	local ps1pc_start='\u@\h:\w '
289
+	local ps1pc_end='\$ '
290
+	local printf_format=' (%s)'
291
+
292
+	case "$#" in
293
+		2|3)	pcmode=yes
294
+			ps1pc_start="$1"
295
+			ps1pc_end="$2"
296
+			printf_format="${3:-$printf_format}"
297
+		;;
298
+		0|1)	printf_format="${1:-$printf_format}"
299
+		;;
300
+		*)	return
301
+		;;
302
+	esac
303
+
304
+	local repo_info rev_parse_exit_code
305
+	repo_info="$(git rev-parse --git-dir --is-inside-git-dir \
306
+		--is-bare-repository --is-inside-work-tree \
307
+		--short HEAD 2>/dev/null)"
308
+	rev_parse_exit_code="$?"
309
+
310
+	if [ -z "$repo_info" ]; then
311
+		if [ $pcmode = yes ]; then
312
+			#In PC mode PS1 always needs to be set
313
+			PS1="$ps1pc_start$ps1pc_end"
314
+		fi
315
+		return
316
+	fi
317
+
318
+	local short_sha
319
+	if [ "$rev_parse_exit_code" = "0" ]; then
320
+		short_sha="${repo_info##*$'\n'}"
321
+		repo_info="${repo_info%$'\n'*}"
322
+	fi
323
+	local inside_worktree="${repo_info##*$'\n'}"
324
+	repo_info="${repo_info%$'\n'*}"
325
+	local bare_repo="${repo_info##*$'\n'}"
326
+	repo_info="${repo_info%$'\n'*}"
327
+	local inside_gitdir="${repo_info##*$'\n'}"
328
+	local g="${repo_info%$'\n'*}"
329
+
330
+	local r=""
331
+	local b=""
332
+	local step=""
333
+	local total=""
334
+	if [ -d "$g/rebase-merge" ]; then
335
+		read b 2>/dev/null <"$g/rebase-merge/head-name"
336
+		read step 2>/dev/null <"$g/rebase-merge/msgnum"
337
+		read total 2>/dev/null <"$g/rebase-merge/end"
338
+		if [ -f "$g/rebase-merge/interactive" ]; then
339
+			r="|REBASE-i"
340
+		else
341
+			r="|REBASE-m"
342
+		fi
343
+	else
344
+		if [ -d "$g/rebase-apply" ]; then
345
+			read step 2>/dev/null <"$g/rebase-apply/next"
346
+			read total 2>/dev/null <"$g/rebase-apply/last"
347
+			if [ -f "$g/rebase-apply/rebasing" ]; then
348
+				read b 2>/dev/null <"$g/rebase-apply/head-name"
349
+				r="|REBASE"
350
+			elif [ -f "$g/rebase-apply/applying" ]; then
351
+				r="|AM"
352
+			else
353
+				r="|AM/REBASE"
354
+			fi
355
+		elif [ -f "$g/MERGE_HEAD" ]; then
356
+			r="|MERGING"
357
+		elif [ -f "$g/CHERRY_PICK_HEAD" ]; then
358
+			r="|CHERRY-PICKING"
359
+		elif [ -f "$g/REVERT_HEAD" ]; then
360
+			r="|REVERTING"
361
+		elif [ -f "$g/BISECT_LOG" ]; then
362
+			r="|BISECTING"
363
+		fi
364
+
365
+		if [ -n "$b" ]; then
366
+			:
367
+		elif [ -h "$g/HEAD" ]; then
368
+			# symlink symbolic ref
369
+			b="$(git symbolic-ref HEAD 2>/dev/null)"
370
+		else
371
+			local head=""
372
+			if ! read head 2>/dev/null <"$g/HEAD"; then
373
+				if [ $pcmode = yes ]; then
374
+					PS1="$ps1pc_start$ps1pc_end"
375
+				fi
376
+				return
377
+			fi
378
+			# is it a symbolic ref?
379
+			b="${head#ref: }"
380
+			if [ "$head" = "$b" ]; then
381
+				detached=yes
382
+				b="$(
383
+				case "${GIT_PS1_DESCRIBE_STYLE-}" in
384
+				(contains)
385
+					git describe --contains HEAD ;;
386
+				(branch)
387
+					git describe --contains --all HEAD ;;
388
+				(describe)
389
+					git describe HEAD ;;
390
+				(* | default)
391
+					git describe --tags --exact-match HEAD ;;
392
+				esac 2>/dev/null)" ||
393
+
394
+				b="$short_sha..."
395
+				b="($b)"
396
+			fi
397
+		fi
398
+	fi
399
+
400
+	if [ -n "$step" ] && [ -n "$total" ]; then
401
+		r="$r $step/$total"
402
+	fi
403
+
404
+	local w=""
405
+	local i=""
406
+	local s=""
407
+	local u=""
408
+	local c=""
409
+	local p=""
410
+
411
+	if [ "true" = "$inside_gitdir" ]; then
412
+		if [ "true" = "$bare_repo" ]; then
413
+			c="BARE:"
414
+		else
415
+			b="GIT_DIR!"
416
+		fi
417
+	elif [ "true" = "$inside_worktree" ]; then
418
+		if [ -n "${GIT_PS1_SHOWDIRTYSTATE-}" ] &&
419
+		   [ "$(git config --bool bash.showDirtyState)" != "false" ]
420
+		then
421
+			git diff --no-ext-diff --quiet --exit-code || w="*"
422
+			if [ -n "$short_sha" ]; then
423
+				git diff-index --cached --quiet HEAD -- || i="+"
424
+			else
425
+				i="#"
426
+			fi
427
+		fi
428
+		if [ -n "${GIT_PS1_SHOWSTASHSTATE-}" ] &&
429
+		   [ -r "$g/refs/stash" ]; then
430
+			s="$"
431
+		fi
432
+
433
+		if [ -n "${GIT_PS1_SHOWUNTRACKEDFILES-}" ] &&
434
+		   [ "$(git config --bool bash.showUntrackedFiles)" != "false" ] &&
435
+		   git ls-files --others --exclude-standard --error-unmatch -- '*' >/dev/null 2>/dev/null
436
+		then
437
+			u="%${ZSH_VERSION+%}"
438
+		fi
439
+
440
+		if [ -n "${GIT_PS1_SHOWUPSTREAM-}" ]; then
441
+			__git_ps1_show_upstream
442
+		fi
443
+	fi
444
+
445
+	local z="${GIT_PS1_STATESEPARATOR-" "}"
446
+
447
+	# NO color option unless in PROMPT_COMMAND mode
448
+	if [ $pcmode = yes ] && [ -n "${GIT_PS1_SHOWCOLORHINTS-}" ]; then
449
+		__git_ps1_colorize_gitstring
450
+	fi
451
+
452
+	b=${b##refs/heads/}
453
+	if [ $pcmode = yes ]; then
454
+		# In pcmode (and only pcmode) the contents of
455
+		# $gitstring are subject to expansion by the shell.
456
+		# Avoid putting the raw ref name in the prompt to
457
+		# protect the user from arbitrary code execution via
458
+		# specially crafted ref names (e.g., a ref named
459
+		# '$(IFS=_;cmd=sudo_rm_-rf_/;$cmd)' would execute
460
+		# 'sudo rm -rf /' when the prompt is drawn).  Instead,
461
+		# put the ref name in a new global variable (in the
462
+		# __git_ps1_* namespace to avoid colliding with the
463
+		# user's environment) and reference that variable from
464
+		# PS1.
465
+		__git_ps1_branch_name=$b
466
+		# note that the $ is escaped -- the variable will be
467
+		# expanded later (when it's time to draw the prompt)
468
+		b="\${__git_ps1_branch_name}"
469
+	fi
470
+
471
+	local f="$w$i$s$u"
472
+	local gitstring="$c$b${f:+$z$f}$r$p"
473
+
474
+	if [ $pcmode = yes ]; then
475
+		if [ "${__git_printf_supports_v-}" != yes ]; then
476
+			gitstring=$(printf -- "$printf_format" "$gitstring")
477
+		else
478
+			printf -v gitstring -- "$printf_format" "$gitstring"
479
+		fi
480
+		PS1="$ps1pc_start$gitstring$ps1pc_end"
481
+	else
482
+		printf -- "$printf_format" "$gitstring"
483
+	fi
484
+}

+ 163
- 0
i3/config View File

@@ -0,0 +1,163 @@
1
+# This file has been auto-generated by i3-config-wizard(1).
2
+# It will not be overwritten, so edit it as you like.
3
+#
4
+# Should you change your keyboard layout somewhen, delete
5
+# this file and re-run i3-config-wizard(1).
6
+#
7
+
8
+# i3 config file (v4)
9
+#
10
+# Please see http://i3wm.org/docs/userguide.html for a complete reference!
11
+
12
+set $mod Mod4
13
+
14
+# Font for window titles. Will also be used by the bar unless a different font
15
+# is used in the bar {} block below. ISO 10646 = Unicode
16
+font -misc-fixed-medium-r-normal--13-120-75-75-C-70-iso10646-1
17
+# The font above is very space-efficient, that is, it looks good, sharp and
18
+# clear in small sizes. However, if you need a lot of unicode glyphs or
19
+# right-to-left text rendering, you should instead use pango for rendering and
20
+# chose a FreeType font, such as:
21
+# font pango:DejaVu Sans Mono 10
22
+
23
+# Use Mouse+$mod to drag floating windows to their wanted position
24
+floating_modifier $mod
25
+
26
+# start a terminal
27
+bindsym $mod+Return exec i3-sensible-terminal
28
+
29
+# kill focused window
30
+bindsym $mod+q kill
31
+
32
+# start dmenu (a program launcher)
33
+bindsym $mod+d exec dmenu_alias
34
+# There also is the (new) i3-dmenu-desktop which only displays applications
35
+# shipping a .desktop file. It is a wrapper around dmenu, so you need that
36
+# installed.
37
+# bindsym $mod+d exec --no-startup-id i3-dmenu-desktop
38
+
39
+# alternatively, you can use the cursor keys:
40
+bindsym $mod+Left focus left
41
+bindsym $mod+Down focus down
42
+bindsym $mod+Up focus up
43
+bindsym $mod+Right focus right
44
+
45
+# move focused window
46
+bindsym $mod+Shift+j move left
47
+bindsym $mod+Shift+k move down
48
+bindsym $mod+Shift+l move up
49
+bindsym $mod+Shift+colon move right
50
+
51
+# alternatively, you can use the cursor keys:
52
+bindsym $mod+Shift+Left move left
53
+bindsym $mod+Shift+Down move down
54
+bindsym $mod+Shift+Up move up
55
+bindsym $mod+Shift+Right move right
56
+
57
+# split in horizontal orientation
58
+bindsym $mod+h split h
59
+
60
+# split in vertical orientation
61
+bindsym $mod+v split v
62
+
63
+# enter fullscreen mode for the focused container
64
+bindsym $mod+f fullscreen
65
+
66
+# change container layout (stacked, tabbed, toggle split)
67
+bindsym $mod+s layout stacking
68
+bindsym $mod+w layout tabbed
69
+bindsym $mod+e layout toggle split
70
+
71
+# toggle tiling / floating
72
+bindsym $mod+Shift+space floating toggle
73
+
74
+# change focus between tiling / floating windows
75
+bindsym $mod+space focus mode_toggle
76
+
77
+# focus the parent container
78
+bindsym $mod+a focus parent
79
+
80
+# focus the child container
81
+#bindsym $mod+d focus child
82
+
83
+# switch to workspace
84
+bindsym $mod+1 workspace 1
85
+bindsym $mod+2 workspace 2
86
+bindsym $mod+3 workspace 3
87
+bindsym $mod+4 workspace 4
88
+bindsym $mod+5 workspace 5
89
+bindsym $mod+6 workspace 6
90
+bindsym $mod+7 workspace 7
91
+bindsym $mod+8 workspace 8
92
+bindsym $mod+9 workspace 9
93
+bindsym $mod+0 workspace 10
94
+
95
+# move focused container to workspace
96
+bindsym $mod+Shift+1 move container to workspace 1
97
+bindsym $mod+Shift+2 move container to workspace 2
98
+bindsym $mod+Shift+3 move container to workspace 3
99
+bindsym $mod+Shift+4 move container to workspace 4
100
+bindsym $mod+Shift+5 move container to workspace 5
101
+bindsym $mod+Shift+6 move container to workspace 6
102
+bindsym $mod+Shift+7 move container to workspace 7
103
+bindsym $mod+Shift+8 move container to workspace 8
104
+bindsym $mod+Shift+9 move container to workspace 9
105
+bindsym $mod+Shift+0 move container to workspace 10
106
+
107
+# reload the configuration file
108
+bindsym $mod+Shift+c reload
109
+# restart i3 inplace (preserves your layout/session, can be used to upgrade i3)
110
+bindsym $mod+Shift+r restart
111
+# exit i3 (logs you out of your X session)
112
+bindsym $mod+Shift+e exit
113
+
114
+# resize window (you can also use the mouse for that)
115
+mode "resize" {
116
+        # These bindings trigger as soon as you enter the resize mode
117
+
118
+        # Pressing left will shrink the window’s width.
119
+        # Pressing right will grow the window’s width.
120
+        # Pressing up will shrink the window’s height.
121
+        # Pressing down will grow the window’s height.
122
+        bindsym j resize shrink width 10 px or 10 ppt
123
+        bindsym k resize grow height 10 px or 10 ppt
124
+        bindsym l resize shrink height 10 px or 10 ppt
125
+        bindsym semicolon resize grow width 10 px or 10 ppt
126
+
127
+        # same bindings, but for the arrow keys
128
+        bindsym Left resize shrink width 10 px or 10 ppt
129
+        bindsym Down resize grow height 10 px or 10 ppt
130
+        bindsym Up resize shrink height 10 px or 10 ppt
131
+        bindsym Right resize grow width 10 px or 10 ppt
132
+
133
+        # back to normal: Enter or Escape
134
+        bindsym Return mode "default"
135
+        bindsym Escape mode "default"
136
+}
137
+
138
+bindsym $mod+r mode "resize"
139
+
140
+# Start i3bar to display a workspace bar (plus the system information i3status
141
+# finds out, if available)
142
+bar {
143
+#        status_command i3status
144
+        font      pango:Terminus, Icons, FontAwesome 9
145
+        status_command python3 ~/.i3/status/status.py
146
+        tray_output primary
147
+}
148
+
149
+exec_always ~/.i3/exec
150
+
151
+bindsym Print exec screen.sh root
152
+bindsym $mod+Print exec screen.sh active
153
+bindsym $mod+l exec i3lock -c 000000
154
+
155
+bindsym $mod+o exec sudo service openvpn restart
156
+bindsym $mod+i exec sudo service openvpn restart g75-internet
157
+bindsym $mod+n exec netsoul
158
+bindsym $mod+c exec chromium-browser
159
+
160
+bindsym $mod+p exec wakeserv4-alert.sh
161
+
162
+workspace 6 output VGA-0
163
+workspace 1 output DP-2

+ 4
- 0
i3/exec View File

@@ -0,0 +1,4 @@
1
+#! /usr/bin/env sh
2
+
3
+gnome-settings-daemon &
4
+numlockx on

+ 81
- 0
i3/status/i3status.conf View File

@@ -0,0 +1,81 @@
1
+general {
2
+    colors = true
3
+    interval = 1
4
+    output_format = "i3bar"
5
+}
6
+
7
+## order += "ipv6"
8
+order += "disk /"
9
+order += "disk /home"
10
+order += "run_watch AirVPN"
11
+order += "run_watch gate"
12
+order += "ethernet enp4s0f2"
13
+order += "wireless wlp3s0"
14
+order += "wireless wlp0s20u2"
15
+#order += "load"
16
+order += "battery 0"
17
+order += "cpu_temperature 0"
18
+order += "volume master"
19
+order += "time"
20
+
21
+ethernet enp4s0f2 {
22
+    # if you use %speed, i3status requires root privileges
23
+    format_up = "E: %ip (%speed)"
24
+    format_down = ""
25
+}
26
+
27
+wireless wlp3s0 {
28
+    # if you use %speed, i3status requires root privileges
29
+    format_up = "W: (%essid) %ip"
30
+    format_down = ""
31
+}
32
+
33
+wireless wlp0s20u2 {
34
+    # if you use %speed, i3status requires root privileges
35
+    format_up = " (%essid) %ip"
36
+    format_down = ""
37
+}
38
+
39
+run_watch DHCP {
40
+    pidfile = "/var/run/dhclient*.pid"
41
+}
42
+
43
+run_watch AirVPN {
44
+    pidfile = "/run/airvpn.pid"
45
+}
46
+
47
+run_watch gate {
48
+    pidfile = "/run/openvpn@epigate.pid"
49
+}
50
+
51
+time {
52
+    format = "%a %d/%m/%Y  %H:%M:%S"
53
+}
54
+
55
+load {
56
+    format = "%1min"
57
+}
58
+
59
+cpu_temperature 0 {
60
+    format = "T: %degrees °C"
61
+    path = "/sys/devices/virtual/thermal/thermal_zone1/temp"
62
+}
63
+
64
+battery 0 {
65
+    format = "%status %percentage %remaining"
66
+    path="/sys/class/power_supply/BAT0/uevent"
67
+}
68
+
69
+disk "/" {
70
+    format = "/ %avail"
71
+}
72
+
73
+disk "/home" {
74
+    format = "/home %avail"
75
+}
76
+
77
+volume master {
78
+    format = "♪: %volume"
79
+    device = "default"
80
+    mixer = "Master"
81
+}

+ 0
- 0
i3/status/i3status/__init__.py View File


BIN
i3/status/i3status/__pycache__/__init__.cpython-34.pyc View File


BIN
i3/status/i3status/__pycache__/arch_updates.cpython-34.pyc View File


BIN
i3/status/i3status/__pycache__/change_i3pystatus.cpython-34.pyc View File


BIN
i3/status/i3status/__pycache__/my_ip.cpython-34.pyc View File


BIN
i3/status/i3status/__pycache__/network_traffic.cpython-34.pyc View File


BIN
i3/status/i3status/__pycache__/ping.cpython-34.pyc View File


BIN
i3/status/i3status/__pycache__/upower.cpython-34.pyc View File


+ 48
- 0
i3/status/i3status/arch_updates.py View File

@@ -0,0 +1,48 @@
1
+import subprocess
2
+from i3pystatus import IntervalModule, formatp
3
+
4
+
5
+class ArchUpdates(IntervalModule):
6
+
7
+    settings = (
8
+        "format",
9
+        "format_down",
10
+        "color",
11
+    )
12
+
13
+    interval = 60
14
+    format = "Update count: {count_pacman} {count_yaourt}"
15
+    format_down = ""
16
+    color = "#FFFFFF"
17
+
18
+    # clicking on it after installing updates will dismiss the notification
19
+    on_leftclick = "run"
20
+
21
+    def run(self):
22
+        # We updates the db
23
+        command = ["sudo", "yaourt", "-Sya"]
24
+        subprocess.Popen(command, stdout=subprocess.PIPE,
25
+                         stderr=subprocess.DEVNULL)
26
+
27
+        count_pacman = self.get_count(["yaourt", "-Qu"])
28
+        count_yaourt = self.get_count(["yaourt", "-Qua"])
29
+
30
+        format = self.format if count_yaourt else self.format_down
31
+        count_yaourt -= count_pacman
32
+
33
+        fdict = {
34
+            "count_pacman": count_pacman,
35
+            "count_yaourt": count_yaourt,
36
+        }
37
+
38
+        self.output = {
39
+            "full_text": formatp(format, **fdict).strip(),
40
+            "color": self.color,
41
+        }
42
+        return
43
+
44
+    def get_count(self, command):
45
+        check_pacman = subprocess.Popen(command, stdout=subprocess.PIPE,
46
+                                        stderr=subprocess.DEVNULL)
47
+        output = check_pacman.communicate()[0].decode("UTF-8").strip()
48
+        return len(output.split("\n")) if len(output) > 0 else 0

+ 131
- 0
i3/status/i3status/change_i3pystatus.py View File

@@ -0,0 +1,131 @@
1
+from i3pystatus.core import CommandEndpoint
2
+from i3pystatus.network import Network
3
+from i3pystatus.clock import Clock
4
+
5
+from gi.repository import Gtk
6
+
7
+import subprocess
8
+import sys
9
+import psutil
10
+import os
11
+import traceback
12
+
13
+
14
+###############################################################################
15
+# Tools
16
+###############################################################################
17
+g_i3bar_size = 18
18
+
19
+
20
+def exec(s):
21
+    p = subprocess.Popen(s.split(), stdout=sys.stderr.buffer)
22
+    return p.pid
23
+
24
+
25
+def check_pid(pid):
26
+    if psutil.pid_exists(pid):
27
+        proc = psutil.Process(pid)
28
+        if proc.status() == psutil.STATUS_ZOMBIE:
29
+            os.kill(pid, 2)
30
+            return False
31
+        return True
32
+    return False
33
+
34
+
35
+def get_current_screen_size(x, y):
36
+    screen = Gtk.Window().get_screen()
37
+    mn_number = screen.get_monitor_at_point(x, y) + 1
38
+    width, height = 0, 0
39
+    for mn_curr in range(mn_number):
40
+        mn = screen.get_monitor_geometry(mn_curr)
41
+        width += mn.width
42
+        height += mn.height
43
+    return width, height
44
+
45
+
46
+###############################################################################
47
+# Command end point
48
+###############################################################################
49
+def change_command_end_point():
50
+    """ We create a modified version of _command_endpoint that add the support
51
+    of x and y"""
52
+    def _command_endpoint(self):
53
+        for command in self.io_handler_factory().read():
54
+            target_module = self.modules.get(command["instance"])
55
+            if target_module:
56
+                try:
57
+                    target_module._pos_x = int(command["x"])
58
+                    target_module._pos_y = int(command["y"])
59
+                    target_module.on_click(command["button"])
60
+                except Exception:
61
+                    continue
62
+    CommandEndpoint._command_endpoint = _command_endpoint
63
+
64
+
65
+###############################################################################
66
+# Clock
67
+###############################################################################
68
+def change_clock():
69
+    def display_calendar(quit, s):
70
+        if "_pid" in s.__dict__ and check_pid(s._pid):
71
+            return
72
+
73
+        x, y = s._pos_x, s._pos_y
74
+        width_calendar, height_calendar = 300, 210  # fixed values...
75
+        width, height = get_current_screen_size(x, y)
76
+
77
+        if (x > width - width_calendar):
78
+            x = width - width_calendar
79
+        if (y < g_i3bar_size):
80
+            y = g_i3bar_size
81
+        if (y > height - height_calendar):
82
+            y = height - height_calendar - g_i3bar_size
83
+
84
+        s._pid = exec("calendar-window --size=%d-%d --position=%d-%d "
85
+                "--onLostFocus=%s" % (width_calendar, height_calendar,
86
+                    x, y, "quit" if quit else "ignore"))
87
+        #s._pid = exec("yad --no-buttons --geometry=+%d+%d --class "
88
+        #              "\"i3bar-gui\" --calendar" % (x, y))
89
+    def display_calendar_quit(s):
90
+        display_calendar(True, s)
91
+    def display_calendar_ignore(s):
92
+        display_calendar(False, s)
93
+
94
+    Clock.display_calendar = display_calendar_quit
95
+    Clock.on_leftclick = display_calendar_quit
96
+    Clock.on_rightclick = display_calendar_ignore
97
+
98
+
99
+###############################################################################
100
+# Network
101
+###############################################################################
102
+def change_network():
103
+    # We create the switch function
104
+    def switch_hide(s):
105
+        s.format_up, s.format_up_hide = s.format_up_hide, s.format_up
106
+        s.format_down, s.format_down_hide = s.format_down_hide, s.format_down
107
+
108
+    # We add it to the module
109
+    Network.switch_hide = switch_hide
110
+
111
+    # We add the correct settings and we init everything properly
112
+    Network.format_up_hide = Network.format_up
113
+    Network.format_down_hide = Network.format_down
114
+    Network.on_leftclick = switch_hide
115
+    Network.settings += (("format_down_hide", ""),)
116
+    Network.settings += (("format_up_hide", ""),)
117
+
118
+    # We change the mouse control
119
+    Network.format_up_hide = Network.format_up
120
+    Network.on_rightclick = Network.on_leftclick
121
+    Network.on_upscroll = Network.on_leftclick
122
+    Network.on_downscroll = Network.on_leftclick
123
+
124
+
125
+###############################################################################
126
+# Change that we apply
127
+###############################################################################
128
+def change_all():
129
+    change_command_end_point()
130
+    change_clock()
131
+    change_network()

+ 61
- 0
i3/status/i3status/my_ip.py View File

@@ -0,0 +1,61 @@
1
+import GeoIP
2
+import subprocess
3
+from i3pystatus import IntervalModule, formatp
4
+
5
+
6
+class MyIP(IntervalModule):
7
+
8
+    settings = (
9
+        "format",
10
+        "format_hide",
11
+        "format_down",
12
+        "timeout",
13
+        "color",
14
+    )
15
+
16
+    interval = 15
17
+    format = "{country_name} {country_code} {ip}"
18
+    format_hide = format
19
+    format_down = ""
20
+    timeout = 5
21
+    color = "#FFFFFF"
22
+
23
+    on_leftclick = "switch_hide"
24
+    on_rightclick = "run"
25
+
26
+    def run(self):
27
+        command = ["curl", "api.ipify.org"]
28
+        try:
29
+            p = subprocess.Popen(command, stdout=subprocess.PIPE,
30
+                                 stderr=subprocess.DEVNULL)
31
+            ip = p.communicate(timeout=self.timeout)[0].decode().strip()
32
+        except Exception:
33
+            return self.disable()
34
+
35
+        gi = GeoIP.GeoIP(GeoIP.GEOIP_STANDARD)
36
+        country_code = gi.country_code_by_addr(ip)
37
+        country_name = gi.country_name_by_addr(ip)
38
+
39
+        if not ip or not country_code:
40
+            return self.disable()
41
+
42
+        fdict = {
43
+            "country_name": country_name,
44
+            "country_code": country_code,
45
+            "ip": ip
46
+        }
47
+
48
+        self.output = {
49
+            "full_text": formatp(self.format, **fdict).strip(),
50
+            "color": self.color
51
+        }
52
+
53
+    def disable(self):
54
+        self.output = {
55
+            "full_text": self.format_down,
56
+            "color": self.color
57
+        }
58
+
59
+    def switch_hide(self):
60
+        self.format, self.format_hide = self.format_hide, self.format
61
+        self.run()

+ 98
- 0
i3/status/i3status/network_traffic.py View File

@@ -0,0 +1,98 @@
1
+from i3pystatus import IntervalModule
2
+from i3pystatus.core.util import round_dict
3
+import psutil
4
+
5
+
6
+class NetworkTraffic(IntervalModule):
7
+    """
8
+    Network traffic for all interfaces, i.e.,
9
+        packets/bytes sent/received per second.
10
+
11
+    Requires the PyPI packages `psutil`.
12
+
13
+    .. rubric:: Available formatters
14
+
15
+    * `{interface}` — the configured network interface
16
+    * `{bytes_sent}` — bytes sent per second (divided by divisor)
17
+    * `{bytes_recv}` — bytes received per second (divided by divisor)
18
+    * `{packets_sent}` — bytes sent per second (divided by divisor)
19
+    * `{packets_recv}` — bytes received per second (divided by divisor)
20
+    """
21
+
22
+    interval = 1
23
+    settings = (
24
+        ("format", "format string"),
25
+        ("interfaces", "network interfaces"),
26
+        ("divisor", "divide all byte values by this value"),
27
+        ("round_size", "defines number of digits in round"),
28
+        ("color", "the default color"),
29
+    )
30
+
31
+    format = "All: \u2197{bytes_sent}kB/s \u2198{bytes_recv}kB/s"
32
+    interfaces = ["eth0"]
33
+    divisor = 1024
34
+    round_size = None
35
+    color = "#FFFFFF"
36
+
37
+    pnic = None
38
+    pnic_before = None
39
+
40
+    def update_counters(self):
41
+        self.pnic_before = self.pnic
42
+        counters = psutil.net_io_counters(pernic=True)
43
+        self.pnic = counters
44
+
45
+    def get_bytes_sent(self, interface):
46
+        if interface not in self.pnic or interface not in self.pnic_before:
47
+            return 0
48
+        return (self.pnic[interface].bytes_sent -
49
+                self.pnic_before[interface].bytes_sent) / self.divisor
50
+
51
+    def get_bytes_received(self, interface):
52
+        if interface not in self.pnic or interface not in self.pnic_before:
53
+            return 0
54
+        return (self.pnic[interface].bytes_recv -
55
+                self.pnic_before[interface].bytes_recv) / self.divisor
56
+
57
+    def get_packets_sent(self, interface):
58
+        if interface not in self.pnic or interface not in self.pnic_before:
59
+            return 0
60
+        return (self.pnic[interface].packets_sent -
61
+                self.pnic_before[interface].packets_sent) / self.divisor
62
+
63
+    def get_packets_received(self, interface):
64
+        if interface not in self.pnic or interface not in self.pnic_before:
65
+            return 0
66
+        return (self.pnic[interface].packets_recv -
67
+                self.pnic_before[interface].packets_recv) / self.divisor
68
+
69
+    def sysfs_interface_up(self, interface):
70
+        try:
71
+            sysfs = "/sys/class/net/{}/operstate".format(interface)
72
+            with open(sysfs) as operstate:
73
+                status = operstate.read().strip()
74
+            return status == "up" or status == "unknown"
75
+        except FileNotFoundError:
76
+            return False
77
+
78
+    def run(self):
79
+        self.update_counters()
80
+        cdict = {
81
+            "bytes_sent": float(0),
82
+            "bytes_recv": float(0),
83
+            "packets_sent": float(0),
84
+            "packets_recv": float(0),
85
+        }
86
+        for interface in self.interfaces:
87
+            if self.sysfs_interface_up(interface):
88
+                if not self.pnic_before or interface not in self.pnic_before:
89
+                    continue
90
+                cdict["bytes_sent"] = self.get_bytes_sent(interface)
91
+                cdict["bytes_recv"] = self.get_bytes_received(interface)
92
+                cdict["packets_sent"] = self.get_packets_sent(interface)
93
+                cdict["packets_recv"] = self.get_packets_received(interface)
94
+        round_dict(cdict, self.round_size)
95
+        self.output = {
96
+            "full_text": self.format.format(**cdict),
97
+            "color": self.color
98
+        }

+ 49
- 0
i3/status/i3status/ping.py View File

@@ -0,0 +1,49 @@
1
+import subprocess
2
+
3
+from i3pystatus import IntervalModule
4
+
5
+
6
+class Ping(IntervalModule):
7
+    interval = 2
8
+
9
+    settings = (
10
+        ("host", "host to ping"),
11
+        ("format", "format string"),
12
+        ("format_down", "format down string"),
13
+        ("color", "color"),
14
+        ("color_down", "color down")
15
+    )
16
+    host = "8.8.8.8"
17
+    format = "{ping} ms"
18
+    format_down = "down"
19
+    color = "#FFFFFF"
20
+    color_down = "#FF0000"
21
+
22
+    def ping_host(self):
23
+        p = subprocess.Popen(["ping", "-c1", "-w%d" % self.interval,
24
+                              self.host], stdout=subprocess.PIPE,
25
+                             stderr=subprocess.DEVNULL)
26
+        out, _ = p.communicate()
27
+        if p.returncode == 0:
28
+            return out.decode().split("\n")[1].split("time=")[1].split()[0]
29
+        else:
30
+            return ""
31
+
32
+    def run(self):
33
+        ping = self.ping_host()
34
+        if not ping:
35
+            self.output = {
36
+                "full_text": self.format_down,
37
+                "color": self.color_down
38
+            }
39
+            return
40
+
41
+        ping = float(ping)
42
+        self.output = {
43
+            "full_text": self.format.format(ping=ping),
44
+            "color": self.color
45
+        }
46
+
47
+
48
+if __name__ == "__main__":
49
+    print(Ping().ping_host())

+ 92
- 0
i3/status/i3status/upower.py View File

@@ -0,0 +1,92 @@
1
+import datetime
2
+import dbus
3
+
4
+from i3pystatus import IntervalModule, formatp
5
+
6
+
7
+class UPower(IntervalModule):
8
+
9
+    settings = (
10
+        ("interval", "Refresh interval"),
11
+        ("battery_ident", "The battery identifier (same as setting)"),
12
+        ("alert_percent", "alert percent"),
13
+        ("format_chr", "format when charging"),
14
+        ("color_chr", "color when charging"),
15
+        ("format_dis", "format when discharging"),
16
+        ("color_dis", "color when discharging"),
17
+        ("format_dis_alert", "format when discharging with alert"),
18
+        ("color_dis_alert", "color when discharging with alert"),
19
+        ("format_full", "format when full"),
20
+        ("color_full", "color when full"),
21
+        ("format_dpl", "format when disable"),
22
+        ("color_dpl", "color when disable"),
23
+    )
24
+
25
+    interval = 3
26
+    battery_ident = "BAT0"
27
+
28
+    format_chr = "{state} {percentage} {time_to_full}"
29
+    format_dis = "{state} {percentage} {time_to_empty}"
30
+    format_full = "{state} {percentage}"
31
+    format_dpl = "{state}"
32
+
33
+    color_chr = "#00FF00"
34
+    color_dis = "#FFFF00"
35
+    color_dis_alert = "#FF0000"
36
+    color_full = "#00FF00"
37
+    color_dpl = "#FF0000"
38
+
39
+    alert_percent = 20
40
+
41
+    def init(self):
42
+        sess = dbus.SystemBus()
43
+        dev = sess.get_object(
44
+            "org.freedesktop.UPower",
45
+            "/org/freedesktop/UPower/devices/battery_%s" % self.battery_ident)
46
+        self.iface = dbus.Interface(
47
+            dev, dbus_interface="org.freedesktop.DBus.Properties")
48
+
49
+    def propertie(self, name):
50
+        return self.iface.Get("org.freedesktop.UPower.Device", name)
51
+
52
+    def time_to(self, name):
53
+        seconds = int(self.iface.Get("org.freedesktop.UPower.Device", name))
54
+        return datetime.timedelta(seconds=seconds)
55
+
56
+    def run(self):
57
+        status = ["CHR", "DIS", "DPL", "FULL"]
58
+        try:
59
+            statep = self.propertie("State")
60
+
61
+            percent = int(self.propertie("Percentage"))
62
+            time_to_empty = self.time_to("TimeToEmpty")
63
+            time_to_full = self.time_to("TimeToFull")
64
+        except Exception:
65
+            percent = 0
66
+            statep = 3
67
+            time_to_empty = datetime.timedelta(seconds=0)
68
+            time_to_full = datetime.timedelta(seconds=0)
69
+
70
+        if statep == 1 and not time_to_full:
71
+            statep = 4
72
+
73
+        state = status[statep - 1] if statep - 1 < len(status) else status[2]
74
+        format = getattr(self, "format_%s" % state.lower())
75
+        color = getattr(self, "color_%s" % state.lower())
76
+        if statep == 2 and percent < self.alert_percent:
77
+            color = self.color_dis_alert
78
+            format = self.format_dis_alert
79
+
80
+        fdict = {
81
+            "battery_ident": self.battery_ident,
82
+            "percentage": percent,
83
+            "time_to_full": time_to_full,
84
+            "time_to_empty": time_to_empty,
85
+            "state": state
86
+        }
87
+
88
+        self.output = {
89
+            "full_text": formatp(format, **fdict),
90
+            "urgent": False,
91
+            "color": color
92
+        }

+ 164
- 0
i3/status/status.py View File

@@ -0,0 +1,164 @@
1
+#!/bin/python3
2
+# coding=utf-8
3
+from i3pystatus import Status
4
+
5
+from i3status.upower import UPower
6
+from i3status.network_traffic import NetworkTraffic
7
+from i3status.ping import Ping
8
+from i3status.arch_updates import ArchUpdates
9
+from i3status.my_ip import MyIP
10
+
11
+# We change i3pystatus
12
+import i3status.change_i3pystatus
13
+i3status.change_i3pystatus.change_all()
14
+
15
+###############################################################################
16
+# COLORS
17
+###############################################################################
18
+g_color_normal = "#AEAEAE"
19
+g_color_second = "#66E0FF"
20
+g_color_good = "#8DE28D"
21
+g_color_warn = "#D68533"
22
+g_color_alert = "#FF5555"
23
+
24
+
25
+###############################################################################
26
+# Clock
27
+###############################################################################
28
+
29
+status = Status(standalone=True)
30
+
31
+status.register("clock",
32
+                color=g_color_second,
33
+                format="\uf0ce %d/%m/%y %H:%M:%S")
34
+
35
+
36
+###############################################################################
37
+# Battery, sound and light
38
+###############################################################################
39
+status.register(UPower,
40
+                alert_percent=30,
41
+                format_chr="\uf214↑ {percentage}% {time_to_full}",
42
+                format_dis="\uf214↓ {percentage}% {time_to_empty}",
43
+                format_dis_alert="\uf215↓ {percentage}% {time_to_empty}",
44
+                format_full="\uf213 {percentage}%",
45
+                format_dpl="\uf212",
46
+                color_chr=g_color_second,
47
+                color_dis=g_color_warn,
48
+                color_dis_alert=g_color_alert,
49
+                color_full=g_color_good,
50
+                color_dpl=g_color_alert)
51
+
52
+status.register("alsa",
53
+                mixer="Master",
54
+                card=0,
55
+                color_muted=g_color_warn,
56
+                format_muted="\uf026 0%",
57
+                format="\uf028 {volume:.0f}%")
58
+
59
+#status.register("backlight",
60
+#                interval=1,
61
+#                backlight="acpi_video0",
62
+#                format="\uf39b {percentage}%")
63
+
64
+
65
+###############################################################################
66
+# Processor and memory status
67
+###############################################################################
68
+status.register("temp",
69
+                file="/sys/class/thermal/thermal_zone1/temp",
70
+                #alert_temp=55,
71
+                color=g_color_good,
72
+                #alert_color=g_color_alert,
73
+                format="\uf3b6 {temp:.0f}°C")
74
+
75
+status.register("cpu_usage",
76
+                format="\uf0e4 {usage:02}%")
77
+
78
+status.register("mem",
79
+                color=g_color_good,
80
+                warn_color=g_color_warn,
81
+                alert_color=g_color_alert,
82
+                format="\uf085 {avail_mem:.0f}M")
83
+
84
+###############################################################################
85
+# Pacman
86
+###############################################################################
87
+#status.register(ArchUpdates,
88
+#                format=u"\uf500{count_pacman}|{count_yaourt}")
89
+
90
+
91
+###############################################################################
92
+# disk usage
93
+###############################################################################
94
+status.register("disk",
95
+                path="/",
96
+                critical_limit=10,
97
+                format="\uf07b {avail}G")
98
+
99
+status.register("disk",
100
+                path="/home",
101
+                critical_limit=5,
102
+                format="\uf015 {avail}G")
103
+
104
+###############################################################################
105
+# Network
106
+###############################################################################
107
+
108
+ifaces_traffic = ["eth0", "wlan0"]
109
+
110
+status.register(NetworkTraffic,
111
+                interfaces=ifaces_traffic,
112
+                divisor=1024**2,
113
+                round_size=2,
114
+                color=g_color_second,
115
+                format="\uf063 {bytes_recv:.2f}")
116
+
117
+status.register(NetworkTraffic,
118
+                interfaces=ifaces_traffic,
119
+                divisor=1024**2,
120
+                round_size=2,
121
+                color=g_color_warn,
122
+                format="\uf062 {bytes_sent:.2f}")
123
+
124
+status.register(Ping,
125
+                color=g_color_good,
126
+                color_down=g_color_alert,
127
+                format="\uf368 {ping:03.0f} ms",
128
+                format_down="\uf368 ∞ ms")
129
+
130
+ifaces_wireless = ["wlan0"]
131
+for iface in ifaces_wireless:
132
+    status.register("network",
133
+                interval=1,
134
+                interface=iface,
135
+                color_up=g_color_good,
136
+                format_down="",
137
+                format_down_hide="",
138
+                format_up="\uf1eb {essid} ({quality:03.0f}%) {v4}",
139
+                format_up_hide="\uf1eb {v4}").switch_hide()
140
+
141
+ifaces_wired = ["eth0"]
142
+for iface in ifaces_wired:
143
+    status.register("network",
144
+                interval=1,
145
+                interface=iface,
146
+                color_up=g_color_good,
147
+                format_down="",
148
+                format_down_hide="",
149
+                format_up_hide="\uf0e8 …",
150
+                format_up="\uf0e8 {v4}")
151
+
152
+ifaces_tun = ["tun0", "tun1", "tun2", "tun3"]
153
+for iface in ifaces_tun:
154
+    status.register("network",
155
+                interval=1,
156
+                interface=iface,
157
+                color_up=g_color_good,
158
+                format_down="",
159
+                format_down_hide="",
160
+                format_up_hide="\uf070 {v4}",
161
+                format_up="\uf070 {v4}",
162
+                unknown_up=True).switch_hide()
163
+
164
+status.run()

+ 44
- 0
i3/status/tools/volume.py View File

@@ -0,0 +1,44 @@
1
+#!/bin/python3
2
+
3
+import subprocess as sp
4
+import sys
5
+g_step = 10
6
+
7
+
8
+def set_volume(value):
9
+    sp.check_output(["xbacklight", "-set", str(int(value))])
10
+
11
+
12
+def get_volume():
13
+    return round(float(sp.check_output(["xbacklight",
14
+                                        "-get"]).decode().split()[0]))
15
+
16
+
17
+def volume_down():
18
+    vol = get_volume()
19
+    if vol <= g_step + 1:
20
+        set_volume(1)
21
+    else:
22
+        set_volume(vol - g_step)
23
+
24
+
25
+def volume_up():
26
+    vol = get_volume()
27
+    print(vol)
28
+    if vol <= 1:
29
+        set_volume(g_step)
30
+    else:
31
+        set_volume(vol + g_step)
32
+
33
+
34
+def main():
35
+    if len(sys.argv) != 2:
36
+        return
37
+    if sys.argv[1] == "up":
38
+        volume_up()
39
+    if sys.argv[1] == "down":
40
+        volume_down()
41
+
42
+
43
+if __name__ == "__main__":
44
+    main()

+ 3
- 0
vim/.netrwhist View File

@@ -0,0 +1,3 @@
1
+let g:netrw_dirhistmax  =10
2
+let g:netrw_dirhist_cnt =1
3
+let g:netrw_dirhist_1='/home/robin/.vim'

+ 1
- 0
vim/bundle/Vundle.vim

@@ -0,0 +1 @@
1
+Subproject commit 0b28e334e65b6628b0a61c412fcb45204a2f2bab

+ 1
- 0
vim/bundle/numbers.vim

@@ -0,0 +1 @@
1
+Subproject commit c7e04485568687ff1c6f4ff842ee80ec9c68d58a

+ 1
- 0
vim/bundle/syntastic

@@ -0,0 +1 @@
1
+Subproject commit 40776864c05ae0c9bd54aab79756ec5a6af1c63a

+ 1
- 0
vim/bundle/vundle

@@ -0,0 +1 @@
1
+Subproject commit 0b28e334e65b6628b0a61c412fcb45204a2f2bab

+ 841
- 0
vim/plugin/a.vim View File

@@ -0,0 +1,841 @@
1
+" Copyright (c) 1998-2006
2
+" Michael Sharpe <feline@irendi.com>
3
+"
4
+" We grant permission to use, copy modify, distribute, and sell this
5
+" software for any purpose without fee, provided that the above copyright
6
+" notice and this text are not removed. We make no guarantee about the
7
+" suitability of this software for any purpose and we are not liable
8
+" for any damages resulting from its use. Further, we are under no
9
+" obligation to maintain or extend this software. It is provided on an
10
+" "as is" basis without any expressed or implied warranty.
11
+
12
+" Directory & regex enhancements added by Bindu Wavell who is well known on
13
+" vim.sf.net
14
+"
15
+" Patch for spaces in files/directories from Nathan Stien (also reported by
16
+" Soeren Sonnenburg)
17
+
18
+" Do not load a.vim if is has already been loaded.
19
+if exists("loaded_alternateFile")
20
+    finish
21
+endif
22
+if (v:progname == "ex")
23
+   finish
24
+endif
25
+let loaded_alternateFile = 1
26
+
27
+let alternateExtensionsDict = {}
28
+
29
+" setup the default set of alternate extensions. The user can override in thier
30
+" .vimrc if the defaults are not suitable. To override in a .vimrc simply set a
31
+" g:alternateExtensions_<EXT> variable to a comma separated list of alternates,
32
+" where <EXT> is the extension to map.
33
+" E.g. let g:alternateExtensions_CPP = "inc,h,H,HPP,hpp"
34
+"      let g:alternateExtensions_{'aspx.cs'} = "aspx"
35
+
36
+
37
+" This variable will be increased when an extension with greater number of dots
38
+" is added by the AddAlternateExtensionMapping call.
39
+let s:maxDotsInExtension = 1
40
+
41
+" Function : AddAlternateExtensionMapping (PRIVATE)
42
+" Purpose  : simple helper function to add the default alternate extension
43
+"            mappings.
44
+" Args     : extension -- the extension to map
45
+"            alternates -- comma separated list of alternates extensions
46
+" Returns  : nothing
47
+" Author   : Michael Sharpe <feline@irendi.com>
48
+function! <SID>AddAlternateExtensionMapping(extension, alternates)
49
+   " This code does not actually work for variables like foo{'a.b.c.d.e'}
50
+   "let varName = "g:alternateExtensions_" . a:extension
51
+   "if (!exists(varName))
52
+   "   let g:alternateExtensions_{a:extension} = a:alternates
53
+   "endif
54
+
55
+   " This code handles extensions which contains a dot. exists() fails with
56
+   " such names.
57
+   "let v:errmsg = ""
58
+   " FIXME this line causes ex to return 1 instead of 0 for some reason??
59
+   "silent! echo g:alternateExtensions_{a:extension}
60
+   "if (v:errmsg != "")
61
+      "let g:alternateExtensions_{a:extension} = a:alternates
62
+   "endif
63
+
64
+   let g:alternateExtensionsDict[a:extension] = a:alternates
65
+   let dotsNumber = strlen(substitute(a:extension, "[^.]", "", "g"))
66
+   if s:maxDotsInExtension < dotsNumber
67
+     let s:maxDotsInExtension = dotsNumber
68
+   endif
69
+endfunction
70
+
71
+
72
+" Add all the default extensions
73
+" Mappings for C and C++
74
+call <SID>AddAlternateExtensionMapping('h',"c,cpp,cxx,cc,CC")
75
+call <SID>AddAlternateExtensionMapping('hh',"c,cpp,cxx,cc,CC")
76
+call <SID>AddAlternateExtensionMapping('H',"C,CPP,CXX,CC")
77
+call <SID>AddAlternateExtensionMapping('hpp',"cpp,c")
78
+call <SID>AddAlternateExtensionMapping('HPP',"CPP,C")
79
+call <SID>AddAlternateExtensionMapping('c',"h")
80
+call <SID>AddAlternateExtensionMapping('C',"H")
81
+call <SID>AddAlternateExtensionMapping('cpp',"h,hh,hpp")
82
+call <SID>AddAlternateExtensionMapping('CPP',"H,HPP")
83
+call <SID>AddAlternateExtensionMapping('cc',"h")
84
+call <SID>AddAlternateExtensionMapping('CC',"H,h")
85
+call <SID>AddAlternateExtensionMapping('cxx',"h")
86
+call <SID>AddAlternateExtensionMapping('CXX',"H")
87
+" Mappings for PSL7
88
+call <SID>AddAlternateExtensionMapping('psl',"ph")
89
+call <SID>AddAlternateExtensionMapping('ph',"psl")
90
+" Mappings for ADA
91
+call <SID>AddAlternateExtensionMapping('adb',"ads")
92
+call <SID>AddAlternateExtensionMapping('ads',"adb")
93
+" Mappings for lex and yacc files
94
+call <SID>AddAlternateExtensionMapping('l',"y,yacc,ypp")
95
+call <SID>AddAlternateExtensionMapping('lex',"yacc,y,ypp")
96
+call <SID>AddAlternateExtensionMapping('lpp',"ypp,y,yacc")
97
+call <SID>AddAlternateExtensionMapping('y',"l,lex,lpp")
98
+call <SID>AddAlternateExtensionMapping('yacc',"lex,l,lpp")
99
+call <SID>AddAlternateExtensionMapping('ypp',"lpp,l,lex")
100
+" Mappings for OCaml
101
+call <SID>AddAlternateExtensionMapping('ml',"mli")
102
+call <SID>AddAlternateExtensionMapping('mli',"ml")
103
+" ASP stuff
104
+call <SID>AddAlternateExtensionMapping('aspx.cs', 'aspx')
105
+call <SID>AddAlternateExtensionMapping('aspx.vb', 'aspx')
106
+call <SID>AddAlternateExtensionMapping('aspx', 'aspx.cs,aspx.vb')
107
+
108
+" Setup default search path, unless the user has specified
109
+" a path in their [._]vimrc. 
110
+if (!exists('g:alternateSearchPath'))
111
+  let g:alternateSearchPath = 'sfr:../source,sfr:../src,sfr:../include,sfr:../inc'
112
+endif
113
+
114
+" If this variable is true then a.vim will not alternate to a file/buffer which
115
+" does not exist. E.g while editing a.c and the :A will not swtich to a.h
116
+" unless it exists.
117
+if (!exists('g:alternateNoDefaultAlternate'))
118
+   " by default a.vim will alternate to a file which does not exist
119
+   let g:alternateNoDefaultAlternate = 0
120
+endif
121
+
122
+" If this variable is true then a.vim will convert the alternate filename to a
123
+" filename relative to the current working directory.
124
+" Feature by Nathan Huizinga
125
+if (!exists('g:alternateRelativeFiles'))                                        
126
+   " by default a.vim will not convert the filename to one relative to the
127
+   " current working directory
128
+   let g:alternateRelativeFiles = 0
129
+endif
130
+
131
+
132
+" Function : GetNthItemFromList (PRIVATE)
133
+" Purpose  : Support reading items from a comma seperated list
134
+"            Used to iterate all the extensions in an extension spec
135
+"            Used to iterate all path prefixes
136
+" Args     : list -- the list (extension spec, file paths) to iterate
137
+"            n -- the extension to get
138
+" Returns  : the nth item (extension, path) from the list (extension 
139
+"            spec), or "" for failure
140
+" Author   : Michael Sharpe <feline@irendi.com>
141
+" History  : Renamed from GetNthExtensionFromSpec to GetNthItemFromList
142
+"            to reflect a more generic use of this function. -- Bindu
143
+function! <SID>GetNthItemFromList(list, n) 
144
+   let itemStart = 0
145
+   let itemEnd = -1
146
+   let pos = 0
147
+   let item = ""
148
+   let i = 0
149
+   while (i != a:n)
150
+      let itemStart = itemEnd + 1
151
+      let itemEnd = match(a:list, ",", itemStart)
152
+      let i = i + 1
153
+      if (itemEnd == -1)
154
+         if (i == a:n)
155
+            let itemEnd = strlen(a:list)
156
+         endif
157
+         break
158
+      endif
159
+   endwhile 
160
+   if (itemEnd != -1) 
161
+      let item = strpart(a:list, itemStart, itemEnd - itemStart)
162
+   endif
163
+   return item 
164
+endfunction
165
+
166
+" Function : ExpandAlternatePath (PRIVATE)
167
+" Purpose  : Expand path info.  A path with a prefix of "wdr:" will be 
168
+"            treated as relative to the working directory (i.e. the 
169
+"            directory where vim was started.) A path prefix of "abs:" will 
170
+"            be treated as absolute. No prefix or "sfr:" will result in the 
171
+"            path being treated as relative to the source file (see sfPath 
172
+"            argument). 
173
+"
174
+"            A prefix of "reg:" will treat the pathSpec as a regular
175
+"            expression substitution that is applied to the source file 
176
+"            path. The format is:
177
+"
178
+"              reg:<sep><pattern><sep><subst><sep><flag><sep>
179
+"          
180
+"            <sep> seperator character, we often use one of [/|%#] 
181
+"            <pattern> is what you are looking for
182
+"            <subst> is the output pattern
183
+"            <flag> can be g for global replace or empty
184
+"
185
+"            EXAMPLE: 'reg:/inc/src/g/' will replace every instance 
186
+"            of 'inc' with 'src' in the source file path. It is possible
187
+"            to use match variables so you could do something like:
188
+"            'reg:|src/\([^/]*\)|inc/\1||' (see 'help :substitute', 
189
+"            'help pattern' and 'help sub-replace-special' for more details
190
+"
191
+"            NOTE: a.vim uses ',' (comma) internally so DON'T use it
192
+"            in your regular expressions or other pathSpecs unless you update 
193
+"            the rest of the a.vim code to use some other seperator.
194
+"
195
+" Args     : pathSpec -- path component (or substitution patterns)
196
+"            sfPath -- source file path
197
+" Returns  : a path that can be used by AlternateFile()
198
+" Author   : Bindu Wavell <bindu@wavell.net>
199
+function! <SID>ExpandAlternatePath(pathSpec, sfPath) 
200
+   let prfx = strpart(a:pathSpec, 0, 4)
201
+   if (prfx == "wdr:" || prfx == "abs:")
202
+      let path = strpart(a:pathSpec, 4)
203
+   elseif (prfx == "reg:")
204
+      let re = strpart(a:pathSpec, 4)
205
+      let sep = strpart(re, 0, 1)
206
+      let patend = match(re, sep, 1)
207
+      let pat = strpart(re, 1, patend - 1)
208
+      let subend = match(re, sep, patend + 1)
209
+      let sub = strpart(re, patend+1, subend - patend - 1)
210
+      let flag = strpart(re, strlen(re) - 2)
211
+      if (flag == sep)
212
+        let flag = ''
213
+      endif
214
+      let path = substitute(a:sfPath, pat, sub, flag)
215
+      "call confirm('PAT: [' . pat . '] SUB: [' . sub . ']')
216
+      "call confirm(a:sfPath . ' => ' . path)
217
+   else
218
+      let path = a:pathSpec
219
+      if (prfx == "sfr:")
220
+         let path = strpart(path, 4)
221
+      endif
222
+      let path = a:sfPath . "/" . path
223
+   endif
224
+   return path
225
+endfunction
226
+
227
+" Function : FindFileInSearchPath (PRIVATE)
228
+" Purpose  : Searches for a file in the search path list
229
+" Args     : filename -- name of the file to search for
230
+"            pathList -- the path list to search
231
+"            relPathBase -- the path which relative paths are expanded from
232
+" Returns  : An expanded filename if found, the empty string otherwise
233
+" Author   : Michael Sharpe (feline@irendi.com)
234
+" History  : inline code written by Bindu Wavell originally
235
+function! <SID>FindFileInSearchPath(fileName, pathList, relPathBase)
236
+   let filepath = ""
237
+   let m = 1
238
+   let pathListLen = strlen(a:pathList)
239
+   if (pathListLen > 0)
240
+      while (1)
241
+         let pathSpec = <SID>GetNthItemFromList(a:pathList, m) 
242
+         if (pathSpec != "")
243
+            let path = <SID>ExpandAlternatePath(pathSpec, a:relPathBase)
244
+            let fullname = path . "/" . a:fileName
245
+            let foundMatch = <SID>BufferOrFileExists(fullname)
246
+            if (foundMatch)
247
+               let filepath = fullname
248
+               break
249
+            endif
250
+         else
251
+            break
252
+         endif
253
+         let m = m + 1
254
+      endwhile
255
+   endif
256
+   return filepath
257
+endfunction
258
+
259
+" Function : FindFileInSearchPathEx (PRIVATE)
260
+" Purpose  : Searches for a file in the search path list
261
+" Args     : filename -- name of the file to search for
262
+"            pathList -- the path list to search
263
+"            relPathBase -- the path which relative paths are expanded from
264
+"            count -- find the count'th occurence of the file on the path
265
+" Returns  : An expanded filename if found, the empty string otherwise
266
+" Author   : Michael Sharpe (feline@irendi.com)
267
+" History  : Based on <SID>FindFileInSearchPath() but with extensions
268
+function! <SID>FindFileInSearchPathEx(fileName, pathList, relPathBase, count)
269
+   let filepath = ""
270
+   let m = 1
271
+   let spath = ""
272
+   let pathListLen = strlen(a:pathList)
273
+   if (pathListLen > 0)
274
+      while (1)
275
+         let pathSpec = <SID>GetNthItemFromList(a:pathList, m) 
276
+         if (pathSpec != "")
277
+            let path = <SID>ExpandAlternatePath(pathSpec, a:relPathBase)
278
+            if (spath != "")
279
+               let spath = spath . ','
280
+            endif
281
+            let spath = spath . path
282
+         else
283
+            break
284
+         endif
285
+         let m = m + 1
286
+      endwhile
287
+   endif
288
+
289
+   if (&path != "")
290
+      if (spath != "")
291
+         let spath = spath . ','
292
+      endif
293
+      let spath = spath . &path
294
+   endif
295
+
296
+   let filepath = findfile(a:fileName, spath, a:count)
297
+   return filepath
298
+endfunction
299
+
300
+" Function : EnumerateFilesByExtension (PRIVATE)
301
+" Purpose  : enumerates all files by a particular list of alternate extensions.
302
+" Args     : path -- path of a file (not including the file)
303
+"            baseName -- base name of the file to be expanded
304
+"            extension -- extension whose alternates are to be enumerated
305
+" Returns  : comma separated list of files with extensions
306
+" Author   : Michael Sharpe <feline@irendi.com>
307
+function! EnumerateFilesByExtension(path, baseName, extension)
308
+   let enumeration = ""
309
+   let extSpec = ""
310
+   let v:errmsg = ""
311
+   silent! echo g:alternateExtensions_{a:extension}
312
+   if (v:errmsg == "")
313
+      let extSpec = g:alternateExtensions_{a:extension}
314
+   endif
315
+   if (extSpec == "")
316
+      if (has_key(g:alternateExtensionsDict, a:extension))
317
+         let extSpec = g:alternateExtensionsDict[a:extension]
318
+      endif
319
+   endif
320
+   if (extSpec != "") 
321
+      let n = 1
322
+      let done = 0
323
+      while (!done)
324
+         let ext = <SID>GetNthItemFromList(extSpec, n)
325
+         if (ext != "")
326
+            if (a:path != "")
327
+               let newFilename = a:path . "/" . a:baseName . "." . ext
328
+            else
329
+               let newFilename =  a:baseName . "." . ext
330
+            endif
331
+            if (enumeration == "")
332
+               let enumeration = newFilename
333
+            else
334
+               let enumeration = enumeration . "," . newFilename
335
+            endif
336
+         else
337
+            let done = 1
338
+         endif
339
+         let n = n + 1
340
+      endwhile
341
+   endif
342
+   return enumeration
343
+endfunction
344
+
345
+" Function : EnumerateFilesByExtensionInPath (PRIVATE)
346
+" Purpose  : enumerates all files by expanding the path list and the extension
347
+"            list.
348
+" Args     : baseName -- base name of the file
349
+"            extension -- extension whose alternates are to be enumerated
350
+"            pathList -- the list of paths to enumerate
351
+"            relPath -- the path of the current file for expansion of relative
352
+"                       paths in the path list.
353
+" Returns  : A comma separated list of paths with extensions
354
+" Author   : Michael Sharpe <feline@irendi.com>
355
+function! EnumerateFilesByExtensionInPath(baseName, extension, pathList, relPathBase)
356
+   let enumeration = ""
357
+   let filepath = ""
358
+   let m = 1
359
+   let pathListLen = strlen(a:pathList)
360
+   if (pathListLen > 0)
361
+      while (1)
362
+         let pathSpec = <SID>GetNthItemFromList(a:pathList, m) 
363
+         if (pathSpec != "")
364
+            let path = <SID>ExpandAlternatePath(pathSpec, a:relPathBase)
365
+            let pe = EnumerateFilesByExtension(path, a:baseName, a:extension)
366
+            if (enumeration == "")
367
+               let enumeration = pe
368
+            else
369
+               let enumeration = enumeration . "," . pe
370
+            endif
371
+         else
372
+            break
373
+         endif
374
+         let m = m + 1
375
+      endwhile
376
+   endif
377
+   return enumeration
378
+endfunction
379
+
380
+" Function : DetermineExtension (PRIVATE)
381
+" Purpose  : Determines the extension of a filename based on the register
382
+"            alternate extension. This allow extension which contain dots to 
383
+"            be considered. E.g. foo.aspx.cs to foo.aspx where an alternate
384
+"            exists for the aspx.cs extension. Note that this will only accept
385
+"            extensions which contain less than 5 dots. This is only
386
+"            implemented in this manner for simplicity...it is doubtful that 
387
+"            this will be a restriction in non-contrived situations.
388
+" Args     : The path to the file to find the extension in
389
+" Returns  : The matched extension if any
390
+" Author   : Michael Sharpe (feline@irendi.com)
391
+" History  : idea from Tom-Erik Duestad
392
+" Notes    : there is some magic occuring here. The exists() function does not
393
+"            work well when the curly brace variable has dots in it. And why
394
+"            should it, dots are not valid in variable names. But the exists
395
+"            function is wierd too. Lets say foo_c does exist. Then
396
+"            exists("foo_c.e.f") will be true...even though the variable does 
397
+"            not exist. However the curly brace variables do work when the
398
+"            variable has dots in it. E.g foo_{'c'} is different from 
399
+"            foo_{'c.d.e'}...and foo_{'c'} is identical to foo_c and
400
+"            foo_{'c.d.e'} is identical to foo_c.d.e right? Yes in the current
401
+"            implementation of vim. To trick vim to test for existence of such
402
+"            variables echo the curly brace variable and look for an error 
403
+"            message.
404
+function! DetermineExtension(path) 
405
+  let mods = ":t"
406
+  let i = 0
407
+  while i <= s:maxDotsInExtension
408
+    let mods = mods . ":e"
409
+    let extension = fnamemodify(a:path, mods)
410
+    if (has_key(g:alternateExtensionsDict, extension))
411
+       return extension
412
+    endif
413
+    let v:errmsg = ""
414
+    silent! echo g:alternateExtensions_{extension}
415
+    if (v:errmsg == "")
416
+      return extension
417
+    endif
418
+    let i = i + 1
419
+  endwhile
420
+  return ""
421
+endfunction
422
+
423
+" Function : AlternateFile (PUBLIC)
424
+" Purpose  : Opens a new buffer by looking at the extension of the current
425
+"            buffer and finding the corresponding file. E.g. foo.c <--> foo.h
426
+" Args     : accepts one argument. If present it used the argument as the new
427
+"            extension.
428
+" Returns  : nothing
429
+" Author   : Michael Sharpe <feline@irendi.com>
430
+" History  : + When an alternate can't be found in the same directory as the
431
+"              source file, a search path will be traversed looking for the
432
+"              alternates.
433
+"            + Moved some code into a separate function, minor optimization
434
+"            + rework to favor files in memory based on complete enumeration of
435
+"              all files extensions and paths
436
+function! AlternateFile(splitWindow, ...)
437
+  let extension   = DetermineExtension(expand("%:p"))
438
+  let baseName    = substitute(expand("%:t"), "\." . extension . '$', "", "")
439
+  let currentPath = expand("%:p:h")
440
+
441
+  if (a:0 != 0)
442
+     let newFullname = currentPath . "/" .  baseName . "." . a:1
443
+     call <SID>FindOrCreateBuffer(newFullname, a:splitWindow, 0)
444
+  else
445
+     let allfiles = ""
446
+     if (extension != "")
447
+        let allfiles1 = EnumerateFilesByExtension(currentPath, baseName, extension)
448
+        let allfiles2 = EnumerateFilesByExtensionInPath(baseName, extension, g:alternateSearchPath, currentPath)
449
+
450
+        if (allfiles1 != "")
451
+           if (allfiles2 != "")
452
+              let allfiles = allfiles1 . ',' . allfiles2
453
+           else
454
+              let allfiles = allfiles1
455
+           endif
456
+        else 
457
+           let allfiles = allfiles2
458
+        endif
459
+     endif
460
+
461
+     if (allfiles != "") 
462
+        let bestFile = ""
463
+        let bestScore = 0
464
+        let score = 0
465
+        let n = 1
466
+         
467
+        let onefile = <SID>GetNthItemFromList(allfiles, n)
468
+        let bestFile = onefile
469
+        while (onefile != "" && score < 2)
470
+           let score = <SID>BufferOrFileExists(onefile)
471
+           if (score > bestScore)
472
+              let bestScore = score
473
+              let bestFile = onefile
474
+           endif
475
+           let n = n + 1
476
+           let onefile = <SID>GetNthItemFromList(allfiles, n)
477
+        endwhile
478
+
479
+        if (bestScore == 0 && g:alternateNoDefaultAlternate == 1)
480
+           echo "No existing alternate available"
481
+        else
482
+           call <SID>FindOrCreateBuffer(bestFile, a:splitWindow, 1)
483
+           let b:AlternateAllFiles = allfiles
484
+        endif
485
+     else
486
+        echo "No alternate file/buffer available"
487
+     endif
488
+   endif
489
+endfunction
490
+
491
+" Function : AlternateOpenFileUnderCursor (PUBLIC)
492
+" Purpose  : Opens file under the cursor
493
+" Args     : splitWindow -- indicates how to open the file
494
+" Returns  : Nothing
495
+" Author   : Michael Sharpe (feline@irendi.com) www.irendi.com
496
+function! AlternateOpenFileUnderCursor(splitWindow,...)
497
+   let cursorFile = (a:0 > 0) ? a:1 : expand("<cfile>") 
498
+   let currentPath = expand("%:p:h")
499
+   let openCount = 1
500
+
501
+   let fileName = <SID>FindFileInSearchPathEx(cursorFile, g:alternateSearchPath, currentPath, openCount)
502
+   if (fileName != "")
503
+      call <SID>FindOrCreateBuffer(fileName, a:splitWindow, 1)
504
+      let b:openCount = openCount
505
+      let b:cursorFile = cursorFile
506
+      let b:currentPath = currentPath
507
+   else
508
+      echo "Can't find file"
509
+   endif
510
+endfunction
511
+
512
+" Function : AlternateOpenNextFile (PUBLIC)
513
+" Purpose  : Opens the next file corresponding to the search which found the 
514
+"            current file
515
+" Args     : bang -- indicates what to do if the current file has not been 
516
+"                    saved
517
+" Returns  : nothing
518
+" Author   : Michael Sharpe (feline@irendi.com) www.irendi.com
519
+function! AlternateOpenNextFile(bang)
520
+   let cursorFile = ""
521
+   if (exists("b:cursorFile"))
522
+      let cursorFile = b:cursorFile
523
+   endif
524
+
525
+   let currentPath = ""
526
+   if (exists("b:currentPath"))
527
+      let currentPath = b:currentPath
528
+   endif
529
+
530
+   let openCount = 0
531
+   if (exists("b:openCount"))
532
+      let openCount = b:openCount + 1
533
+   endif
534
+
535
+   if (cursorFile != ""  && currentPath != ""  && openCount != 0)
536
+      let fileName = <SID>FindFileInSearchPathEx(cursorFile, g:alternateSearchPath, currentPath, openCount)
537
+      if (fileName != "")
538
+         call <SID>FindOrCreateBuffer(fileName, "n".a:bang, 0)
539
+         let b:openCount = openCount
540
+         let b:cursorFile = cursorFile
541
+         let b:currentPath = currentPath
542
+      else 
543
+         let fileName = <SID>FindFileInSearchPathEx(cursorFile, g:alternateSearchPath, currentPath, 1)
544
+         if (fileName != "")
545
+            call <SID>FindOrCreateBuffer(fileName, "n".a:bang, 0)
546
+            let b:openCount = 1
547
+            let b:cursorFile = cursorFile
548
+            let b:currentPath = currentPath
549
+         else
550
+            echo "Can't find next file"
551
+         endif
552
+      endif
553
+   endif
554
+endfunction
555
+
556
+comm! -nargs=? -bang IH call AlternateOpenFileUnderCursor("n<bang>", <f-args>)
557
+comm! -nargs=? -bang IHS call AlternateOpenFileUnderCursor("h<bang>", <f-args>)
558
+comm! -nargs=? -bang IHV call AlternateOpenFileUnderCursor("v<bang>", <f-args>)
559
+comm! -nargs=? -bang IHT call AlternateOpenFileUnderCursor("t<bang>", <f-args>)
560
+comm! -nargs=? -bang IHN call AlternateOpenNextFile("<bang>")
561
+imap <Leader>ih <ESC>:IHS<CR>
562
+nmap <Leader>ih :IHS<CR>
563
+imap <Leader>is <ESC>:IHS<CR>:A<CR>
564
+nmap <Leader>is :IHS<CR>:A<CR>
565
+imap <Leader>ihn <ESC>:IHN<CR>
566
+nmap <Leader>ihn :IHN<CR>
567
+
568
+"function! <SID>PrintList(theList) 
569
+"   let n = 1
570
+"   let oneFile = <SID>GetNthItemFromList(a:theList, n)
571
+"   while (oneFile != "")
572
+"      let n = n + 1
573
+"      let oneFile = <SID>GetNthItemFromList(a:theList, n)
574
+"   endwhile
575
+"endfunction
576
+
577
+" Function : NextAlternate (PUBLIC)
578
+" Purpose  : Used to cycle through any other alternate file which existed on
579
+"            the search path.
580
+" Args     : bang (IN) - used to implement the AN vs AN! functionality
581
+" Returns  : nothing
582
+" Author   : Michael Sharpe <feline@irendi.com>
583
+function! NextAlternate(bang)
584
+   if (exists('b:AlternateAllFiles'))
585
+      let currentFile = expand("%")
586
+      let n = 1
587
+      let onefile = <SID>GetNthItemFromList(b:AlternateAllFiles, n)
588
+      while (onefile != "" && !<SID>EqualFilePaths(fnamemodify(onefile,":p"), fnamemodify(currentFile,":p")))
589
+         let n = n + 1
590
+         let onefile = <SID>GetNthItemFromList(b:AlternateAllFiles, n)
591
+      endwhile
592
+
593
+      if (onefile != "")
594
+         let stop = n
595
+         let n = n + 1
596
+         let foundAlternate = 0
597
+         let nextAlternate = ""
598
+         while (n != stop)
599
+            let nextAlternate = <SID>GetNthItemFromList(b:AlternateAllFiles, n)
600
+            if (nextAlternate == "")
601
+               let n = 1
602
+               continue
603
+            endif
604
+            let n = n + 1
605
+            if (<SID>EqualFilePaths(fnamemodify(nextAlternate, ":p"), fnamemodify(currentFile, ":p")))
606
+                continue
607
+            endif
608
+            if (filereadable(nextAlternate))
609
+                " on cygwin filereadable("foo.H") returns true if "foo.h" exists
610
+               if (has("unix") && $WINDIR != "" && fnamemodify(nextAlternate, ":p") ==? fnamemodify(currentFile, ":p")) 
611
+                  continue
612
+               endif
613
+               let foundAlternate = 1
614
+               break
615
+            endif
616
+         endwhile
617
+         if (foundAlternate == 1)
618
+            let s:AlternateAllFiles = b:AlternateAllFiles
619
+            "silent! execute ":e".a:bang." " . nextAlternate
620
+            call <SID>FindOrCreateBuffer(nextAlternate, "n".a:bang, 0)
621
+            let b:AlternateAllFiles = s:AlternateAllFiles
622
+         else 
623
+            echo "Only this alternate file exists"
624
+         endif
625
+      else 
626
+         echo "Could not find current file in alternates list"
627
+      endif
628
+   else 
629
+      echo "No other alternate files exist"
630
+   endif
631
+endfunction
632
+
633
+comm! -nargs=? -bang A call AlternateFile("n<bang>", <f-args>)
634
+comm! -nargs=? -bang AS call AlternateFile("h<bang>", <f-args>)
635
+comm! -nargs=? -bang AV call AlternateFile("v<bang>", <f-args>)
636
+comm! -nargs=? -bang AT call AlternateFile("t<bang>", <f-args>)
637
+comm! -nargs=? -bang AN call NextAlternate("<bang>")
638
+
639
+" Function : BufferOrFileExists (PRIVATE)
640
+" Purpose  : determines if a buffer or a readable file exists
641
+" Args     : fileName (IN) - name of the file to check
642
+" Returns  : 2 if it exists in memory, 1 if it exists, 0 otherwise
643
+" Author   : Michael Sharpe <feline@irendi.com>
644
+" History  : Updated code to handle buffernames using just the
645
+"            filename and not the path.
646
+function! <SID>BufferOrFileExists(fileName)
647
+   let result = 0
648
+
649
+   let lastBuffer = bufnr("$")
650
+   let i = 1
651
+   while i <= lastBuffer
652
+     if <SID>EqualFilePaths(expand("#".i.":p"), a:fileName)
653
+       let result = 2
654
+       break
655
+     endif
656
+     let i = i + 1
657
+   endwhile
658
+
659
+   if (!result) 
660
+      let bufName = fnamemodify(a:fileName,":t")
661
+      let memBufName = bufname(bufName)
662
+      if (memBufName != "")
663
+         let memBufBasename = fnamemodify(memBufName, ":t")
664
+         if (bufName == memBufBasename)
665
+            let result = 2
666
+         endif
667
+      endif
668
+
669
+      if (!result)
670
+         let result  = bufexists(bufName) || bufexists(a:fileName) || filereadable(a:fileName)
671
+      endif
672
+   endif
673
+
674
+   if (!result)
675
+      let result = filereadable(a:fileName)
676
+   endif
677
+   return result
678
+endfunction
679
+
680
+" Function : FindOrCreateBuffer (PRIVATE)
681
+" Purpose  : searches the buffer list (:ls) for the specified filename. If
682
+"            found, checks the window list for the buffer. If the buffer is in
683
+"            an already open window, it switches to the window. If the buffer
684
+"            was not in a window, it switches to that buffer. If the buffer did
685
+"            not exist, it creates it.
686
+" Args     : filename (IN) -- the name of the file
687
+"            doSplit (IN) -- indicates whether the window should be split
688
+"                            ("v", "h", "n", "v!", "h!", "n!", "t", "t!") 
689
+"            findSimilar (IN) -- indicate weather existing buffers should be
690
+"                                prefered
691
+" Returns  : nothing
692
+" Author   : Michael Sharpe <feline@irendi.com>
693
+" History  : + bufname() was not working very well with the possibly strange
694
+"            paths that can abound with the search path so updated this
695
+"            slightly.  -- Bindu
696
+"            + updated window switching code to make it more efficient -- Bindu
697
+"            Allow ! to be applied to buffer/split/editing commands for more
698
+"            vim/vi like consistency
699
+"            + implemented fix from Matt Perry
700
+function! <SID>FindOrCreateBuffer(fileName, doSplit, findSimilar)
701
+  " Check to see if the buffer is already open before re-opening it.
702
+  let FILENAME = escape(a:fileName, ' ')
703
+  let bufNr = -1
704
+  let lastBuffer = bufnr("$")
705
+  let i = 1
706
+  if (a:findSimilar) 
707
+     while i <= lastBuffer
708
+       if <SID>EqualFilePaths(expand("#".i.":p"), a:fileName)
709
+         let bufNr = i
710
+         break
711
+       endif
712
+       let i = i + 1
713
+     endwhile
714
+
715
+     if (bufNr == -1)
716
+        let bufName = bufname(a:fileName)
717
+        let bufFilename = fnamemodify(a:fileName,":t")
718
+
719
+        if (bufName == "")
720
+           let bufName = bufname(bufFilename)
721
+        endif
722
+
723
+        if (bufName != "")
724
+           let tail = fnamemodify(bufName, ":t")
725
+           if (tail != bufFilename)
726
+              let bufName = ""
727
+           endif
728
+        endif
729
+        if (bufName != "")
730
+           let bufNr = bufnr(bufName)
731
+           let FILENAME = bufName
732
+        endif
733
+     endif
734
+  endif
735
+
736
+  if (g:alternateRelativeFiles == 1)                                            
737
+        let FILENAME = fnamemodify(FILENAME, ":p:.")
738
+  endif
739
+
740
+  let splitType = a:doSplit[0]
741
+  let bang = a:doSplit[1]
742
+  if (bufNr == -1)
743
+     " Buffer did not exist....create it
744
+     let v:errmsg=""
745
+     if (splitType == "h")
746
+        silent! execute ":split".bang." " . FILENAME
747
+     elseif (splitType == "v")
748
+        silent! execute ":vsplit".bang." " . FILENAME
749
+     elseif (splitType == "t")
750
+        silent! execute ":tab split".bang." " . FILENAME
751
+     else
752
+        silent! execute ":e".bang." " . FILENAME
753
+     endif
754
+     if (v:errmsg != "")
755
+        echo v:errmsg
756
+     endif
757
+  else
758
+
759
+     " Find the correct tab corresponding to the existing buffer
760
+     let tabNr = -1
761
+     " iterate tab pages
762
+     for i in range(tabpagenr('$'))
763
+        " get the list of buffers in the tab
764
+        let tabList =  tabpagebuflist(i + 1)
765
+        let idx = 0
766
+        " iterate each buffer in the list
767
+        while idx < len(tabList)
768
+           " if it matches the buffer we are looking for...
769
+           if (tabList[idx] == bufNr)
770
+              " ... save the number
771
+              let tabNr = i + 1
772
+              break
773
+           endif
774
+           let idx = idx + 1
775
+        endwhile
776
+        if (tabNr != -1)
777
+           break
778
+        endif
779
+     endfor
780
+     " switch the the tab containing the buffer
781
+     if (tabNr != -1)
782
+        execute "tabn ".tabNr
783
+     endif
784
+
785
+     " Buffer was already open......check to see if it is in a window
786
+     let bufWindow = bufwinnr(bufNr)
787
+     if (bufWindow == -1) 
788
+        " Buffer was not in a window so open one
789
+        let v:errmsg=""
790
+        if (splitType == "h")
791
+           silent! execute ":sbuffer".bang." " . FILENAME
792
+        elseif (splitType == "v")
793
+           silent! execute ":vert sbuffer " . FILENAME
794
+        elseif (splitType == "t")
795
+           silent! execute ":tab sbuffer " . FILENAME
796
+        else
797
+           silent! execute ":buffer".bang." " . FILENAME
798
+        endif
799
+        if (v:errmsg != "")
800
+           echo v:errmsg
801
+        endif
802
+     else
803
+        " Buffer is already in a window so switch to the window
804
+        execute bufWindow."wincmd w"
805
+        if (bufWindow != winnr()) 
806
+           " something wierd happened...open the buffer
807
+           let v:errmsg=""
808
+           if (splitType == "h")
809
+              silent! execute ":split".bang." " . FILENAME
810
+           elseif (splitType == "v")
811
+              silent! execute ":vsplit".bang." " . FILENAME
812
+           elseif (splitType == "t")
813
+              silent! execute ":tab split".bang." " . FILENAME
814
+           else
815
+              silent! execute ":e".bang." " . FILENAME
816
+           endif
817
+           if (v:errmsg != "")
818
+              echo v:errmsg
819
+           endif
820
+        endif
821
+     endif
822
+  endif
823
+endfunction
824
+
825
+" Function : EqualFilePaths (PRIVATE)
826
+" Purpose  : Compares two paths. Do simple string comparison anywhere but on
827
+"            Windows. On Windows take into account that file paths could differ
828
+"            in usage of separators and the fact that case does not matter.
829
+"            "c:\WINDOWS" is the same path as "c:/windows". has("win32unix") Vim
830
+"            version does not count as one having Windows path rules.
831
+" Args     : path1 (IN) -- first path
832
+"            path2 (IN) -- second path
833
+" Returns  : 1 if path1 is equal to path2, 0 otherwise.
834
+" Author   : Ilya Bobir <ilya@po4ta.com>
835
+function! <SID>EqualFilePaths(path1, path2)
836
+  if has("win16") || has("win32") || has("win64") || has("win95")
837
+    return substitute(a:path1, "\/", "\\", "g") ==? substitute(a:path2, "\/", "\\", "g")
838
+  else
839
+    return a:path1 == a:path2
840
+  endif
841
+endfunction

+ 118
- 0
vim/plugin/tiger.vim View File

@@ -0,0 +1,118 @@
1
+""
2
+"" tiger.vim for vim-syntax in /u/a1/sigour_b/.vim/syntax
3
+""
4
+"" Made by SIGOURE Benoit
5
+"" Login   <sigour_b@epita.fr>
6
+""
7
+"" Started on  Sat Jan  7 20:11:05 2006 SIGOURE Benoit
8
+"" Last update Wed Mar  8 14:23:09 2006 SIGOURE Benoit
9
+""
10
+
11
+" Vim syntax file based on the C syntax file by Bram Moolenaar <Bram@vim.org>
12
+
13
+" INSTALL instructions:
14
+" install tiger-ftdetect.vim
15
+" $ mkdir -p ~/.vim/syntax
16
+" $ cp tiger.vim ~/.vim/syntax
17
+
18
+" For version 5.x: Clear all syntax items
19
+" For version 6.x: Quit when a syntax file was already loaded
20
+if version < 600
21
+  syntax clear
22
+elseif exists("b:current_syntax")
23
+  finish
24
+endif
25
+
26
+" A bunch of useful Tiger keywords
27
+syn keyword	tigerStatement		break let in end of
28
+syn keyword	tigerConditional	if then else
29
+syn keyword	tigerRepeat		while for to do
30
+
31
+syn keyword	tigerTodo		contained TODO FIXME XXX NOTE[S]
32
+
33
+" tigerCommentGroup allows adding matches for special things in comments
34
+syn cluster	tigerCommentGroup	contains=tigerTodo
35
+
36
+" String constants (Note: there is no character constants in Tiger)
37
+" Highlight special characters (those which have a backslash) differently
38
+syn match	tigerSpecial		display contained "\\\(x\x\{2}\|\o\{3}\|a\|b\|f\|n\|r\|t\|v\|\\\|\"\)"
39
+" Highlight invalid escapes
40
+syn match	tigerSpecialError	display contained "\\[^0-9abfnrtvx\\\"]"
41
+syn match	tigerSpecialError	display contained "\\x[^0-9a-fA-F]"
42
+syn match	tigerSpecialError	display contained "\\x\x[^0-9a-fA-F]"
43
+syn region	tigerString		start=+L\="+ skip=+\\\\\|\\"+ end=+"+ contains=tigerSpecial,tigerSpecialError,Spell
44
+
45
+syn match	tigerSpaceError		display excludenl "\s\+$"
46
+syn match	tigerSpaceError		display " \+\t"me=e-1
47
+
48
+"catch errors caused by wrong parenthesis and brackets
49
+syn cluster	tigerParenGroup		contains=tigerParenError,tigerSpecial,tigerSpecialError,tigerCommentGroup,tigerNumber,tigerNumbersCom
50
+syn region	tigerParen		transparent start='(' end=')' contains=ALLBUT,@tigerParenGroup,tigerErrInBracket,Spell
51
+syn match	tigerParenError		display "[\])]"
52
+syn match	tigerErrInParen		display contained "[\]]"
53
+syn region	tigerBracket		transparent start='\[' end=']' contains=ALLBUT,@tigerParenGroup,tigerErrInParen,Spell
54
+syn match	tigerErrInBracket	display contained "[);{}]"
55
+
56
+" integer number (Note: octal or hexadecimal literals don't exist in Tiger.)
57
+"                (Numbers starting with a 0 are not considered in a special way)
58
+syn case ignore
59
+syn match	tigerNumbers		display transparent "\<\d\|\.\d" contains=tigerNumber
60
+" Same, but without octal error (for comments)
61
+syn match	tigerNumbersCom		display contained transparent "\<\d\|\.\d" contains=tigerNumber
62
+syn match	tigerNumber		display contained "\d\+\(u\=l\{0,2}\|ll\=u\)\>"
63
+syn case match
64
+
65
+syn region	tigerComment		matchgroup=tigerCommentStart start="/\*" end="\*/" contains=@tigerCommentGroup,tigerComment,@Spell
66
+
67
+syn keyword	tigerType		int string
68
+
69
+syn keyword	tigerStructure		type array
70
+syn keyword	tigerStorageClass	var
71
+syn keyword	tigerDecl		function primitive
72
+syn keyword	tigerImport		import
73
+syn keyword	tigerNil		nil
74
+syn keyword	tigerBuiltin		chr concat exit flush getchar not ord print print_err print_int size strcmp streq substring
75
+
76
+" Define the default highlighting.
77
+" For version 5.7 and earlier: only when not done already
78
+" For version 5.8 and later: only when an item doesn't have highlighting yet
79
+if version >= 508 || !exists("did_tiger_syn_inits")
80
+  if version < 508
81
+    let did_tiger_syn_inits = 1
82
+    command -nargs=+ HiLink hi link <args>
83
+  else
84
+    command -nargs=+ HiLink hi def link <args>
85
+  endif
86
+
87
+  HiLink tigerCommentL		tigerComment
88
+  HiLink tigerCommentStart	tigerComment
89
+  HiLink tigerConditional	Conditional
90
+  HiLink tigerRepeat		Repeat
91
+  HiLink tigerNumber		Number
92
+  HiLink tigerParenError	tigerError
93
+  HiLink tigerErrInParen	tigerError
94
+  HiLink tigerErrInBracket	tigerError
95
+  HiLink tigerSpaceError	tigerError
96
+  HiLink tigerSpecialError	tigerError
97
+  HiLink tigerStructure		Structure
98
+  HiLink tigerStorageClass	StorageClass
99
+  HiLink tigerDefine		Macro
100
+  HiLink tigerError		Error
101
+  HiLink tigerStatement		Statement
102
+  HiLink tigerType		Type
103
+  HiLink tigerConstant		Constant
104
+  HiLink tigerString		String
105
+  HiLink tigerComment		Comment
106
+  HiLink tigerSpecial		SpecialChar
107
+  HiLink tigerTodo		Todo
108
+  HiLink tigerDecl		Type
109
+  HiLink tigerImport            Include
110
+  HiLink tigerNil               Constant
111
+  HiLink tigerBuiltin		Define
112
+
113
+  delcommand HiLink
114
+endif
115
+
116
+let b:current_syntax = "tiger"
117
+
118
+" vim: ts=8

+ 5
- 0
vim/plugin/vim-syntax-extra.vim View File

@@ -0,0 +1,5 @@
1
+" flex
2
+autocmd BufRead,BufNewFile *.fl,*.flex,*.ll,*.l,*.lm setlocal ft=lex
3
+
4
+" bison
5
+autocmd BufRead,BufNewFile *.yy,*.y,*.ypp,*.ym setlocal ft=yacc

+ 46
- 0
vimrc View File

@@ -0,0 +1,46 @@
1
+set number
2
+syntax on
3
+set mouse=a
4
+highlight ExtraWhitespace ctermbg=red guibg=red
5
+match ExtraWhitespace /\s\+$/
6
+set colorcolumn=80
7
+highlight colorcolumn ctermbg=green guibg=green
8
+set hlsearch
9
+nnoremap <F3> :noh<CR>
10
+nnoremap <F4> :A<CR>
11
+
12
+set nocompatible
13
+set expandtab
14
+set shiftwidth=2
15
+set softtabstop=2
16
+set smarttab
17
+set tabstop=8
18
+
19
+"plugin
20
+filetype off
21
+set rtp+=~/.vim/bundle/vundle
22
+call vundle#rc()
23
+Plugin 'gmarik/Vundle.vim'
24
+Plugin 'scrooloose/syntastic'
25
+Plugin 'myusuf3/numbers.vim'
26
+
27
+let g:syntastic_c_compiler='clang'          " Use clang instead of gcc
28
+let g:syntastic_c_compiler_options='-Wall -Wextra -pedantic -std=c99'
29
+let g:syntastic_c_check_header=1            " Check headers in c
30
+let g:syntastic_cpp_compiler='clang++'      " Use clang++ instead of g++
31
+let g:syntastic_cpp_compiler_options='-Wall -Wextra -pedantic -std=c++11'
32
+let g:syntastic_cpp_check_header=1          " Check headers in c++
33
+let g:syntastic_ocaml_use_ocamlc=1          " Use ocamlc instead of ocamlopt
34
+
35
+let g:numbers_exclude=[ 'nerdtree', 'undotree', 'diffpanel', 'tagbar' ]
36
+filetype plugin indent on
37
+autocmd FileType * setlocal formatoptions-=c formatoptions-=r formatoptions-=o
38
+
39
+set relativenumber
40
+set number
41
+let mapleader=","
42
+nnoremap <leader>n :NumbersToggle<CR>
43
+
44
+inoremap <Nul> <C-n>
45
+noremap <expr> <silent> <Home> col('.') == match(getline('.'),'\S')+1 ? '0' : '^'
46
+imap <silent> <Home> <C-O><Home>

Loading…
Cancel
Save