From e53c625e08a40d72ce564b27739e2bc0394baa14 Mon Sep 17 00:00:00 2001 From: Marcin Wozniak Date: Sat, 9 May 2020 13:43:39 +0200 Subject: [PATCH] first commit --- .local/bin/backup-mc | 1 + .local/bin/bin-cp | 8 + .local/bin/cleaner | 15 + .local/bin/cleanertmp | 5 + .local/bin/cmus-shell | 4 + .local/bin/dmenumount | 59 + .local/bin/dmenuumount | 41 + .local/bin/dmenuunicode | 18 + .local/bin/eix-repos-sync | 2 + .local/bin/f2py | 8 + .local/bin/f2py3 | 8 + .local/bin/f2py3.6 | 8 + .local/bin/geoip | 3 + .local/bin/getforecast | 15 + .local/bin/git-init-folder | 11 + .local/bin/hosts-update | 11 + .local/bin/mailsync | 26 + .local/bin/minecraft-launcher | 1 + .local/bin/mouse-set | 10 + .local/bin/night | 2 + .local/bin/obsh | 22 + .local/bin/rasp | 5 + .local/bin/screen-switcher | 12 + .local/bin/screenshot | 7 + .local/bin/screenshot-area | 7 + .local/bin/set-wallpaper | 7 + .local/bin/shut-sup-rest | 13 + .local/bin/speedtest-cli | 1944 ++++++++++++++++++++ .local/bin/ssh-permissions | 10 + .local/bin/stream-twitch | 2 + .local/bin/stream-youtube | 2 + .local/bin/suspend-at-time | 15 + .local/bin/temp | 3 + .local/bin/term-wmi | 1 + .local/bin/twitch | 2 + .local/bin/update | 2 + .local/bin/update-kernel | 108 ++ .local/bin/welcomer | 54 + .local/bin/welcomer-serwer | 33 + .local/bin/wheel | 8 + .local/bin/wylaczoff | 5 + .local/bin/yatqa | 1 + .local/bin/yt-mp3 | 2 + .local/bin/yt-video | 2 + .tmux.conf | 36 + .vim/.netrwhist | 3 + .vim/autoload/plug.vim | 2591 +++++++++++++++++++++++++++ .vim/plugged/goyo.vim | 1 + .vim/plugged/nerdtree | 1 + .vim/plugged/vim-latex-live-preview | 1 + .vim/plugged/vimtex | 1 + .viminfo | 1818 +++++++++++++++++++ .vimrc | 115 ++ .zshrc | 86 + 54 files changed, 7176 insertions(+) create mode 100755 .local/bin/backup-mc create mode 100755 .local/bin/bin-cp create mode 100755 .local/bin/cleaner create mode 100755 .local/bin/cleanertmp create mode 100755 .local/bin/cmus-shell create mode 100755 .local/bin/dmenumount create mode 100755 .local/bin/dmenuumount create mode 100755 .local/bin/dmenuunicode create mode 100755 .local/bin/eix-repos-sync create mode 100755 .local/bin/f2py create mode 100755 .local/bin/f2py3 create mode 100755 .local/bin/f2py3.6 create mode 100755 .local/bin/geoip create mode 100755 .local/bin/getforecast create mode 100755 .local/bin/git-init-folder create mode 100755 .local/bin/hosts-update create mode 100755 .local/bin/mailsync create mode 100755 .local/bin/minecraft-launcher create mode 100755 .local/bin/mouse-set create mode 100755 .local/bin/night create mode 100755 .local/bin/obsh create mode 100755 .local/bin/rasp create mode 100755 .local/bin/screen-switcher create mode 100755 .local/bin/screenshot create mode 100755 .local/bin/screenshot-area create mode 100755 .local/bin/set-wallpaper create mode 100755 .local/bin/shut-sup-rest create mode 100755 .local/bin/speedtest-cli create mode 100755 .local/bin/ssh-permissions create mode 100755 .local/bin/stream-twitch create mode 100755 .local/bin/stream-youtube create mode 100755 .local/bin/suspend-at-time create mode 100755 .local/bin/temp create mode 100755 .local/bin/term-wmi create mode 100755 .local/bin/twitch create mode 100755 .local/bin/update create mode 100755 .local/bin/update-kernel create mode 100755 .local/bin/welcomer create mode 100755 .local/bin/welcomer-serwer create mode 100755 .local/bin/wheel create mode 100755 .local/bin/wylaczoff create mode 100755 .local/bin/yatqa create mode 100755 .local/bin/yt-mp3 create mode 100755 .local/bin/yt-video create mode 100644 .tmux.conf create mode 100644 .vim/.netrwhist create mode 100644 .vim/autoload/plug.vim create mode 160000 .vim/plugged/goyo.vim create mode 160000 .vim/plugged/nerdtree create mode 160000 .vim/plugged/vim-latex-live-preview create mode 160000 .vim/plugged/vimtex create mode 100644 .viminfo create mode 100644 .vimrc create mode 100644 .zshrc diff --git a/.local/bin/backup-mc b/.local/bin/backup-mc new file mode 100755 index 0000000..f9560f0 --- /dev/null +++ b/.local/bin/backup-mc @@ -0,0 +1 @@ +sudo mkdir -p /mnt/backup/mcserver/$(/bin/date +%Y-%m-%d); sudo chown yorune:yorune -R /mnt/backup/mcserver/$(/bin/date +%Y-%m-%d); sudo cp -rv /home/yorune/mcserver/* /mnt/backup/mcserver/$(/bin/date +%Y-%m-%d) diff --git a/.local/bin/bin-cp b/.local/bin/bin-cp new file mode 100755 index 0000000..725956c --- /dev/null +++ b/.local/bin/bin-cp @@ -0,0 +1,8 @@ +#!/bin/bash +chmod +x * +chown -R yorune: * +sudo cp -pr * /bin/ +#sudo cp /etc/bash.bashrc ../configs +#cp /home/yorune/Arch/configs/zshrc /home/yorune/.zshrc +#cp /home/yorune/Arch/configs/vimrc /home/yorune/.vimrc +echo DONE!! diff --git a/.local/bin/cleaner b/.local/bin/cleaner new file mode 100755 index 0000000..c115d50 --- /dev/null +++ b/.local/bin/cleaner @@ -0,0 +1,15 @@ +#!/bin/bash +sudo rm -rf /var/tmp/portage/* +sudo rm -rf /var/tmp/binpkgs/* +sudo rm -rf /var/tmp/genkernel/* +sudo rm -rf /tmp/* +sudo rm -rf /var/cache/genkernel/* +sudo emerge -a --depclean +sudo emerge -a @preserved-rebuild +sudo eclean -C -q packages +sudo eclean -C -q -d -t1w distfiles +sudo revdep-rebuild +sudo perl-cleaner --all +sudo etc-update +sudo env-update +source /etc/profile diff --git a/.local/bin/cleanertmp b/.local/bin/cleanertmp new file mode 100755 index 0000000..ee3818c --- /dev/null +++ b/.local/bin/cleanertmp @@ -0,0 +1,5 @@ +sudo rm -rf /var/tmp/portage/* +sudo rm -rf /var/tmp/binpkgs/* +sudo rm -rf /var/tmp/genkernel/* +sudo rm -rf /tmp/* +sudo rm -rf /var/cache/genkernel/* diff --git a/.local/bin/cmus-shell b/.local/bin/cmus-shell new file mode 100755 index 0000000..35a46ef --- /dev/null +++ b/.local/bin/cmus-shell @@ -0,0 +1,4 @@ +#!/bin/bash +if ! screen -r -D cmus >/dev/null ; then + screen -S cmus /usr/bin/cmus "$@" +fi diff --git a/.local/bin/dmenumount b/.local/bin/dmenumount new file mode 100755 index 0000000..dcdf08f --- /dev/null +++ b/.local/bin/dmenumount @@ -0,0 +1,59 @@ +#!/bin/sh +# Gives a dmenu prompt to mount unmounted drives. +# If they're in /etc/fstab, they'll be mounted automatically. +# Otherwise, you'll be prompted to give a mountpoint from already existsing directories. +# If you input a novel directory, it will prompt you to create that directory. + +getmount() { \ + [ -z "$chosen" ] && exit 1 + mp="$(find $1 | dmenu -i -p "Type in mount point.")" + [ "$mp" = "" ] && exit 1 + if [ ! -d "$mp" ]; then + mkdiryn=$(printf "No\\nYes" | dmenu -i -p "$mp does not exist. Create it?") + [ "$mkdiryn" = "Yes" ] && (mkdir -p "$mp" || sudo -A mkdir -p "$mp") + fi + } + +mountusb() { \ + chosen="$(echo "$usbdrives" | dmenu -i -p "Mount which drive?" | awk '{print $1}')" + sudo -A mount "$chosen" && notify-send "💻 USB mounting" "$chosen mounted." && exit 0 + alreadymounted=$(lsblk -nrpo "name,type,mountpoint" | awk '$2=="part"&&$3!~/\/boot|\/home$|SWAP/&&length($3)>1{printf "-not \( -path *%s -prune \) \ \n",$3}') + getmount "/mnt /media -maxdepth 5 -type d $alreadymounted" + partitiontype="$(lsblk -no "fstype" "$chosen")" + case "$partitiontype" in + "vfat") sudo -A mount -t vfat "$chosen" "$mp" -o rw,umask=0000;; + *) sudo -A mount "$chosen" "$mp"; user="$(whoami)"; ug="$(groups | awk '{print $1}')"; sudo -A chown "$user":"$ug" 741 "$mp";; + esac + notify-send "💻 USB mounting" "$chosen mounted to $mp." + } + +mountandroid() { \ + chosen=$(echo "$anddrives" | dmenu -i -p "Which Android device?" | cut -d : -f 1) + getmount "/media -maxdepth 3 -type d" + sudo simple-mtpfs --device "$chosen" "$mp" + notify-send "🤖 Android Mounting" "Android device mounted to $mp." + } + +asktype() { \ + case $(printf "USB\\nAndroid" | dmenu -i -p "Mount a USB drive or Android device?") in + USB) mountusb ;; + Android) mountandroid ;; + esac + } + +anddrives=$(simple-mtpfs -l 2>/dev/null) +usbdrives="$(lsblk -rpo "name,type,size,mountpoint" | awk '$2=="part"&&$4==""{printf "%s (%s)\n",$1,$3}')" + +if [ -z "$usbdrives" ]; then + [ -z "$anddrives" ] && echo "No USB drive or Android device detected" && exit + echo "Android device(s) detected." + mountandroid +else + if [ -z "$anddrives" ]; then + echo "USB drive(s) detected." + mountusb + else + echo "Mountable USB drive(s) and Android device(s) detected." + asktype + fi +fi diff --git a/.local/bin/dmenuumount b/.local/bin/dmenuumount new file mode 100755 index 0000000..dee53e7 --- /dev/null +++ b/.local/bin/dmenuumount @@ -0,0 +1,41 @@ +#!/bin/sh +# A dmenu prompt to unmount drives. +# Provides you with mounted partitions, select one to unmount. +# Drives mounted at /, /boot and /home will not be options to unmount. + +unmountusb() { + [ -z "$drives" ] && exit + chosen=$(echo "$drives" | dmenu -i -p "Unmount which drive?" | awk '{print $1}') + [ -z "$chosen" ] && exit + sudo -A umount "$chosen" && notify-send "💻 USB unmounting" "$chosen unmounted." + } + +unmountandroid() { \ + chosen=$(awk '/simple-mtpfs/ {print $2}' /etc/mtab | dmenu -i -p "Unmount which device?") + [ -z "$chosen" ] && exit + sudo -A umount -l "$chosen" && notify-send "🤖 Android unmounting" "$chosen unmounted." + } + +asktype() { \ + case "$(printf "USB\\nAndroid" | dmenu -i -p "Unmount a USB drive or Android device?")" in + USB) unmountusb ;; + Android) unmountandroid ;; + esac + } + +drives=$(lsblk -nrpo "name,type,size,mountpoint" | awk '$2=="part"&&$4!~/\/boot|\/home$|SWAP/&&length($4)>1{printf "%s (%s)\n",$4,$3}') + +if ! grep simple-mtpfs /etc/mtab; then + [ -z "$drives" ] && echo "No drives to unmount." && exit + echo "Unmountable USB drive detected." + unmountusb +else + if [ -z "$drives" ] + then + echo "Unmountable Android device detected." + unmountandroid + else + echo "Unmountable USB drive(s) and Android device(s) detected." + asktype + fi +fi diff --git a/.local/bin/dmenuunicode b/.local/bin/dmenuunicode new file mode 100755 index 0000000..6b1a175 --- /dev/null +++ b/.local/bin/dmenuunicode @@ -0,0 +1,18 @@ +#!/bin/sh +# Give dmenu list of all unicode characters to copy. +# Shows the selected character in dunst if running. + +# Must have xclip installed to even show menu. +xclip -h >/dev/null || exit + +chosen=$(grep -v "#" ~/dwm/emoji | dmenu -i -l 20 -fn Monospace-18) + +[ "$chosen" != "" ] || exit + +c=$(echo "$chosen" | sed "s/ .*//") +echo "$c" | tr -d '\n' | xclip -selection clipboard +notify-send "'$c' copied to clipboard." & + +s=$(echo "$chosen" | sed "s/.*; //" | awk '{print $1}') +echo "$s" | tr -d '\n' | xclip +notify-send "'$s' copied to primary." & diff --git a/.local/bin/eix-repos-sync b/.local/bin/eix-repos-sync new file mode 100755 index 0000000..185d16b --- /dev/null +++ b/.local/bin/eix-repos-sync @@ -0,0 +1,2 @@ +#!/bin/bash +for i in /usr/repos/*/.git; do ( echo $i; cd $i/..; sudo git pull; ); done diff --git a/.local/bin/f2py b/.local/bin/f2py new file mode 100755 index 0000000..bafb207 --- /dev/null +++ b/.local/bin/f2py @@ -0,0 +1,8 @@ +#!/usr/bin/python3.6 +# -*- coding: utf-8 -*- +import re +import sys +from numpy.f2py.f2py2e import main +if __name__ == '__main__': + sys.argv[0] = re.sub(r'(-script\.pyw|\.exe)?$', '', sys.argv[0]) + sys.exit(main()) diff --git a/.local/bin/f2py3 b/.local/bin/f2py3 new file mode 100755 index 0000000..bafb207 --- /dev/null +++ b/.local/bin/f2py3 @@ -0,0 +1,8 @@ +#!/usr/bin/python3.6 +# -*- coding: utf-8 -*- +import re +import sys +from numpy.f2py.f2py2e import main +if __name__ == '__main__': + sys.argv[0] = re.sub(r'(-script\.pyw|\.exe)?$', '', sys.argv[0]) + sys.exit(main()) diff --git a/.local/bin/f2py3.6 b/.local/bin/f2py3.6 new file mode 100755 index 0000000..bafb207 --- /dev/null +++ b/.local/bin/f2py3.6 @@ -0,0 +1,8 @@ +#!/usr/bin/python3.6 +# -*- coding: utf-8 -*- +import re +import sys +from numpy.f2py.f2py2e import main +if __name__ == '__main__': + sys.argv[0] = re.sub(r'(-script\.pyw|\.exe)?$', '', sys.argv[0]) + sys.exit(main()) diff --git a/.local/bin/geoip b/.local/bin/geoip new file mode 100755 index 0000000..885fb84 --- /dev/null +++ b/.local/bin/geoip @@ -0,0 +1,3 @@ +#!/bin/bash + +curl -s ipinfo.io/$1 diff --git a/.local/bin/getforecast b/.local/bin/getforecast new file mode 100755 index 0000000..1658110 --- /dev/null +++ b/.local/bin/getforecast @@ -0,0 +1,15 @@ +#!/bin/sh +# Updates weather forecast + +FILE="$HOME/.config/.weatherreport.tmp" +FILER="$HOME/.config/weatherreport" + +curl -s --max-time 10 "wttr.in/$location" > $FILE + +if [ -s "$FILE" ] +then + mv $FILE $FILER +# notify-send " Weather" "The weather forecast has been updated." +else + rm $FILE +fi diff --git a/.local/bin/git-init-folder b/.local/bin/git-init-folder new file mode 100755 index 0000000..1c9863d --- /dev/null +++ b/.local/bin/git-init-folder @@ -0,0 +1,11 @@ +#!/bin/bash + +mkdir $1 +cd $1 +git init +touch README.md +git add README.md +git commit -m "first commit" +curl -u 'linux923344' https://api.github.com/user/repos -d '{"name":"'$1'"}' +git remote add origin git@github.com:linux923344/$1.git +git push -u origin master diff --git a/.local/bin/hosts-update b/.local/bin/hosts-update new file mode 100755 index 0000000..27071a6 --- /dev/null +++ b/.local/bin/hosts-update @@ -0,0 +1,11 @@ +#!/bin/bash +rm -rf /tmp/steven /tmp/luke /tmp/hosts +wget -O /tmp/steven https://raw.githubusercontent.com/StevenBlack/hosts/master/alternates/fakenews-gambling-porn/hosts + +wget -O /tmp/luke https://raw.githubusercontent.com/LukeSmithxyz/etc/master/ips + +cat /tmp/luke >> /tmp/steven + +cat /tmp/steven | sort | uniq -d | sed '/^#/d' >> /tmp/hosts + +sudo mv /tmp/hosts /etc/hosts diff --git a/.local/bin/mailsync b/.local/bin/mailsync new file mode 100755 index 0000000..ad5e9e0 --- /dev/null +++ b/.local/bin/mailsync @@ -0,0 +1,26 @@ +#!/usr/bin/env sh +# Sync mail and give notification if there is new mail. + +# Checks for internet connection and set notification script. +ping -q -c 1 1.1.1.1 > /dev/null || exit +command -v notify-send >/dev/null || echo "Note that \`libnotify\` or \`libnotify-send\` should be installed for pop-up mail notifications with this script." + +export DISPLAY=:0.0 +# IKONKA SYNC ##echo " 🔃" > /tmp/imapsyncicon_$USER +pkill -RTMIN+12 i3blocks + +# Run mbsync. You can feed this script different settings. +mbsync -a + +# IKONKA SYNC #rm -f /tmp/imapsyncicon_$USER +pkill -RTMIN+12 i3blocks + +RESULT=$(echo "$(du -a ~/.mailbox/*/inbox/new/* 2>/dev/null | sed -n '$=')$(cat /tmp/imapsyncicon_$USER 2>/dev/null)") +#if [ -z $RESULT ]; then +# echo "" +#else +# notify-send "mutt-wizard" "📬 new mail(s)" +#fi + +#Create a touch file that indicates the time of the last run of mailsync +touch "$HOME/.mutt/.mailsynclastrun" diff --git a/.local/bin/minecraft-launcher b/.local/bin/minecraft-launcher new file mode 100755 index 0000000..0b6840e --- /dev/null +++ b/.local/bin/minecraft-launcher @@ -0,0 +1 @@ +java -Xmx1024M -Xms1024M -jar /home/yorune/Linux/apps/TLauncher-MCL.jar diff --git a/.local/bin/mouse-set b/.local/bin/mouse-set new file mode 100755 index 0000000..8940eba --- /dev/null +++ b/.local/bin/mouse-set @@ -0,0 +1,10 @@ +#!/bin/bash +choices="Off\nCycle" +chosen=$(echo -e "$choices" | dmenu -i) + +mouse=$(sudo ratbag-command list | awk '{print $1}' | sed 's/://') + +case "$chosen" in + Off) sudo ratbag-command led 0 set mode off $mouse ;; + Cycle) sudo ratbag-command led 0 set mode cycle $mouse && sudo ratbag-command led 0 set rate 25000 $mouse ;; +esac diff --git a/.local/bin/night b/.local/bin/night new file mode 100755 index 0000000..8814e36 --- /dev/null +++ b/.local/bin/night @@ -0,0 +1,2 @@ +#!/bin/bash +redshift -l 52.2327:18.3036 -t 6500:3200& diff --git a/.local/bin/obsh b/.local/bin/obsh new file mode 100755 index 0000000..7cd9131 --- /dev/null +++ b/.local/bin/obsh @@ -0,0 +1,22 @@ +#! /bin/bash +broadcast=$(ip a | awk '$1 == "inet" && $4 !~ /^127/ { print $4"/24" }' | uniq) + +RED='\033[0;31m' +GRAY='\033[0;37m' +GREEN='\033[0;32m' +NC='\033[0m' + +clear +printf "${GRAY}Executing nmap on the subnets: ${RED}\n$broadcast\n" +candidates=$( +for brdip in ${broadcast}; do + nmap -sP $brdip | awk '$2 == "scan" { print $5 }' +done) +printf "${GRAY}\nFound the following candidates: ${GREEN}\n$candidates\n" +for ip in ${candidates}; do + printf "${GRAY}\nProbing $ip...\n${NC}" + ssh -q root@$ip +done +clear +echo "Nothing found" + diff --git a/.local/bin/rasp b/.local/bin/rasp new file mode 100755 index 0000000..412a215 --- /dev/null +++ b/.local/bin/rasp @@ -0,0 +1,5 @@ +#!/bin/bash +sudo chown yorune: /mnt/rasp +sshfs root@192.168.0.222:/mnt/ /mnt/rasp/ +sleep 10 +cd /mnt/rasp diff --git a/.local/bin/screen-switcher b/.local/bin/screen-switcher new file mode 100755 index 0000000..616eaf0 --- /dev/null +++ b/.local/bin/screen-switcher @@ -0,0 +1,12 @@ +#!/bin/bash +choices="Left\nRight\nDuplicated\nHDMI\nMonitor\n" + +chosen=$(echo -e "$choices" | dmenu -i) + +case "$chosen" in + Monitor) mons -o ;; + Duplicated) mons -d ;; + Left) mons -e left ;; + Right) mons -e right ;; + HDMI) mons -s +esac diff --git a/.local/bin/screenshot b/.local/bin/screenshot new file mode 100755 index 0000000..4b86b31 --- /dev/null +++ b/.local/bin/screenshot @@ -0,0 +1,7 @@ +FILE="/tmp/`date +%Y%m%d-%H.%M.%S.png`" +NAME=$(date +%s | sha256sum | base64 | head -c 20 ; echo) + +gnome-screenshot -f "$FILE" +rsync -avz --delete $FILE -e "ssh -p 2223" root@209.250.255.224:/var/www/yorune.pl/u/$NAME.png && + +echo -e "https://yorune.pl/u/$NAME.png" | xclip -selection clipboard && notify-send "Screenshot has been updated" diff --git a/.local/bin/screenshot-area b/.local/bin/screenshot-area new file mode 100755 index 0000000..7bcfd13 --- /dev/null +++ b/.local/bin/screenshot-area @@ -0,0 +1,7 @@ +FILE="/tmp/`date +%Y%m%d-%H.%M.%S.png`" +NAME=$(date +%s | sha256sum | base64 | head -c 20 ; echo) + +gnome-screenshot --area -f "$FILE" +rsync -avz --delete $FILE -e "ssh -p 2223" root@209.250.255.224:/var/www/yorune.pl/u/$NAME.png && + +echo -e "https://yorune.pl/u/$NAME.png" | xclip -selection clipboard && notify-send "Screenshot has been updated" diff --git a/.local/bin/set-wallpaper b/.local/bin/set-wallpaper new file mode 100755 index 0000000..daddc39 --- /dev/null +++ b/.local/bin/set-wallpaper @@ -0,0 +1,7 @@ +#!/bin/bash + +cp $1 ~/.wall.jpg +#feh --bg-scale /home/yorune/.wall.jpg +feh --bg-fill /home/yorune/.wall.jpg +#wal -i $1 -o wal-set +notify-send "Wallpaper changed" diff --git a/.local/bin/shut-sup-rest b/.local/bin/shut-sup-rest new file mode 100755 index 0000000..5e1d0cb --- /dev/null +++ b/.local/bin/shut-sup-rest @@ -0,0 +1,13 @@ +#!/bin/bash +choices="Lock\nSuspend\nReboot\nShutdown" + +chosen=$(echo -e "$choices" | dmenu -i) + +case "$chosen" in + Lock) slock ;; + Suspend) sudo pm-suspend && slock ;; + #Suspend) sudo systemctl suspend && slock ;; + #Suspend) sudo systemctl suspend && locki3 ;; + Reboot) sudo reboot ;; + Shutdown) sudo shutdown -h now ;; +esac diff --git a/.local/bin/speedtest-cli b/.local/bin/speedtest-cli new file mode 100755 index 0000000..e0d15e9 --- /dev/null +++ b/.local/bin/speedtest-cli @@ -0,0 +1,1944 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- +# Copyright 2012 Matt Martz +# All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); you may +# not use this file except in compliance with the License. You may obtain +# a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT +# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the +# License for the specific language governing permissions and limitations +# under the License. + +import os +import re +import csv +import sys +import math +import errno +import signal +import socket +import timeit +import datetime +import platform +import threading +import xml.parsers.expat + +try: + import gzip + GZIP_BASE = gzip.GzipFile +except ImportError: + gzip = None + GZIP_BASE = object + +__version__ = '2.1.1' + + +class FakeShutdownEvent(object): + """Class to fake a threading.Event.isSet so that users of this module + are not required to register their own threading.Event() + """ + + @staticmethod + def isSet(): + "Dummy method to always return false""" + return False + + +# Some global variables we use +DEBUG = False +_GLOBAL_DEFAULT_TIMEOUT = object() + +# Begin import game to handle Python 2 and Python 3 +try: + import json +except ImportError: + try: + import simplejson as json + except ImportError: + json = None + +try: + import xml.etree.cElementTree as ET +except ImportError: + try: + import xml.etree.ElementTree as ET + except ImportError: + from xml.dom import minidom as DOM + from xml.parsers.expat import ExpatError + ET = None + +try: + from urllib2 import (urlopen, Request, HTTPError, URLError, + AbstractHTTPHandler, ProxyHandler, + HTTPDefaultErrorHandler, HTTPRedirectHandler, + HTTPErrorProcessor, OpenerDirector) +except ImportError: + from urllib.request import (urlopen, Request, HTTPError, URLError, + AbstractHTTPHandler, ProxyHandler, + HTTPDefaultErrorHandler, HTTPRedirectHandler, + HTTPErrorProcessor, OpenerDirector) + +try: + from httplib import HTTPConnection, BadStatusLine +except ImportError: + from http.client import HTTPConnection, BadStatusLine + +try: + from httplib import HTTPSConnection +except ImportError: + try: + from http.client import HTTPSConnection + except ImportError: + HTTPSConnection = None + +try: + from httplib import FakeSocket +except ImportError: + FakeSocket = None + +try: + from Queue import Queue +except ImportError: + from queue import Queue + +try: + from urlparse import urlparse +except ImportError: + from urllib.parse import urlparse + +try: + from urlparse import parse_qs +except ImportError: + try: + from urllib.parse import parse_qs + except ImportError: + from cgi import parse_qs + +try: + from hashlib import md5 +except ImportError: + from md5 import md5 + +try: + from argparse import ArgumentParser as ArgParser + from argparse import SUPPRESS as ARG_SUPPRESS + PARSER_TYPE_INT = int + PARSER_TYPE_STR = str + PARSER_TYPE_FLOAT = float +except ImportError: + from optparse import OptionParser as ArgParser + from optparse import SUPPRESS_HELP as ARG_SUPPRESS + PARSER_TYPE_INT = 'int' + PARSER_TYPE_STR = 'string' + PARSER_TYPE_FLOAT = 'float' + +try: + from cStringIO import StringIO + BytesIO = None +except ImportError: + try: + from StringIO import StringIO + BytesIO = None + except ImportError: + from io import StringIO, BytesIO + +try: + import __builtin__ +except ImportError: + import builtins + from io import TextIOWrapper, FileIO + + class _Py3Utf8Output(TextIOWrapper): + """UTF-8 encoded wrapper around stdout for py3, to override + ASCII stdout + """ + def __init__(self, f, **kwargs): + buf = FileIO(f.fileno(), 'w') + super(_Py3Utf8Output, self).__init__( + buf, + encoding='utf8', + errors='strict' + ) + + def write(self, s): + super(_Py3Utf8Output, self).write(s) + self.flush() + + _py3_print = getattr(builtins, 'print') + try: + _py3_utf8_stdout = _Py3Utf8Output(sys.stdout) + _py3_utf8_stderr = _Py3Utf8Output(sys.stderr) + except OSError: + # sys.stdout/sys.stderr is not a compatible stdout/stderr object + # just use it and hope things go ok + _py3_utf8_stdout = sys.stdout + _py3_utf8_stderr = sys.stderr + + def to_utf8(v): + """No-op encode to utf-8 for py3""" + return v + + def print_(*args, **kwargs): + """Wrapper function for py3 to print, with a utf-8 encoded stdout""" + if kwargs.get('file') == sys.stderr: + kwargs['file'] = _py3_utf8_stderr + else: + kwargs['file'] = kwargs.get('file', _py3_utf8_stdout) + _py3_print(*args, **kwargs) +else: + del __builtin__ + + def to_utf8(v): + """Encode value to utf-8 if possible for py2""" + try: + return v.encode('utf8', 'strict') + except AttributeError: + return v + + def print_(*args, **kwargs): + """The new-style print function for Python 2.4 and 2.5. + + Taken from https://pypi.python.org/pypi/six/ + + Modified to set encoding to UTF-8 always, and to flush after write + """ + fp = kwargs.pop("file", sys.stdout) + if fp is None: + return + + def write(data): + if not isinstance(data, basestring): + data = str(data) + # If the file has an encoding, encode unicode with it. + encoding = 'utf8' # Always trust UTF-8 for output + if (isinstance(fp, file) and + isinstance(data, unicode) and + encoding is not None): + errors = getattr(fp, "errors", None) + if errors is None: + errors = "strict" + data = data.encode(encoding, errors) + fp.write(data) + fp.flush() + want_unicode = False + sep = kwargs.pop("sep", None) + if sep is not None: + if isinstance(sep, unicode): + want_unicode = True + elif not isinstance(sep, str): + raise TypeError("sep must be None or a string") + end = kwargs.pop("end", None) + if end is not None: + if isinstance(end, unicode): + want_unicode = True + elif not isinstance(end, str): + raise TypeError("end must be None or a string") + if kwargs: + raise TypeError("invalid keyword arguments to print()") + if not want_unicode: + for arg in args: + if isinstance(arg, unicode): + want_unicode = True + break + if want_unicode: + newline = unicode("\n") + space = unicode(" ") + else: + newline = "\n" + space = " " + if sep is None: + sep = space + if end is None: + end = newline + for i, arg in enumerate(args): + if i: + write(sep) + write(arg) + write(end) + + +# Exception "constants" to support Python 2 through Python 3 +try: + import ssl + try: + CERT_ERROR = (ssl.CertificateError,) + except AttributeError: + CERT_ERROR = tuple() + + HTTP_ERRORS = ( + (HTTPError, URLError, socket.error, ssl.SSLError, BadStatusLine) + + CERT_ERROR + ) +except ImportError: + ssl = None + HTTP_ERRORS = (HTTPError, URLError, socket.error, BadStatusLine) + + +class SpeedtestException(Exception): + """Base exception for this module""" + + +class SpeedtestCLIError(SpeedtestException): + """Generic exception for raising errors during CLI operation""" + + +class SpeedtestHTTPError(SpeedtestException): + """Base HTTP exception for this module""" + + +class SpeedtestConfigError(SpeedtestException): + """Configuration XML is invalid""" + + +class SpeedtestServersError(SpeedtestException): + """Servers XML is invalid""" + + +class ConfigRetrievalError(SpeedtestHTTPError): + """Could not retrieve config.php""" + + +class ServersRetrievalError(SpeedtestHTTPError): + """Could not retrieve speedtest-servers.php""" + + +class InvalidServerIDType(SpeedtestException): + """Server ID used for filtering was not an integer""" + + +class NoMatchedServers(SpeedtestException): + """No servers matched when filtering""" + + +class SpeedtestMiniConnectFailure(SpeedtestException): + """Could not connect to the provided speedtest mini server""" + + +class InvalidSpeedtestMiniServer(SpeedtestException): + """Server provided as a speedtest mini server does not actually appear + to be a speedtest mini server + """ + + +class ShareResultsConnectFailure(SpeedtestException): + """Could not connect to speedtest.net API to POST results""" + + +class ShareResultsSubmitFailure(SpeedtestException): + """Unable to successfully POST results to speedtest.net API after + connection + """ + + +class SpeedtestUploadTimeout(SpeedtestException): + """testlength configuration reached during upload + Used to ensure the upload halts when no additional data should be sent + """ + + +class SpeedtestBestServerFailure(SpeedtestException): + """Unable to determine best server""" + + +class SpeedtestMissingBestServer(SpeedtestException): + """get_best_server not called or not able to determine best server""" + + +def create_connection(address, timeout=_GLOBAL_DEFAULT_TIMEOUT, + source_address=None): + """Connect to *address* and return the socket object. + + Convenience function. Connect to *address* (a 2-tuple ``(host, + port)``) and return the socket object. Passing the optional + *timeout* parameter will set the timeout on the socket instance + before attempting to connect. If no *timeout* is supplied, the + global default timeout setting returned by :func:`getdefaulttimeout` + is used. If *source_address* is set it must be a tuple of (host, port) + for the socket to bind as a source address before making the connection. + An host of '' or port 0 tells the OS to use the default. + + Largely vendored from Python 2.7, modified to work with Python 2.4 + """ + + host, port = address + err = None + for res in socket.getaddrinfo(host, port, 0, socket.SOCK_STREAM): + af, socktype, proto, canonname, sa = res + sock = None + try: + sock = socket.socket(af, socktype, proto) + if timeout is not _GLOBAL_DEFAULT_TIMEOUT: + sock.settimeout(float(timeout)) + if source_address: + sock.bind(source_address) + sock.connect(sa) + return sock + + except socket.error: + err = get_exception() + if sock is not None: + sock.close() + + if err is not None: + raise err + else: + raise socket.error("getaddrinfo returns an empty list") + + +class SpeedtestHTTPConnection(HTTPConnection): + """Custom HTTPConnection to support source_address across + Python 2.4 - Python 3 + """ + def __init__(self, *args, **kwargs): + source_address = kwargs.pop('source_address', None) + timeout = kwargs.pop('timeout', 10) + + HTTPConnection.__init__(self, *args, **kwargs) + + self.source_address = source_address + self.timeout = timeout + + def connect(self): + """Connect to the host and port specified in __init__.""" + try: + self.sock = socket.create_connection( + (self.host, self.port), + self.timeout, + self.source_address + ) + except (AttributeError, TypeError): + self.sock = create_connection( + (self.host, self.port), + self.timeout, + self.source_address + ) + + +if HTTPSConnection: + class SpeedtestHTTPSConnection(HTTPSConnection, + SpeedtestHTTPConnection): + """Custom HTTPSConnection to support source_address across + Python 2.4 - Python 3 + """ + def __init__(self, *args, **kwargs): + source_address = kwargs.pop('source_address', None) + timeout = kwargs.pop('timeout', 10) + + HTTPSConnection.__init__(self, *args, **kwargs) + + self.timeout = timeout + self.source_address = source_address + + def connect(self): + "Connect to a host on a given (SSL) port." + + SpeedtestHTTPConnection.connect(self) + + if ssl: + try: + kwargs = {} + if hasattr(ssl, 'SSLContext'): + kwargs['server_hostname'] = self.host + self.sock = self._context.wrap_socket(self.sock, **kwargs) + except AttributeError: + self.sock = ssl.wrap_socket(self.sock) + try: + self.sock.server_hostname = self.host + except AttributeError: + pass + elif FakeSocket: + # Python 2.4/2.5 support + try: + self.sock = FakeSocket(self.sock, socket.ssl(self.sock)) + except AttributeError: + raise SpeedtestException( + 'This version of Python does not support HTTPS/SSL ' + 'functionality' + ) + else: + raise SpeedtestException( + 'This version of Python does not support HTTPS/SSL ' + 'functionality' + ) + + +def _build_connection(connection, source_address, timeout, context=None): + """Cross Python 2.4 - Python 3 callable to build an ``HTTPConnection`` or + ``HTTPSConnection`` with the args we need + + Called from ``http(s)_open`` methods of ``SpeedtestHTTPHandler`` or + ``SpeedtestHTTPSHandler`` + """ + def inner(host, **kwargs): + kwargs.update({ + 'source_address': source_address, + 'timeout': timeout + }) + if context: + kwargs['context'] = context + return connection(host, **kwargs) + return inner + + +class SpeedtestHTTPHandler(AbstractHTTPHandler): + """Custom ``HTTPHandler`` that can build a ``HTTPConnection`` with the + args we need for ``source_address`` and ``timeout`` + """ + def __init__(self, debuglevel=0, source_address=None, timeout=10): + AbstractHTTPHandler.__init__(self, debuglevel) + self.source_address = source_address + self.timeout = timeout + + def http_open(self, req): + return self.do_open( + _build_connection( + SpeedtestHTTPConnection, + self.source_address, + self.timeout + ), + req + ) + + http_request = AbstractHTTPHandler.do_request_ + + +class SpeedtestHTTPSHandler(AbstractHTTPHandler): + """Custom ``HTTPSHandler`` that can build a ``HTTPSConnection`` with the + args we need for ``source_address`` and ``timeout`` + """ + def __init__(self, debuglevel=0, context=None, source_address=None, + timeout=10): + AbstractHTTPHandler.__init__(self, debuglevel) + self._context = context + self.source_address = source_address + self.timeout = timeout + + def https_open(self, req): + return self.do_open( + _build_connection( + SpeedtestHTTPSConnection, + self.source_address, + self.timeout, + context=self._context, + ), + req + ) + + https_request = AbstractHTTPHandler.do_request_ + + +def build_opener(source_address=None, timeout=10): + """Function similar to ``urllib2.build_opener`` that will build + an ``OpenerDirector`` with the explicit handlers we want, + ``source_address`` for binding, ``timeout`` and our custom + `User-Agent` + """ + + printer('Timeout set to %d' % timeout, debug=True) + + if source_address: + source_address_tuple = (source_address, 0) + printer('Binding to source address: %r' % (source_address_tuple,), + debug=True) + else: + source_address_tuple = None + + handlers = [ + ProxyHandler(), + SpeedtestHTTPHandler(source_address=source_address_tuple, + timeout=timeout), + SpeedtestHTTPSHandler(source_address=source_address_tuple, + timeout=timeout), + HTTPDefaultErrorHandler(), + HTTPRedirectHandler(), + HTTPErrorProcessor() + ] + + opener = OpenerDirector() + opener.addheaders = [('User-agent', build_user_agent())] + + for handler in handlers: + opener.add_handler(handler) + + return opener + + +class GzipDecodedResponse(GZIP_BASE): + """A file-like object to decode a response encoded with the gzip + method, as described in RFC 1952. + + Largely copied from ``xmlrpclib``/``xmlrpc.client`` and modified + to work for py2.4-py3 + """ + def __init__(self, response): + # response doesn't support tell() and read(), required by + # GzipFile + if not gzip: + raise SpeedtestHTTPError('HTTP response body is gzip encoded, ' + 'but gzip support is not available') + IO = BytesIO or StringIO + self.io = IO() + while 1: + chunk = response.read(1024) + if len(chunk) == 0: + break + self.io.write(chunk) + self.io.seek(0) + gzip.GzipFile.__init__(self, mode='rb', fileobj=self.io) + + def close(self): + try: + gzip.GzipFile.close(self) + finally: + self.io.close() + + +def get_exception(): + """Helper function to work with py2.4-py3 for getting the current + exception in a try/except block + """ + return sys.exc_info()[1] + + +def distance(origin, destination): + """Determine distance between 2 sets of [lat,lon] in km""" + + lat1, lon1 = origin + lat2, lon2 = destination + radius = 6371 # km + + dlat = math.radians(lat2 - lat1) + dlon = math.radians(lon2 - lon1) + a = (math.sin(dlat / 2) * math.sin(dlat / 2) + + math.cos(math.radians(lat1)) * + math.cos(math.radians(lat2)) * math.sin(dlon / 2) * + math.sin(dlon / 2)) + c = 2 * math.atan2(math.sqrt(a), math.sqrt(1 - a)) + d = radius * c + + return d + + +def build_user_agent(): + """Build a Mozilla/5.0 compatible User-Agent string""" + + ua_tuple = ( + 'Mozilla/5.0', + '(%s; U; %s; en-us)' % (platform.platform(), + platform.architecture()[0]), + 'Python/%s' % platform.python_version(), + '(KHTML, like Gecko)', + 'speedtest-cli/%s' % __version__ + ) + user_agent = ' '.join(ua_tuple) + printer('User-Agent: %s' % user_agent, debug=True) + return user_agent + + +def build_request(url, data=None, headers=None, bump='0', secure=False): + """Build a urllib2 request object + + This function automatically adds a User-Agent header to all requests + + """ + + if not headers: + headers = {} + + if url[0] == ':': + scheme = ('http', 'https')[bool(secure)] + schemed_url = '%s%s' % (scheme, url) + else: + schemed_url = url + + if '?' in url: + delim = '&' + else: + delim = '?' + + # WHO YOU GONNA CALL? CACHE BUSTERS! + final_url = '%s%sx=%s.%s' % (schemed_url, delim, + int(timeit.time.time() * 1000), + bump) + + headers.update({ + 'Cache-Control': 'no-cache', + }) + + printer('%s %s' % (('GET', 'POST')[bool(data)], final_url), + debug=True) + + return Request(final_url, data=data, headers=headers) + + +def catch_request(request, opener=None): + """Helper function to catch common exceptions encountered when + establishing a connection with a HTTP/HTTPS request + + """ + + if opener: + _open = opener.open + else: + _open = urlopen + + try: + uh = _open(request) + if request.get_full_url() != uh.geturl(): + printer('Redirected to %s' % uh.geturl(), debug=True) + return uh, False + except HTTP_ERRORS: + e = get_exception() + return None, e + + +def get_response_stream(response): + """Helper function to return either a Gzip reader if + ``Content-Encoding`` is ``gzip`` otherwise the response itself + + """ + + try: + getheader = response.headers.getheader + except AttributeError: + getheader = response.getheader + + if getheader('content-encoding') == 'gzip': + return GzipDecodedResponse(response) + + return response + + +def get_attributes_by_tag_name(dom, tag_name): + """Retrieve an attribute from an XML document and return it in a + consistent format + + Only used with xml.dom.minidom, which is likely only to be used + with python versions older than 2.5 + """ + elem = dom.getElementsByTagName(tag_name)[0] + return dict(list(elem.attributes.items())) + + +def print_dots(shutdown_event): + """Built in callback function used by Thread classes for printing + status + """ + def inner(current, total, start=False, end=False): + if shutdown_event.isSet(): + return + + sys.stdout.write('.') + if current + 1 == total and end is True: + sys.stdout.write('\n') + sys.stdout.flush() + return inner + + +def do_nothing(*args, **kwargs): + pass + + +class HTTPDownloader(threading.Thread): + """Thread class for retrieving a URL""" + + def __init__(self, i, request, start, timeout, opener=None, + shutdown_event=None): + threading.Thread.__init__(self) + self.request = request + self.result = [0] + self.starttime = start + self.timeout = timeout + self.i = i + if opener: + self._opener = opener.open + else: + self._opener = urlopen + + if shutdown_event: + self._shutdown_event = shutdown_event + else: + self._shutdown_event = FakeShutdownEvent() + + def run(self): + try: + if (timeit.default_timer() - self.starttime) <= self.timeout: + f = self._opener(self.request) + while (not self._shutdown_event.isSet() and + (timeit.default_timer() - self.starttime) <= + self.timeout): + self.result.append(len(f.read(10240))) + if self.result[-1] == 0: + break + f.close() + except IOError: + pass + + +class HTTPUploaderData(object): + """File like object to improve cutting off the upload once the timeout + has been reached + """ + + def __init__(self, length, start, timeout, shutdown_event=None): + self.length = length + self.start = start + self.timeout = timeout + + if shutdown_event: + self._shutdown_event = shutdown_event + else: + self._shutdown_event = FakeShutdownEvent() + + self._data = None + + self.total = [0] + + def pre_allocate(self): + chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ' + multiplier = int(round(int(self.length) / 36.0)) + IO = BytesIO or StringIO + try: + self._data = IO( + ('content1=%s' % + (chars * multiplier)[0:int(self.length) - 9] + ).encode() + ) + except MemoryError: + raise SpeedtestCLIError( + 'Insufficient memory to pre-allocate upload data. Please ' + 'use --no-pre-allocate' + ) + + @property + def data(self): + if not self._data: + self.pre_allocate() + return self._data + + def read(self, n=10240): + if ((timeit.default_timer() - self.start) <= self.timeout and + not self._shutdown_event.isSet()): + chunk = self.data.read(n) + self.total.append(len(chunk)) + return chunk + else: + raise SpeedtestUploadTimeout() + + def __len__(self): + return self.length + + +class HTTPUploader(threading.Thread): + """Thread class for putting a URL""" + + def __init__(self, i, request, start, size, timeout, opener=None, + shutdown_event=None): + threading.Thread.__init__(self) + self.request = request + self.request.data.start = self.starttime = start + self.size = size + self.result = None + self.timeout = timeout + self.i = i + + if opener: + self._opener = opener.open + else: + self._opener = urlopen + + if shutdown_event: + self._shutdown_event = shutdown_event + else: + self._shutdown_event = FakeShutdownEvent() + + def run(self): + request = self.request + try: + if ((timeit.default_timer() - self.starttime) <= self.timeout and + not self._shutdown_event.isSet()): + try: + f = self._opener(request) + except TypeError: + # PY24 expects a string or buffer + # This also causes issues with Ctrl-C, but we will concede + # for the moment that Ctrl-C on PY24 isn't immediate + request = build_request(self.request.get_full_url(), + data=request.data.read(self.size)) + f = self._opener(request) + f.read(11) + f.close() + self.result = sum(self.request.data.total) + else: + self.result = 0 + except (IOError, SpeedtestUploadTimeout): + self.result = sum(self.request.data.total) + + +class SpeedtestResults(object): + """Class for holding the results of a speedtest, including: + + Download speed + Upload speed + Ping/Latency to test server + Data about server that the test was run against + + Additionally this class can return a result data as a dictionary or CSV, + as well as submit a POST of the result data to the speedtest.net API + to get a share results image link. + """ + + def __init__(self, download=0, upload=0, ping=0, server=None, client=None, + opener=None, secure=False): + self.download = download + self.upload = upload + self.ping = ping + if server is None: + self.server = {} + else: + self.server = server + self.client = client or {} + + self._share = None + self.timestamp = '%sZ' % datetime.datetime.utcnow().isoformat() + self.bytes_received = 0 + self.bytes_sent = 0 + + if opener: + self._opener = opener + else: + self._opener = build_opener() + + self._secure = secure + + def __repr__(self): + return repr(self.dict()) + + def share(self): + """POST data to the speedtest.net API to obtain a share results + link + """ + + if self._share: + return self._share + + download = int(round(self.download / 1000.0, 0)) + ping = int(round(self.ping, 0)) + upload = int(round(self.upload / 1000.0, 0)) + + # Build the request to send results back to speedtest.net + # We use a list instead of a dict because the API expects parameters + # in a certain order + api_data = [ + 'recommendedserverid=%s' % self.server['id'], + 'ping=%s' % ping, + 'screenresolution=', + 'promo=', + 'download=%s' % download, + 'screendpi=', + 'upload=%s' % upload, + 'testmethod=http', + 'hash=%s' % md5(('%s-%s-%s-%s' % + (ping, upload, download, '297aae72')) + .encode()).hexdigest(), + 'touchscreen=none', + 'startmode=pingselect', + 'accuracy=1', + 'bytesreceived=%s' % self.bytes_received, + 'bytessent=%s' % self.bytes_sent, + 'serverid=%s' % self.server['id'], + ] + + headers = {'Referer': 'http://c.speedtest.net/flash/speedtest.swf'} + request = build_request('://www.speedtest.net/api/api.php', + data='&'.join(api_data).encode(), + headers=headers, secure=self._secure) + f, e = catch_request(request, opener=self._opener) + if e: + raise ShareResultsConnectFailure(e) + + response = f.read() + code = f.code + f.close() + + if int(code) != 200: + raise ShareResultsSubmitFailure('Could not submit results to ' + 'speedtest.net') + + qsargs = parse_qs(response.decode()) + resultid = qsargs.get('resultid') + if not resultid or len(resultid) != 1: + raise ShareResultsSubmitFailure('Could not submit results to ' + 'speedtest.net') + + self._share = 'http://www.speedtest.net/result/%s.png' % resultid[0] + + return self._share + + def dict(self): + """Return dictionary of result data""" + + return { + 'download': self.download, + 'upload': self.upload, + 'ping': self.ping, + 'server': self.server, + 'timestamp': self.timestamp, + 'bytes_sent': self.bytes_sent, + 'bytes_received': self.bytes_received, + 'share': self._share, + 'client': self.client, + } + + @staticmethod + def csv_header(delimiter=','): + """Return CSV Headers""" + + row = ['Server ID', 'Sponsor', 'Server Name', 'Timestamp', 'Distance', + 'Ping', 'Download', 'Upload', 'Share', 'IP Address'] + out = StringIO() + writer = csv.writer(out, delimiter=delimiter, lineterminator='') + writer.writerow([to_utf8(v) for v in row]) + return out.getvalue() + + def csv(self, delimiter=','): + """Return data in CSV format""" + + data = self.dict() + out = StringIO() + writer = csv.writer(out, delimiter=delimiter, lineterminator='') + row = [data['server']['id'], data['server']['sponsor'], + data['server']['name'], data['timestamp'], + data['server']['d'], data['ping'], data['download'], + data['upload'], self._share or '', self.client['ip']] + writer.writerow([to_utf8(v) for v in row]) + return out.getvalue() + + def json(self, pretty=False): + """Return data in JSON format""" + + kwargs = {} + if pretty: + kwargs.update({ + 'indent': 4, + 'sort_keys': True + }) + return json.dumps(self.dict(), **kwargs) + + +class Speedtest(object): + """Class for performing standard speedtest.net testing operations""" + + def __init__(self, config=None, source_address=None, timeout=10, + secure=False, shutdown_event=None): + self.config = {} + + self._source_address = source_address + self._timeout = timeout + self._opener = build_opener(source_address, timeout) + + self._secure = secure + + if shutdown_event: + self._shutdown_event = shutdown_event + else: + self._shutdown_event = FakeShutdownEvent() + + self.get_config() + if config is not None: + self.config.update(config) + + self.servers = {} + self.closest = [] + self._best = {} + + self.results = SpeedtestResults( + client=self.config['client'], + opener=self._opener, + secure=secure, + ) + + @property + def best(self): + if not self._best: + self.get_best_server() + return self._best + + def get_config(self): + """Download the speedtest.net configuration and return only the data + we are interested in + """ + + headers = {} + if gzip: + headers['Accept-Encoding'] = 'gzip' + request = build_request('://www.speedtest.net/speedtest-config.php', + headers=headers, secure=self._secure) + uh, e = catch_request(request, opener=self._opener) + if e: + raise ConfigRetrievalError(e) + configxml_list = [] + + stream = get_response_stream(uh) + + while 1: + try: + configxml_list.append(stream.read(1024)) + except (OSError, EOFError): + raise ConfigRetrievalError(get_exception()) + if len(configxml_list[-1]) == 0: + break + stream.close() + uh.close() + + if int(uh.code) != 200: + return None + + configxml = ''.encode().join(configxml_list) + + printer('Config XML:\n%s' % configxml, debug=True) + + try: + try: + root = ET.fromstring(configxml) + except ET.ParseError: + e = get_exception() + raise SpeedtestConfigError( + 'Malformed speedtest.net configuration: %s' % e + ) + server_config = root.find('server-config').attrib + download = root.find('download').attrib + upload = root.find('upload').attrib + # times = root.find('times').attrib + client = root.find('client').attrib + + except AttributeError: + try: + root = DOM.parseString(configxml) + except ExpatError: + e = get_exception() + raise SpeedtestConfigError( + 'Malformed speedtest.net configuration: %s' % e + ) + server_config = get_attributes_by_tag_name(root, 'server-config') + download = get_attributes_by_tag_name(root, 'download') + upload = get_attributes_by_tag_name(root, 'upload') + # times = get_attributes_by_tag_name(root, 'times') + client = get_attributes_by_tag_name(root, 'client') + + ignore_servers = list( + map(int, server_config['ignoreids'].split(',')) + ) + + ratio = int(upload['ratio']) + upload_max = int(upload['maxchunkcount']) + up_sizes = [32768, 65536, 131072, 262144, 524288, 1048576, 7340032] + sizes = { + 'upload': up_sizes[ratio - 1:], + 'download': [350, 500, 750, 1000, 1500, 2000, 2500, + 3000, 3500, 4000] + } + + size_count = len(sizes['upload']) + + upload_count = int(math.ceil(upload_max / size_count)) + + counts = { + 'upload': upload_count, + 'download': int(download['threadsperurl']) + } + + threads = { + 'upload': int(upload['threads']), + 'download': int(server_config['threadcount']) * 2 + } + + length = { + 'upload': int(upload['testlength']), + 'download': int(download['testlength']) + } + + self.config.update({ + 'client': client, + 'ignore_servers': ignore_servers, + 'sizes': sizes, + 'counts': counts, + 'threads': threads, + 'length': length, + 'upload_max': upload_count * size_count + }) + + try: + self.lat_lon = (float(client['lat']), float(client['lon'])) + except ValueError: + raise SpeedtestConfigError( + 'Unknown location: lat=%r lon=%r' % + (client.get('lat'), client.get('lon')) + ) + + printer('Config:\n%r' % self.config, debug=True) + + return self.config + + def get_servers(self, servers=None, exclude=None): + """Retrieve a the list of speedtest.net servers, optionally filtered + to servers matching those specified in the ``servers`` argument + """ + if servers is None: + servers = [] + + if exclude is None: + exclude = [] + + self.servers.clear() + + for server_list in (servers, exclude): + for i, s in enumerate(server_list): + try: + server_list[i] = int(s) + except ValueError: + raise InvalidServerIDType( + '%s is an invalid server type, must be int' % s + ) + + urls = [ + '://www.speedtest.net/speedtest-servers-static.php', + 'http://c.speedtest.net/speedtest-servers-static.php', + '://www.speedtest.net/speedtest-servers.php', + 'http://c.speedtest.net/speedtest-servers.php', + ] + + headers = {} + if gzip: + headers['Accept-Encoding'] = 'gzip' + + errors = [] + for url in urls: + try: + request = build_request( + '%s?threads=%s' % (url, + self.config['threads']['download']), + headers=headers, + secure=self._secure + ) + uh, e = catch_request(request, opener=self._opener) + if e: + errors.append('%s' % e) + raise ServersRetrievalError() + + stream = get_response_stream(uh) + + serversxml_list = [] + while 1: + try: + serversxml_list.append(stream.read(1024)) + except (OSError, EOFError): + raise ServersRetrievalError(get_exception()) + if len(serversxml_list[-1]) == 0: + break + + stream.close() + uh.close() + + if int(uh.code) != 200: + raise ServersRetrievalError() + + serversxml = ''.encode().join(serversxml_list) + + printer('Servers XML:\n%s' % serversxml, debug=True) + + try: + try: + try: + root = ET.fromstring(serversxml) + except ET.ParseError: + e = get_exception() + raise SpeedtestServersError( + 'Malformed speedtest.net server list: %s' % e + ) + elements = root.getiterator('server') + except AttributeError: + try: + root = DOM.parseString(serversxml) + except ExpatError: + e = get_exception() + raise SpeedtestServersError( + 'Malformed speedtest.net server list: %s' % e + ) + elements = root.getElementsByTagName('server') + except (SyntaxError, xml.parsers.expat.ExpatError): + raise ServersRetrievalError() + + for server in elements: + try: + attrib = server.attrib + except AttributeError: + attrib = dict(list(server.attributes.items())) + + if servers and int(attrib.get('id')) not in servers: + continue + + if (int(attrib.get('id')) in self.config['ignore_servers'] + or int(attrib.get('id')) in exclude): + continue + + try: + d = distance(self.lat_lon, + (float(attrib.get('lat')), + float(attrib.get('lon')))) + except Exception: + continue + + attrib['d'] = d + + try: + self.servers[d].append(attrib) + except KeyError: + self.servers[d] = [attrib] + + break + + except ServersRetrievalError: + continue + + if (servers or exclude) and not self.servers: + raise NoMatchedServers() + + return self.servers + + def set_mini_server(self, server): + """Instead of querying for a list of servers, set a link to a + speedtest mini server + """ + + urlparts = urlparse(server) + + name, ext = os.path.splitext(urlparts[2]) + if ext: + url = os.path.dirname(server) + else: + url = server + + request = build_request(url) + uh, e = catch_request(request, opener=self._opener) + if e: + raise SpeedtestMiniConnectFailure('Failed to connect to %s' % + server) + else: + text = uh.read() + uh.close() + + extension = re.findall('upload_?[Ee]xtension: "([^"]+)"', + text.decode()) + if not extension: + for ext in ['php', 'asp', 'aspx', 'jsp']: + try: + f = self._opener.open( + '%s/speedtest/upload.%s' % (url, ext) + ) + except Exception: + pass + else: + data = f.read().strip().decode() + if (f.code == 200 and + len(data.splitlines()) == 1 and + re.match('size=[0-9]', data)): + extension = [ext] + break + if not urlparts or not extension: + raise InvalidSpeedtestMiniServer('Invalid Speedtest Mini Server: ' + '%s' % server) + + self.servers = [{ + 'sponsor': 'Speedtest Mini', + 'name': urlparts[1], + 'd': 0, + 'url': '%s/speedtest/upload.%s' % (url.rstrip('/'), extension[0]), + 'latency': 0, + 'id': 0 + }] + + return self.servers + + def get_closest_servers(self, limit=5): + """Limit servers to the closest speedtest.net servers based on + geographic distance + """ + + if not self.servers: + self.get_servers() + + for d in sorted(self.servers.keys()): + for s in self.servers[d]: + self.closest.append(s) + if len(self.closest) == limit: + break + else: + continue + break + + printer('Closest Servers:\n%r' % self.closest, debug=True) + return self.closest + + def get_best_server(self, servers=None): + """Perform a speedtest.net "ping" to determine which speedtest.net + server has the lowest latency + """ + + if not servers: + if not self.closest: + servers = self.get_closest_servers() + servers = self.closest + + if self._source_address: + source_address_tuple = (self._source_address, 0) + else: + source_address_tuple = None + + user_agent = build_user_agent() + + results = {} + for server in servers: + cum = [] + url = os.path.dirname(server['url']) + stamp = int(timeit.time.time() * 1000) + latency_url = '%s/latency.txt?x=%s' % (url, stamp) + for i in range(0, 3): + this_latency_url = '%s.%s' % (latency_url, i) + printer('%s %s' % ('GET', this_latency_url), + debug=True) + urlparts = urlparse(latency_url) + try: + if urlparts[0] == 'https': + h = SpeedtestHTTPSConnection( + urlparts[1], + source_address=source_address_tuple + ) + else: + h = SpeedtestHTTPConnection( + urlparts[1], + source_address=source_address_tuple + ) + headers = {'User-Agent': user_agent} + path = '%s?%s' % (urlparts[2], urlparts[4]) + start = timeit.default_timer() + h.request("GET", path, headers=headers) + r = h.getresponse() + total = (timeit.default_timer() - start) + except HTTP_ERRORS: + e = get_exception() + printer('ERROR: %r' % e, debug=True) + cum.append(3600) + continue + + text = r.read(9) + if int(r.status) == 200 and text == 'test=test'.encode(): + cum.append(total) + else: + cum.append(3600) + h.close() + + avg = round((sum(cum) / 6) * 1000.0, 3) + results[avg] = server + + try: + fastest = sorted(results.keys())[0] + except IndexError: + raise SpeedtestBestServerFailure('Unable to connect to servers to ' + 'test latency.') + best = results[fastest] + best['latency'] = fastest + + self.results.ping = fastest + self.results.server = best + + self._best.update(best) + printer('Best Server:\n%r' % best, debug=True) + return best + + def download(self, callback=do_nothing, threads=None): + """Test download speed against speedtest.net + + A ``threads`` value of ``None`` will fall back to those dictated + by the speedtest.net configuration + """ + + urls = [] + for size in self.config['sizes']['download']: + for _ in range(0, self.config['counts']['download']): + urls.append('%s/random%sx%s.jpg' % + (os.path.dirname(self.best['url']), size, size)) + + request_count = len(urls) + requests = [] + for i, url in enumerate(urls): + requests.append( + build_request(url, bump=i, secure=self._secure) + ) + + def producer(q, requests, request_count): + for i, request in enumerate(requests): + thread = HTTPDownloader( + i, + request, + start, + self.config['length']['download'], + opener=self._opener, + shutdown_event=self._shutdown_event + ) + thread.start() + q.put(thread, True) + callback(i, request_count, start=True) + + finished = [] + + def consumer(q, request_count): + while len(finished) < request_count: + thread = q.get(True) + while thread.isAlive(): + thread.join(timeout=0.1) + finished.append(sum(thread.result)) + callback(thread.i, request_count, end=True) + + q = Queue(threads or self.config['threads']['download']) + prod_thread = threading.Thread(target=producer, + args=(q, requests, request_count)) + cons_thread = threading.Thread(target=consumer, + args=(q, request_count)) + start = timeit.default_timer() + prod_thread.start() + cons_thread.start() + while prod_thread.isAlive(): + prod_thread.join(timeout=0.1) + while cons_thread.isAlive(): + cons_thread.join(timeout=0.1) + + stop = timeit.default_timer() + self.results.bytes_received = sum(finished) + self.results.download = ( + (self.results.bytes_received / (stop - start)) * 8.0 + ) + if self.results.download > 100000: + self.config['threads']['upload'] = 8 + return self.results.download + + def upload(self, callback=do_nothing, pre_allocate=True, threads=None): + """Test upload speed against speedtest.net + + A ``threads`` value of ``None`` will fall back to those dictated + by the speedtest.net configuration + """ + + sizes = [] + + for size in self.config['sizes']['upload']: + for _ in range(0, self.config['counts']['upload']): + sizes.append(size) + + # request_count = len(sizes) + request_count = self.config['upload_max'] + + requests = [] + for i, size in enumerate(sizes): + # We set ``0`` for ``start`` and handle setting the actual + # ``start`` in ``HTTPUploader`` to get better measurements + data = HTTPUploaderData( + size, + 0, + self.config['length']['upload'], + shutdown_event=self._shutdown_event + ) + if pre_allocate: + data.pre_allocate() + + headers = {'Content-length': size} + requests.append( + ( + build_request(self.best['url'], data, secure=self._secure, + headers=headers), + size + ) + ) + + def producer(q, requests, request_count): + for i, request in enumerate(requests[:request_count]): + thread = HTTPUploader( + i, + request[0], + start, + request[1], + self.config['length']['upload'], + opener=self._opener, + shutdown_event=self._shutdown_event + ) + thread.start() + q.put(thread, True) + callback(i, request_count, start=True) + + finished = [] + + def consumer(q, request_count): + while len(finished) < request_count: + thread = q.get(True) + while thread.isAlive(): + thread.join(timeout=0.1) + finished.append(thread.result) + callback(thread.i, request_count, end=True) + + q = Queue(threads or self.config['threads']['upload']) + prod_thread = threading.Thread(target=producer, + args=(q, requests, request_count)) + cons_thread = threading.Thread(target=consumer, + args=(q, request_count)) + start = timeit.default_timer() + prod_thread.start() + cons_thread.start() + while prod_thread.isAlive(): + prod_thread.join(timeout=0.1) + while cons_thread.isAlive(): + cons_thread.join(timeout=0.1) + + stop = timeit.default_timer() + self.results.bytes_sent = sum(finished) + self.results.upload = ( + (self.results.bytes_sent / (stop - start)) * 8.0 + ) + return self.results.upload + + +def ctrl_c(shutdown_event): + """Catch Ctrl-C key sequence and set a SHUTDOWN_EVENT for our threaded + operations + """ + def inner(signum, frame): + shutdown_event.set() + printer('\nCancelling...', error=True) + sys.exit(0) + return inner + + +def version(): + """Print the version""" + + printer('speedtest-cli %s' % __version__) + printer('Python %s' % sys.version.replace('\n', '')) + sys.exit(0) + + +def csv_header(delimiter=','): + """Print the CSV Headers""" + + printer(SpeedtestResults.csv_header(delimiter=delimiter)) + sys.exit(0) + + +def parse_args(): + """Function to handle building and parsing of command line arguments""" + description = ( + 'Command line interface for testing internet bandwidth using ' + 'speedtest.net.\n' + '------------------------------------------------------------' + '--------------\n' + 'https://github.com/sivel/speedtest-cli') + + parser = ArgParser(description=description) + # Give optparse.OptionParser an `add_argument` method for + # compatibility with argparse.ArgumentParser + try: + parser.add_argument = parser.add_option + except AttributeError: + pass + parser.add_argument('--no-download', dest='download', default=True, + action='store_const', const=False, + help='Do not perform download test') + parser.add_argument('--no-upload', dest='upload', default=True, + action='store_const', const=False, + help='Do not perform upload test') + parser.add_argument('--single', default=False, action='store_true', + help='Only use a single connection instead of ' + 'multiple. This simulates a typical file ' + 'transfer.') + parser.add_argument('--bytes', dest='units', action='store_const', + const=('byte', 8), default=('bit', 1), + help='Display values in bytes instead of bits. Does ' + 'not affect the image generated by --share, nor ' + 'output from --json or --csv') + parser.add_argument('--share', action='store_true', + help='Generate and provide a URL to the speedtest.net ' + 'share results image, not displayed with --csv') + parser.add_argument('--simple', action='store_true', default=False, + help='Suppress verbose output, only show basic ' + 'information') + parser.add_argument('--csv', action='store_true', default=False, + help='Suppress verbose output, only show basic ' + 'information in CSV format. Speeds listed in ' + 'bit/s and not affected by --bytes') + parser.add_argument('--csv-delimiter', default=',', type=PARSER_TYPE_STR, + help='Single character delimiter to use in CSV ' + 'output. Default ","') + parser.add_argument('--csv-header', action='store_true', default=False, + help='Print CSV headers') + parser.add_argument('--json', action='store_true', default=False, + help='Suppress verbose output, only show basic ' + 'information in JSON format. Speeds listed in ' + 'bit/s and not affected by --bytes') + parser.add_argument('--list', action='store_true', + help='Display a list of speedtest.net servers ' + 'sorted by distance') + parser.add_argument('--server', type=PARSER_TYPE_INT, action='append', + help='Specify a server ID to test against. Can be ' + 'supplied multiple times') + parser.add_argument('--exclude', type=PARSER_TYPE_INT, action='append', + help='Exclude a server from selection. Can be ' + 'supplied multiple times') + parser.add_argument('--mini', help='URL of the Speedtest Mini server') + parser.add_argument('--source', help='Source IP address to bind to') + parser.add_argument('--timeout', default=10, type=PARSER_TYPE_FLOAT, + help='HTTP timeout in seconds. Default 10') + parser.add_argument('--secure', action='store_true', + help='Use HTTPS instead of HTTP when communicating ' + 'with speedtest.net operated servers') + parser.add_argument('--no-pre-allocate', dest='pre_allocate', + action='store_const', default=True, const=False, + help='Do not pre allocate upload data. Pre allocation ' + 'is enabled by default to improve upload ' + 'performance. To support systems with ' + 'insufficient memory, use this option to avoid a ' + 'MemoryError') + parser.add_argument('--version', action='store_true', + help='Show the version number and exit') + parser.add_argument('--debug', action='store_true', + help=ARG_SUPPRESS, default=ARG_SUPPRESS) + + options = parser.parse_args() + if isinstance(options, tuple): + args = options[0] + else: + args = options + return args + + +def validate_optional_args(args): + """Check if an argument was provided that depends on a module that may + not be part of the Python standard library. + + If such an argument is supplied, and the module does not exist, exit + with an error stating which module is missing. + """ + optional_args = { + 'json': ('json/simplejson python module', json), + 'secure': ('SSL support', HTTPSConnection), + } + + for arg, info in optional_args.items(): + if getattr(args, arg, False) and info[1] is None: + raise SystemExit('%s is not installed. --%s is ' + 'unavailable' % (info[0], arg)) + + +def printer(string, quiet=False, debug=False, error=False, **kwargs): + """Helper function print a string with various features""" + + if debug and not DEBUG: + return + + if debug: + if sys.stdout.isatty(): + out = '\033[1;30mDEBUG: %s\033[0m' % string + else: + out = 'DEBUG: %s' % string + else: + out = string + + if error: + kwargs['file'] = sys.stderr + + if not quiet: + print_(out, **kwargs) + + +def shell(): + """Run the full speedtest.net test""" + + global DEBUG + shutdown_event = threading.Event() + + signal.signal(signal.SIGINT, ctrl_c(shutdown_event)) + + args = parse_args() + + # Print the version and exit + if args.version: + version() + + if not args.download and not args.upload: + raise SpeedtestCLIError('Cannot supply both --no-download and ' + '--no-upload') + + if len(args.csv_delimiter) != 1: + raise SpeedtestCLIError('--csv-delimiter must be a single character') + + if args.csv_header: + csv_header(args.csv_delimiter) + + validate_optional_args(args) + + debug = getattr(args, 'debug', False) + if debug == 'SUPPRESSHELP': + debug = False + if debug: + DEBUG = True + + if args.simple or args.csv or args.json: + quiet = True + else: + quiet = False + + if args.csv or args.json: + machine_format = True + else: + machine_format = False + + # Don't set a callback if we are running quietly + if quiet or debug: + callback = do_nothing + else: + callback = print_dots(shutdown_event) + + printer('Retrieving speedtest.net configuration...', quiet) + try: + speedtest = Speedtest( + source_address=args.source, + timeout=args.timeout, + secure=args.secure + ) + except (ConfigRetrievalError,) + HTTP_ERRORS: + printer('Cannot retrieve speedtest configuration', error=True) + raise SpeedtestCLIError(get_exception()) + + if args.list: + try: + speedtest.get_servers() + except (ServersRetrievalError,) + HTTP_ERRORS: + printer('Cannot retrieve speedtest server list', error=True) + raise SpeedtestCLIError(get_exception()) + + for _, servers in sorted(speedtest.servers.items()): + for server in servers: + line = ('%(id)5s) %(sponsor)s (%(name)s, %(country)s) ' + '[%(d)0.2f km]' % server) + try: + printer(line) + except IOError: + e = get_exception() + if e.errno != errno.EPIPE: + raise + sys.exit(0) + + printer('Testing from %(isp)s (%(ip)s)...' % speedtest.config['client'], + quiet) + + if not args.mini: + printer('Retrieving speedtest.net server list...', quiet) + try: + speedtest.get_servers(servers=args.server, exclude=args.exclude) + except NoMatchedServers: + raise SpeedtestCLIError( + 'No matched servers: %s' % + ', '.join('%s' % s for s in args.server) + ) + except (ServersRetrievalError,) + HTTP_ERRORS: + printer('Cannot retrieve speedtest server list', error=True) + raise SpeedtestCLIError(get_exception()) + except InvalidServerIDType: + raise SpeedtestCLIError( + '%s is an invalid server type, must ' + 'be an int' % ', '.join('%s' % s for s in args.server) + ) + + if args.server and len(args.server) == 1: + printer('Retrieving information for the selected server...', quiet) + else: + printer('Selecting best server based on ping...', quiet) + speedtest.get_best_server() + elif args.mini: + speedtest.get_best_server(speedtest.set_mini_server(args.mini)) + + results = speedtest.results + + printer('Hosted by %(sponsor)s (%(name)s) [%(d)0.2f km]: ' + '%(latency)s ms' % results.server, quiet) + + if args.download: + printer('Testing download speed', quiet, + end=('', '\n')[bool(debug)]) + speedtest.download( + callback=callback, + threads=(None, 1)[args.single] + ) + printer('Download: %0.2f M%s/s' % + ((results.download / 1000.0 / 1000.0) / args.units[1], + args.units[0]), + quiet) + else: + printer('Skipping download test', quiet) + + if args.upload: + printer('Testing upload speed', quiet, + end=('', '\n')[bool(debug)]) + speedtest.upload( + callback=callback, + pre_allocate=args.pre_allocate, + threads=(None, 1)[args.single] + ) + printer('Upload: %0.2f M%s/s' % + ((results.upload / 1000.0 / 1000.0) / args.units[1], + args.units[0]), + quiet) + else: + printer('Skipping upload test', quiet) + + printer('Results:\n%r' % results.dict(), debug=True) + + if not args.simple and args.share: + results.share() + + if args.simple: + printer('Ping: %s ms\nDownload: %0.2f M%s/s\nUpload: %0.2f M%s/s' % + (results.ping, + (results.download / 1000.0 / 1000.0) / args.units[1], + args.units[0], + (results.upload / 1000.0 / 1000.0) / args.units[1], + args.units[0])) + elif args.csv: + printer(results.csv(delimiter=args.csv_delimiter)) + elif args.json: + printer(results.json()) + + if args.share and not machine_format: + printer('Share results: %s' % results.share()) + + +def main(): + try: + shell() + except KeyboardInterrupt: + printer('\nCancelling...', error=True) + except (SpeedtestException, SystemExit): + e = get_exception() + # Ignore a successful exit, or argparse exit + if getattr(e, 'code', 1) not in (0, 2): + msg = '%s' % e + if not msg: + msg = '%r' % e + raise SystemExit('ERROR: %s' % msg) + + +if __name__ == '__main__': + main() diff --git a/.local/bin/ssh-permissions b/.local/bin/ssh-permissions new file mode 100755 index 0000000..b88cb46 --- /dev/null +++ b/.local/bin/ssh-permissions @@ -0,0 +1,10 @@ +chmod 700 ~/.ssh +chmod 644 ~/.ssh/authorized_keys +chmod 644 ~/.ssh/known_hosts +chmod 644 ~/.ssh/config +chmod 600 ~/.ssh/id_rsa +chmod 644 ~/.ssh/id_rsa.pub +chmod 600 ~/.ssh/github_rsa +chmod 644 ~/.ssh/github_rsa.pub +chmod 600 ~/.ssh/mozilla_rsa +chmod 644 ~/.ssh/mozilla_rsa.pub diff --git a/.local/bin/stream-twitch b/.local/bin/stream-twitch new file mode 100755 index 0000000..93ceac6 --- /dev/null +++ b/.local/bin/stream-twitch @@ -0,0 +1,2 @@ +#!/bin/bash +nohup streamlink -p mpv https://www.twitch.tv/$1 best > /dev/null 2>&1 & diff --git a/.local/bin/stream-youtube b/.local/bin/stream-youtube new file mode 100755 index 0000000..748cf23 --- /dev/null +++ b/.local/bin/stream-youtube @@ -0,0 +1,2 @@ +#!/bin/bash +nohup streamlink -p mpv $1 best > /dev/null 2>&1 & diff --git a/.local/bin/suspend-at-time b/.local/bin/suspend-at-time new file mode 100755 index 0000000..b3ce40a --- /dev/null +++ b/.local/bin/suspend-at-time @@ -0,0 +1,15 @@ +#!/bin/bash +#./suspend-at-time 0:00 + +RUNAT="$1" + +while [ 1 ] +do + DATE=`/bin/date +%H:%M` + if [ $DATE. = $RUNAT. ] + then + sudo systemctl suspend + echo ""DONE" at "$(date)"" + pkill suspend-at-time + fi +done diff --git a/.local/bin/temp b/.local/bin/temp new file mode 100755 index 0000000..95fe391 --- /dev/null +++ b/.local/bin/temp @@ -0,0 +1,3 @@ +#!/bin/bash + +echo -e "CPU: $(sensors | awk '/Core 0/ {print $3}'| egrep --color=no -o '[0-9]+\.' | sed 's/\.//')"; echo -e "GPU: $(sudo nvidia-smi -q -d temperature | grep --color=no -i "GPU Current" |egrep --color=no -o '[0-9]*')" diff --git a/.local/bin/term-wmi b/.local/bin/term-wmi new file mode 100755 index 0000000..5a63503 --- /dev/null +++ b/.local/bin/term-wmi @@ -0,0 +1 @@ +rdesktop -u "\LABS\s434812" -g 90% term.wmi.amu.edu.pl diff --git a/.local/bin/twitch b/.local/bin/twitch new file mode 100755 index 0000000..93ceac6 --- /dev/null +++ b/.local/bin/twitch @@ -0,0 +1,2 @@ +#!/bin/bash +nohup streamlink -p mpv https://www.twitch.tv/$1 best > /dev/null 2>&1 & diff --git a/.local/bin/update b/.local/bin/update new file mode 100755 index 0000000..3692f74 --- /dev/null +++ b/.local/bin/update @@ -0,0 +1,2 @@ +#!/bin/bash +sudo eix-repos-sync; sudo emerge-webrsync; sudo emerge --sync; sudo eix-sync -a; sudo eix-update; sudo emaint sync -a; sudo emerge -auDN @world diff --git a/.local/bin/update-kernel b/.local/bin/update-kernel new file mode 100755 index 0000000..45175d1 --- /dev/null +++ b/.local/bin/update-kernel @@ -0,0 +1,108 @@ +#!/bin/bash + +BACKUP="/home/yorune/Linux/portage" +LOG_FILE="/tmp/update-kernel.log" +TMP_KERNEL="/tmp/kernel-config-`uname -r`" +DEFAULT_KERNEL="/usr/src/linux/.config" + +function starting() { +echo -e "\e[93m----------------------COMPILING------------------------------\e[0m" +sudo cp -rv $DEFAULT_KERNEL $TMP_KERNEL +cp -r $TMP_KERNEL $BACKUP +cp -r /etc/portage/* $BACKUP +qlist -I | sort | uniq | tr '\n' ' ' > $BACKUP/list-of-programs-"$(date +"%d-%m-%Y")" +} + +function selection() { +echo -e "\e[93m----------------------SELECTION-----------------------------\e[0m" +sudo eselect kernel list +echo +echo +read -p "New kernel is: " KERVER +echo +echo -e "Your kernel now is \e[91m$(uname -sr)\e[0m" +echo -e "Your selected kernel is \e[91m"$KERVER"\e[0m" +sudo eselect kernel set $KERVER +sudo eselect kernel list | grep "*" +echo +} + +function compilation() { +read -p "Do you want to accept and compile (Y/N): " agreed +echo +if [ "$agreed" == "y" ] || [ "$agreed" == "Y" ] + then + echo -e "\e[91m----------------------\e[5mSTARTING\e[0m\e[91m------------------------------\e[0m" && sleep 10 + $NOW > /tmp/compiling-starting + NEW_KERNEL="/tmp/new-kernel-config" + sudo cp -r $TMP_KERNEL $DEFAULT_KERNEL + cd /usr/src/linux; sudo make menuconfig; sleep 2; sudo cp -r $DEFAULT_KERNEL $NEW_KERNEL + sudo genkernel all --makeopts=-j$(nproc --all) --kernel-config=$NEW_KERNEL --callback="emerge nvidia-drivers::gentoo" + elif [ "$agreed" == "N" ] || [ "$agreed" == "n" ] + then + exit +fi +} + +function ending() { +echo +echo +echo -e "\e[93m----------------------CHECKING-----------------------------\e[0m" +checking +echo +echo +echo -e "\e[93m----------------------REMEMBER-----------------------------\e[0m" +echo "You can remove:" +echo "* /lib/modules/OLD_KERNEL" +echo "* /boot/initramfs-genkernel-OLD_KERNEL" +echo "* /boot/vmlinuz-OLD_KERNEL" +echo "* /boot/System.map-OLD_KERNEL" +echo "* /boot/initramfs-OLD_KERNEL" +echo "* /usr/src/linux-OLD_KERNEL" +echo +echo -e "AFTER EVERYTHING YOU MUST WRITE COMMAND \e[91m"sudo grub-mkconfig -o /boot/grub/grub.cfg"\e[0m" +} + +function checking() { +KERNEL=`eselect kernel list | awk '{print $2}' | egrep -o '[0-9]+.[0-9]+.[0-9]+' | tail -n1` + +INITRANFS="initramfs-$KERNEL-gentoo-x86_64.img" +SYSTEMMAP="System.map-$KERNEL-gentoo-x86_64" +VMLINUZ="vmlinuz-$KERNEL-gentoo-x86_64" + +ifchecking $INITRANFS +ifchecking $SYSTEMMAP +ifchecking $VMLINUZ +} + +function ifchecking () { +FILE=/boot/$1 +if test -f "$FILE"; then + echo "$FILE exist in the /boot folder ;)" +else + echo "$FILE NOT exist in the /boot folder ;)" +fi +} + +function main() { +clear + +BEGIN=$(date +"%s") + +starting +selection +compilation + +echo -e "\e[31mI am leaving! Thank You!\e[0m" && sleep 3 + +TERMIN=$(date +"%s") +DIFFTLPS=$(($TERMIN-$BEGIN)) + +echo -e "\e[93m------------------TIME COMPILATION-------------------------\e[0m" +echo -e "\e[93m$(($DIFFTLPS / 60)) minutes and $(($DIFFTLPS % 60)) seconds \e[0m elapsed for Script Execution." && sleep 3 +ending + +exit +} + +main diff --git a/.local/bin/welcomer b/.local/bin/welcomer new file mode 100755 index 0000000..97125d6 --- /dev/null +++ b/.local/bin/welcomer @@ -0,0 +1,54 @@ +#!/bin/bash + +MEMTOTAL=`awk '$3=="kB"{$2=$2/1024**2;$3="GB";} 1' /proc/meminfo | column -t | grep "MemTotal" | awk '{print $2}'` +MEMFREE=`awk '$3=="kB"{$2=$2/1024**2;$3="GB";} 1' /proc/meminfo | column -t | grep "MemAvailable" | awk '{print $2}'` +NETE=`ip a | awk {'print $2'} | grep -i en | sed 's/://g'` +NETW=`ip a | awk {'print $2'} | grep -i wl | sed 's/://g'` +BACKUP_SDA8=`df -h | grep -i sda8 | awk '{print $5", " $2 " (Total), " $3" (Usage)"}'` +BACKUP_EL=`df -h | grep /run/media/jaqu3/ELEMENTS | awk '{print $5", " $2 " (Total), " $3" (Usage)"}'` +BACKUP_EV=`df -h | grep /run/media/jaqu3/BACKUP_EVERYTHING | awk '{print $5", " $2 " (Total), " $3" (Usage)"}'` + + +if [ -z "$NETW" ]; then + NETD=$NETE +else + NETD=$NETW +fi + +if [ -z "$BACKUP_SDA8" ]; then + BACKUPSDA8=`echo NOT MOUNTED` +else + BACKUPSDA8=$BACKUP_SDA8 +fi + +if [ -z "$BACKUP_EL" ]; then + BACKUPEL=`echo NOT MOUNTED` +else + BACKUPEL=$BACKUP_EL +fi + +if [ -z "$BACKUP_EV" ]; then + BACKUPEV=`echo NOT MOUNTED` +else + BACKUPEV=$BACKUP_EV +fi + + echo -e " + \033[0;35m+++++++++++++++++++: \033[0;37mInfo\033[0;35m :+++++++++++++++++++++++++++++++++++++++++++++++++++++ + + + + \033[0;37mHostname \033[0;35m= \033[1;32m `hostname` + \033[0;35m+ \033[0;37mAddress \033[0;35m= \033[1;32m `/sbin/ip addr show $NETD | grep "inet " | awk '{print $2}' | cut -d'/' -f1` + \033[0;35m+ \033[0;37mKernel \033[0;35m= \033[1;32m `uname -r` + \033[0;35m+ \033[0;37mUptime \033[0;35m= \033[1;32m`uptime | sed 's/.*up ([^,]*), .*/1/'` + \033[0;35m+ \033[0;37mMemory \033[0;35m= \033[1;32m $MEMTOTAL GB (free $MEMFREE GB)\033[0;35m + \033[0;35m+ \033[0;37mUsername \033[0;35m= \033[1;32m `whoami`\033[0;35m + + + \033[0;35m++++++++++++++++++: \033[0;37mStorage\033[0;35m :+++++++++++++++++++++++++++++++++++++++++++++++++++ + + + + \033[0;37m/ \033[0;35m= \033[1;32m `df -h / | sed '1,1d' | awk '{print $5\", \"$2\" (Total), \"$3\" (Usage)\"}'`\033[0;35m + + \033[0;37mSDA8 \033[0;35m= \033[1;32m $BACKUPSDA8 \033[0;35m + + \033[0;37mELEMENTS \033[0;35m= \033[1;32m $BACKUPEL \033[0;35m + + \033[0;37mBACKUP_EVERYTHING \033[0;35m= \033[1;32m $BACKUPEV \033[0;35m + + + \033[0;35m++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ \033[0m" + echo "" diff --git a/.local/bin/welcomer-serwer b/.local/bin/welcomer-serwer new file mode 100755 index 0000000..ef61673 --- /dev/null +++ b/.local/bin/welcomer-serwer @@ -0,0 +1,33 @@ +#!/bin/bash + +# Copy this file to /bin/welcomer and change permisson +x +# sudo bash -c $'echo "/bin/welcomer" >> /etc/profile.d/mymotd.sh && chmod +x /etc/profile.d/mymotd.sh' + + +MEMTOTAL=`awk '$3=="kB"{$2=$2/1024**2;$3="GB";} 1' /proc/meminfo | column -t | grep "MemTotal" | awk '{print $2}'` +MEMFREE=`awk '$3=="kB"{$2=$2/1024**2;$3="GB";} 1' /proc/meminfo | column -t | grep "MemAvailable" | awk '{print $2}'` +NETE=`ip a | awk {'print $2'} | grep -i en | sed 's/://g'` +NETW=`ip a | awk {'print $2'} | grep -i wl | sed 's/://g'` + +if [ -z "$NETW" ]; then + NETD=$NETE +else + NETD=$NETW +fi + + echo -e " + \033[0;35m+++++++++++++++++++: \033[0;37mInfo\033[0;35m :+++++++++++++++++++++++++++++++++++++++++++++++++++++ + + + + \033[0;37mHostname \033[0;35m= \033[1;32m `hostname` + \033[0;35m+ \033[0;37mAddress \033[0;35m= \033[1;32m `/sbin/ip addr show $NETD | grep "inet " | awk '{print $2}' | cut -d'/' -f1` + \033[0;35m+ \033[0;37mKernel \033[0;35m= \033[1;32m `uname -r` + \033[0;35m+ \033[0;37mUptime \033[0;35m= \033[1;32m`uptime | sed 's/.*up ([^,]*), .*/1/'` + \033[0;35m+ \033[0;37mMemory \033[0;35m= \033[1;32m $MEMTOTAL GB (free $MEMFREE GB)\033[0;35m + \033[0;35m+ \033[0;37mUsername \033[0;35m= \033[1;32m `whoami`\033[0;35m + + + \033[0;35m++++++++++++++++++: \033[0;37mStorage\033[0;35m :+++++++++++++++++++++++++++++++++++++++++++++++++++ + + + + \033[0;37m/ \033[0;35m= \033[1;32m `df -h / | sed '1,1d' | awk '{print $5\", \"$2\" (Total), \"$3\" (Usage)\"}'`\033[0;35m + + + \033[0;35m++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ \033[0m" + echo "" diff --git a/.local/bin/wheel b/.local/bin/wheel new file mode 100755 index 0000000..71225dc --- /dev/null +++ b/.local/bin/wheel @@ -0,0 +1,8 @@ +#!/usr/bin/python3.6 +# -*- coding: utf-8 -*- +import re +import sys +from wheel.cli import main +if __name__ == '__main__': + sys.argv[0] = re.sub(r'(-script\.pyw|\.exe)?$', '', sys.argv[0]) + sys.exit(main()) diff --git a/.local/bin/wylaczoff b/.local/bin/wylaczoff new file mode 100755 index 0000000..bfb72eb --- /dev/null +++ b/.local/bin/wylaczoff @@ -0,0 +1,5 @@ +xset b off +xset s off && xset -dpms +set bell-style none +#/usr/bin/amixer -c 0 sset "Auto-Mute Mode" Disabled + diff --git a/.local/bin/yatqa b/.local/bin/yatqa new file mode 100755 index 0000000..b1df29b --- /dev/null +++ b/.local/bin/yatqa @@ -0,0 +1 @@ +wine "C:/Program Files (x86)/YaTQA/yatqa.exe" diff --git a/.local/bin/yt-mp3 b/.local/bin/yt-mp3 new file mode 100755 index 0000000..6827cdd --- /dev/null +++ b/.local/bin/yt-mp3 @@ -0,0 +1,2 @@ +#!/bin/bash +youtube-dl --extract-audio --audio-format mp3 $1 diff --git a/.local/bin/yt-video b/.local/bin/yt-video new file mode 100755 index 0000000..a3053b0 --- /dev/null +++ b/.local/bin/yt-video @@ -0,0 +1,2 @@ +#!/bin/bash +youtube-dl $1 diff --git a/.tmux.conf b/.tmux.conf new file mode 100644 index 0000000..68ef296 --- /dev/null +++ b/.tmux.conf @@ -0,0 +1,36 @@ +set -g prefix C-a +set-option -g default-shell /bin/zsh +unbind C-b +bind-key C-a send-prefix +unbind q +bind q confirm kill-window +set -g status on +bind-key -n C-f copy-mode \; send-key ? +set -g default-terminal "st-256color" +set -g history-limit 20000 +set-option -sg escape-time 0 +set -g base-index 1 # start windows numbering at 1 +setw -g pane-base-index 1 # make pane numbering consistent with windows +setw -g automatic-rename on # rename window to reflect current program +set -g renumber-windows on # renumber windows when a window is closed +set -g set-titles on # set terminal title +set -g display-panes-time 800 # slightly longer pane indicators display time +set -g display-time 1000 # slightly longer status messages display time +set -g status-interval 10 # redraw status line every 10 seconds +set -g status-style bg=blue +set -g status-style fg=white +set -g monitor-activity on +set -g visual-activity off +bind C-c new-session +bind C-f command-prompt -p find-session 'switch-client -t %%' +bind - split-window -v +bind _ split-window -h +bind > swap-pane -D # swap current pane with the next one +bind < swap-pane -U # swap current pane with the previous one +bind -r H resize-pane -L 2 +bind -r J resize-pane -D 2 +bind -r K resize-pane -U 3 +bind -r L resize-pane -R 2 +bind -r C-h previous-window # select previous window +bind -r C-l next-window # select next window +bind Tab last-window # move to last active window diff --git a/.vim/.netrwhist b/.vim/.netrwhist new file mode 100644 index 0000000..f732d20 --- /dev/null +++ b/.vim/.netrwhist @@ -0,0 +1,3 @@ +let g:netrw_dirhistmax =10 +let g:netrw_dirhistcnt =1 +let g:netrw_dirhist_1='/home/yorune' diff --git a/.vim/autoload/plug.vim b/.vim/autoload/plug.vim new file mode 100644 index 0000000..92fea62 --- /dev/null +++ b/.vim/autoload/plug.vim @@ -0,0 +1,2591 @@ +" vim-plug: Vim plugin manager +" ============================ +" +" Download plug.vim and put it in ~/.vim/autoload +" +" curl -fLo ~/.vim/autoload/plug.vim --create-dirs \ +" https://raw.githubusercontent.com/junegunn/vim-plug/master/plug.vim +" +" Edit your .vimrc +" +" call plug#begin('~/.vim/plugged') +" +" " Make sure you use single quotes +" +" " Shorthand notation; fetches https://github.com/junegunn/vim-easy-align +" Plug 'junegunn/vim-easy-align' +" +" " Any valid git URL is allowed +" Plug 'https://github.com/junegunn/vim-github-dashboard.git' +" +" " Multiple Plug commands can be written in a single line using | separators +" Plug 'SirVer/ultisnips' | Plug 'honza/vim-snippets' +" +" " On-demand loading +" Plug 'scrooloose/nerdtree', { 'on': 'NERDTreeToggle' } +" Plug 'tpope/vim-fireplace', { 'for': 'clojure' } +" +" " Using a non-master branch +" Plug 'rdnetto/YCM-Generator', { 'branch': 'stable' } +" +" " Using a tagged release; wildcard allowed (requires git 1.9.2 or above) +" Plug 'fatih/vim-go', { 'tag': '*' } +" +" " Plugin options +" Plug 'nsf/gocode', { 'tag': 'v.20150303', 'rtp': 'vim' } +" +" " Plugin outside ~/.vim/plugged with post-update hook +" Plug 'junegunn/fzf', { 'dir': '~/.fzf', 'do': './install --all' } +" +" " Unmanaged plugin (manually installed and updated) +" Plug '~/my-prototype-plugin' +" +" " Initialize plugin system +" call plug#end() +" +" Then reload .vimrc and :PlugInstall to install plugins. +" +" Plug options: +" +"| Option | Description | +"| ----------------------- | ------------------------------------------------ | +"| `branch`/`tag`/`commit` | Branch/tag/commit of the repository to use | +"| `rtp` | Subdirectory that contains Vim plugin | +"| `dir` | Custom directory for the plugin | +"| `as` | Use different name for the plugin | +"| `do` | Post-update hook (string or funcref) | +"| `on` | On-demand loading: Commands or ``-mappings | +"| `for` | On-demand loading: File types | +"| `frozen` | Do not update unless explicitly specified | +" +" More information: https://github.com/junegunn/vim-plug +" +" +" Copyright (c) 2017 Junegunn Choi +" +" MIT License +" +" Permission is hereby granted, free of charge, to any person obtaining +" a copy of this software and associated documentation files (the +" "Software"), to deal in the Software without restriction, including +" without limitation the rights to use, copy, modify, merge, publish, +" distribute, sublicense, and/or sell copies of the Software, and to +" permit persons to whom the Software is furnished to do so, subject to +" the following conditions: +" +" The above copyright notice and this permission notice shall be +" included in all copies or substantial portions of the Software. +" +" THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +" EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +" MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +" NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +" LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +" OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +" WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + +if exists('g:loaded_plug') + finish +endif +let g:loaded_plug = 1 + +let s:cpo_save = &cpo +set cpo&vim + +let s:plug_src = 'https://github.com/junegunn/vim-plug.git' +let s:plug_tab = get(s:, 'plug_tab', -1) +let s:plug_buf = get(s:, 'plug_buf', -1) +let s:mac_gui = has('gui_macvim') && has('gui_running') +let s:is_win = has('win32') +let s:nvim = has('nvim-0.2') || (has('nvim') && exists('*jobwait') && !s:is_win) +let s:vim8 = has('patch-8.0.0039') && exists('*job_start') +if s:is_win && &shellslash + set noshellslash + let s:me = resolve(expand(':p')) + set shellslash +else + let s:me = resolve(expand(':p')) +endif +let s:base_spec = { 'branch': 'master', 'frozen': 0 } +let s:TYPE = { +\ 'string': type(''), +\ 'list': type([]), +\ 'dict': type({}), +\ 'funcref': type(function('call')) +\ } +let s:loaded = get(s:, 'loaded', {}) +let s:triggers = get(s:, 'triggers', {}) + +if s:is_win + function! s:plug_call(fn, ...) + let shellslash = &shellslash + try + set noshellslash + return call(a:fn, a:000) + finally + let &shellslash = shellslash + endtry + endfunction +else + function! s:plug_call(fn, ...) + return call(a:fn, a:000) + endfunction +endif + +function! s:plug_getcwd() + return s:plug_call('getcwd') +endfunction + +function! s:plug_fnamemodify(fname, mods) + return s:plug_call('fnamemodify', a:fname, a:mods) +endfunction + +function! s:plug_expand(fmt) + return s:plug_call('expand', a:fmt, 1) +endfunction + +function! s:plug_tempname() + return s:plug_call('tempname') +endfunction + +function! plug#begin(...) + if a:0 > 0 + let s:plug_home_org = a:1 + let home = s:path(s:plug_fnamemodify(s:plug_expand(a:1), ':p')) + elseif exists('g:plug_home') + let home = s:path(g:plug_home) + elseif !empty(&rtp) + let home = s:path(split(&rtp, ',')[0]) . '/plugged' + else + return s:err('Unable to determine plug home. Try calling plug#begin() with a path argument.') + endif + if s:plug_fnamemodify(home, ':t') ==# 'plugin' && s:plug_fnamemodify(home, ':h') ==# s:first_rtp + return s:err('Invalid plug home. '.home.' is a standard Vim runtime path and is not allowed.') + endif + + let g:plug_home = home + let g:plugs = {} + let g:plugs_order = [] + let s:triggers = {} + + call s:define_commands() + return 1 +endfunction + +function! s:define_commands() + command! -nargs=+ -bar Plug call plug#() + if !executable('git') + return s:err('`git` executable not found. Most commands will not be available. To suppress this message, prepend `silent!` to `call plug#begin(...)`.') + endif + if has('win32') + \ && &shellslash + \ && (&shell =~# 'cmd\.exe' || &shell =~# 'powershell\.exe') + return s:err('vim-plug does not support shell, ' . &shell . ', when shellslash is set.') + endif + if !has('nvim') + \ && (has('win32') || has('win32unix')) + \ && (!has('multi_byte') || !has('iconv')) + return s:err('Vim needs +iconv, +multi_byte features on Windows to run shell commands.') + endif + command! -nargs=* -bar -bang -complete=customlist,s:names PlugInstall call s:install(0, []) + command! -nargs=* -bar -bang -complete=customlist,s:names PlugUpdate call s:update(0, []) + command! -nargs=0 -bar -bang PlugClean call s:clean(0) + command! -nargs=0 -bar PlugUpgrade if s:upgrade() | execute 'source' s:esc(s:me) | endif + command! -nargs=0 -bar PlugStatus call s:status() + command! -nargs=0 -bar PlugDiff call s:diff() + command! -nargs=? -bar -bang -complete=file PlugSnapshot call s:snapshot(0, ) +endfunction + +function! s:to_a(v) + return type(a:v) == s:TYPE.list ? a:v : [a:v] +endfunction + +function! s:to_s(v) + return type(a:v) == s:TYPE.string ? a:v : join(a:v, "\n") . "\n" +endfunction + +function! s:glob(from, pattern) + return s:lines(globpath(a:from, a:pattern)) +endfunction + +function! s:source(from, ...) + let found = 0 + for pattern in a:000 + for vim in s:glob(a:from, pattern) + execute 'source' s:esc(vim) + let found = 1 + endfor + endfor + return found +endfunction + +function! s:assoc(dict, key, val) + let a:dict[a:key] = add(get(a:dict, a:key, []), a:val) +endfunction + +function! s:ask(message, ...) + call inputsave() + echohl WarningMsg + let answer = input(a:message.(a:0 ? ' (y/N/a) ' : ' (y/N) ')) + echohl None + call inputrestore() + echo "\r" + return (a:0 && answer =~? '^a') ? 2 : (answer =~? '^y') ? 1 : 0 +endfunction + +function! s:ask_no_interrupt(...) + try + return call('s:ask', a:000) + catch + return 0 + endtry +endfunction + +function! s:lazy(plug, opt) + return has_key(a:plug, a:opt) && + \ (empty(s:to_a(a:plug[a:opt])) || + \ !isdirectory(a:plug.dir) || + \ len(s:glob(s:rtp(a:plug), 'plugin')) || + \ len(s:glob(s:rtp(a:plug), 'after/plugin'))) +endfunction + +function! plug#end() + if !exists('g:plugs') + return s:err('Call plug#begin() first') + endif + + if exists('#PlugLOD') + augroup PlugLOD + autocmd! + augroup END + augroup! PlugLOD + endif + let lod = { 'ft': {}, 'map': {}, 'cmd': {} } + + if exists('g:did_load_filetypes') + filetype off + endif + for name in g:plugs_order + if !has_key(g:plugs, name) + continue + endif + let plug = g:plugs[name] + if get(s:loaded, name, 0) || !s:lazy(plug, 'on') && !s:lazy(plug, 'for') + let s:loaded[name] = 1 + continue + endif + + if has_key(plug, 'on') + let s:triggers[name] = { 'map': [], 'cmd': [] } + for cmd in s:to_a(plug.on) + if cmd =~? '^.\+' + if empty(mapcheck(cmd)) && empty(mapcheck(cmd, 'i')) + call s:assoc(lod.map, cmd, name) + endif + call add(s:triggers[name].map, cmd) + elseif cmd =~# '^[A-Z]' + let cmd = substitute(cmd, '!*$', '', '') + if exists(':'.cmd) != 2 + call s:assoc(lod.cmd, cmd, name) + endif + call add(s:triggers[name].cmd, cmd) + else + call s:err('Invalid `on` option: '.cmd. + \ '. Should start with an uppercase letter or ``.') + endif + endfor + endif + + if has_key(plug, 'for') + let types = s:to_a(plug.for) + if !empty(types) + augroup filetypedetect + call s:source(s:rtp(plug), 'ftdetect/**/*.vim', 'after/ftdetect/**/*.vim') + augroup END + endif + for type in types + call s:assoc(lod.ft, type, name) + endfor + endif + endfor + + for [cmd, names] in items(lod.cmd) + execute printf( + \ 'command! -nargs=* -range -bang -complete=file %s call s:lod_cmd(%s, "", , , , %s)', + \ cmd, string(cmd), string(names)) + endfor + + for [map, names] in items(lod.map) + for [mode, map_prefix, key_prefix] in + \ [['i', '', ''], ['n', '', ''], ['v', '', 'gv'], ['o', '', '']] + execute printf( + \ '%snoremap %s %s:call lod_map(%s, %s, %s, "%s")', + \ mode, map, map_prefix, string(map), string(names), mode != 'i', key_prefix) + endfor + endfor + + for [ft, names] in items(lod.ft) + augroup PlugLOD + execute printf('autocmd FileType %s call lod_ft(%s, %s)', + \ ft, string(ft), string(names)) + augroup END + endfor + + call s:reorg_rtp() + filetype plugin indent on + if has('vim_starting') + if has('syntax') && !exists('g:syntax_on') + syntax enable + end + else + call s:reload_plugins() + endif +endfunction + +function! s:loaded_names() + return filter(copy(g:plugs_order), 'get(s:loaded, v:val, 0)') +endfunction + +function! s:load_plugin(spec) + call s:source(s:rtp(a:spec), 'plugin/**/*.vim', 'after/plugin/**/*.vim') +endfunction + +function! s:reload_plugins() + for name in s:loaded_names() + call s:load_plugin(g:plugs[name]) + endfor +endfunction + +function! s:trim(str) + return substitute(a:str, '[\/]\+$', '', '') +endfunction + +function! s:version_requirement(val, min) + for idx in range(0, len(a:min) - 1) + let v = get(a:val, idx, 0) + if v < a:min[idx] | return 0 + elseif v > a:min[idx] | return 1 + endif + endfor + return 1 +endfunction + +function! s:git_version_requirement(...) + if !exists('s:git_version') + let s:git_version = map(split(split(s:system('git --version'))[2], '\.'), 'str2nr(v:val)') + endif + return s:version_requirement(s:git_version, a:000) +endfunction + +function! s:progress_opt(base) + return a:base && !s:is_win && + \ s:git_version_requirement(1, 7, 1) ? '--progress' : '' +endfunction + +function! s:rtp(spec) + return s:path(a:spec.dir . get(a:spec, 'rtp', '')) +endfunction + +if s:is_win + function! s:path(path) + return s:trim(substitute(a:path, '/', '\', 'g')) + endfunction + + function! s:dirpath(path) + return s:path(a:path) . '\' + endfunction + + function! s:is_local_plug(repo) + return a:repo =~? '^[a-z]:\|^[%~]' + endfunction + + " Copied from fzf + let s:codepage = libcallnr('kernel32.dll', 'GetACP', 0) + function! s:wrap_cmds(cmds) + return map([ + \ '@echo off', + \ 'setlocal enabledelayedexpansion'] + \ + (type(a:cmds) == type([]) ? a:cmds : [a:cmds]) + \ + ['endlocal'], + \ printf('iconv(v:val."\r", "%s", "cp%d")', &encoding, s:codepage)) + endfunction + + function! s:batchfile(cmd) + let batchfile = s:plug_tempname().'.bat' + call writefile(s:wrap_cmds(a:cmd), batchfile) + let cmd = plug#shellescape(batchfile, {'shell': &shell, 'script': 0}) + if &shell =~# 'powershell\.exe' + let cmd = '& ' . cmd + endif + return [batchfile, cmd] + endfunction +else + function! s:path(path) + return s:trim(a:path) + endfunction + + function! s:dirpath(path) + return substitute(a:path, '[/\\]*$', '/', '') + endfunction + + function! s:is_local_plug(repo) + return a:repo[0] =~ '[/$~]' + endfunction +endif + +function! s:err(msg) + echohl ErrorMsg + echom '[vim-plug] '.a:msg + echohl None +endfunction + +function! s:warn(cmd, msg) + echohl WarningMsg + execute a:cmd 'a:msg' + echohl None +endfunction + +function! s:esc(path) + return escape(a:path, ' ') +endfunction + +function! s:escrtp(path) + return escape(a:path, ' ,') +endfunction + +function! s:remove_rtp() + for name in s:loaded_names() + let rtp = s:rtp(g:plugs[name]) + execute 'set rtp-='.s:escrtp(rtp) + let after = globpath(rtp, 'after') + if isdirectory(after) + execute 'set rtp-='.s:escrtp(after) + endif + endfor +endfunction + +function! s:reorg_rtp() + if !empty(s:first_rtp) + execute 'set rtp-='.s:first_rtp + execute 'set rtp-='.s:last_rtp + endif + + " &rtp is modified from outside + if exists('s:prtp') && s:prtp !=# &rtp + call s:remove_rtp() + unlet! s:middle + endif + + let s:middle = get(s:, 'middle', &rtp) + let rtps = map(s:loaded_names(), 's:rtp(g:plugs[v:val])') + let afters = filter(map(copy(rtps), 'globpath(v:val, "after")'), '!empty(v:val)') + let rtp = join(map(rtps, 'escape(v:val, ",")'), ',') + \ . ','.s:middle.',' + \ . join(map(afters, 'escape(v:val, ",")'), ',') + let &rtp = substitute(substitute(rtp, ',,*', ',', 'g'), '^,\|,$', '', 'g') + let s:prtp = &rtp + + if !empty(s:first_rtp) + execute 'set rtp^='.s:first_rtp + execute 'set rtp+='.s:last_rtp + endif +endfunction + +function! s:doautocmd(...) + if exists('#'.join(a:000, '#')) + execute 'doautocmd' ((v:version > 703 || has('patch442')) ? '' : '') join(a:000) + endif +endfunction + +function! s:dobufread(names) + for name in a:names + let path = s:rtp(g:plugs[name]) + for dir in ['ftdetect', 'ftplugin', 'after/ftdetect', 'after/ftplugin'] + if len(finddir(dir, path)) + if exists('#BufRead') + doautocmd BufRead + endif + return + endif + endfor + endfor +endfunction + +function! plug#load(...) + if a:0 == 0 + return s:err('Argument missing: plugin name(s) required') + endif + if !exists('g:plugs') + return s:err('plug#begin was not called') + endif + let names = a:0 == 1 && type(a:1) == s:TYPE.list ? a:1 : a:000 + let unknowns = filter(copy(names), '!has_key(g:plugs, v:val)') + if !empty(unknowns) + let s = len(unknowns) > 1 ? 's' : '' + return s:err(printf('Unknown plugin%s: %s', s, join(unknowns, ', '))) + end + let unloaded = filter(copy(names), '!get(s:loaded, v:val, 0)') + if !empty(unloaded) + for name in unloaded + call s:lod([name], ['ftdetect', 'after/ftdetect', 'plugin', 'after/plugin']) + endfor + call s:dobufread(unloaded) + return 1 + end + return 0 +endfunction + +function! s:remove_triggers(name) + if !has_key(s:triggers, a:name) + return + endif + for cmd in s:triggers[a:name].cmd + execute 'silent! delc' cmd + endfor + for map in s:triggers[a:name].map + execute 'silent! unmap' map + execute 'silent! iunmap' map + endfor + call remove(s:triggers, a:name) +endfunction + +function! s:lod(names, types, ...) + for name in a:names + call s:remove_triggers(name) + let s:loaded[name] = 1 + endfor + call s:reorg_rtp() + + for name in a:names + let rtp = s:rtp(g:plugs[name]) + for dir in a:types + call s:source(rtp, dir.'/**/*.vim') + endfor + if a:0 + if !s:source(rtp, a:1) && !empty(s:glob(rtp, a:2)) + execute 'runtime' a:1 + endif + call s:source(rtp, a:2) + endif + call s:doautocmd('User', name) + endfor +endfunction + +function! s:lod_ft(pat, names) + let syn = 'syntax/'.a:pat.'.vim' + call s:lod(a:names, ['plugin', 'after/plugin'], syn, 'after/'.syn) + execute 'autocmd! PlugLOD FileType' a:pat + call s:doautocmd('filetypeplugin', 'FileType') + call s:doautocmd('filetypeindent', 'FileType') +endfunction + +function! s:lod_cmd(cmd, bang, l1, l2, args, names) + call s:lod(a:names, ['ftdetect', 'after/ftdetect', 'plugin', 'after/plugin']) + call s:dobufread(a:names) + execute printf('%s%s%s %s', (a:l1 == a:l2 ? '' : (a:l1.','.a:l2)), a:cmd, a:bang, a:args) +endfunction + +function! s:lod_map(map, names, with_prefix, prefix) + call s:lod(a:names, ['ftdetect', 'after/ftdetect', 'plugin', 'after/plugin']) + call s:dobufread(a:names) + let extra = '' + while 1 + let c = getchar(0) + if c == 0 + break + endif + let extra .= nr2char(c) + endwhile + + if a:with_prefix + let prefix = v:count ? v:count : '' + let prefix .= '"'.v:register.a:prefix + if mode(1) == 'no' + if v:operator == 'c' + let prefix = "\" . prefix + endif + let prefix .= v:operator + endif + call feedkeys(prefix, 'n') + endif + call feedkeys(substitute(a:map, '^', "\", '') . extra) +endfunction + +function! plug#(repo, ...) + if a:0 > 1 + return s:err('Invalid number of arguments (1..2)') + endif + + try + let repo = s:trim(a:repo) + let opts = a:0 == 1 ? s:parse_options(a:1) : s:base_spec + let name = get(opts, 'as', s:plug_fnamemodify(repo, ':t:s?\.git$??')) + let spec = extend(s:infer_properties(name, repo), opts) + if !has_key(g:plugs, name) + call add(g:plugs_order, name) + endif + let g:plugs[name] = spec + let s:loaded[name] = get(s:loaded, name, 0) + catch + return s:err(v:exception) + endtry +endfunction + +function! s:parse_options(arg) + let opts = copy(s:base_spec) + let type = type(a:arg) + if type == s:TYPE.string + let opts.tag = a:arg + elseif type == s:TYPE.dict + call extend(opts, a:arg) + if has_key(opts, 'dir') + let opts.dir = s:dirpath(s:plug_expand(opts.dir)) + endif + else + throw 'Invalid argument type (expected: string or dictionary)' + endif + return opts +endfunction + +function! s:infer_properties(name, repo) + let repo = a:repo + if s:is_local_plug(repo) + return { 'dir': s:dirpath(s:plug_expand(repo)) } + else + if repo =~ ':' + let uri = repo + else + if repo !~ '/' + throw printf('Invalid argument: %s (implicit `vim-scripts'' expansion is deprecated)', repo) + endif + let fmt = get(g:, 'plug_url_format', 'https://git::@github.com/%s.git') + let uri = printf(fmt, repo) + endif + return { 'dir': s:dirpath(g:plug_home.'/'.a:name), 'uri': uri } + endif +endfunction + +function! s:install(force, names) + call s:update_impl(0, a:force, a:names) +endfunction + +function! s:update(force, names) + call s:update_impl(1, a:force, a:names) +endfunction + +function! plug#helptags() + if !exists('g:plugs') + return s:err('plug#begin was not called') + endif + for spec in values(g:plugs) + let docd = join([s:rtp(spec), 'doc'], '/') + if isdirectory(docd) + silent! execute 'helptags' s:esc(docd) + endif + endfor + return 1 +endfunction + +function! s:syntax() + syntax clear + syntax region plug1 start=/\%1l/ end=/\%2l/ contains=plugNumber + syntax region plug2 start=/\%2l/ end=/\%3l/ contains=plugBracket,plugX + syn match plugNumber /[0-9]\+[0-9.]*/ contained + syn match plugBracket /[[\]]/ contained + syn match plugX /x/ contained + syn match plugDash /^-/ + syn match plugPlus /^+/ + syn match plugStar /^*/ + syn match plugMessage /\(^- \)\@<=.*/ + syn match plugName /\(^- \)\@<=[^ ]*:/ + syn match plugSha /\%(: \)\@<=[0-9a-f]\{4,}$/ + syn match plugTag /(tag: [^)]\+)/ + syn match plugInstall /\(^+ \)\@<=[^:]*/ + syn match plugUpdate /\(^* \)\@<=[^:]*/ + syn match plugCommit /^ \X*[0-9a-f]\{7,9} .*/ contains=plugRelDate,plugEdge,plugTag + syn match plugEdge /^ \X\+$/ + syn match plugEdge /^ \X*/ contained nextgroup=plugSha + syn match plugSha /[0-9a-f]\{7,9}/ contained + syn match plugRelDate /([^)]*)$/ contained + syn match plugNotLoaded /(not loaded)$/ + syn match plugError /^x.*/ + syn region plugDeleted start=/^\~ .*/ end=/^\ze\S/ + syn match plugH2 /^.*:\n-\+$/ + syn keyword Function PlugInstall PlugStatus PlugUpdate PlugClean + hi def link plug1 Title + hi def link plug2 Repeat + hi def link plugH2 Type + hi def link plugX Exception + hi def link plugBracket Structure + hi def link plugNumber Number + + hi def link plugDash Special + hi def link plugPlus Constant + hi def link plugStar Boolean + + hi def link plugMessage Function + hi def link plugName Label + hi def link plugInstall Function + hi def link plugUpdate Type + + hi def link plugError Error + hi def link plugDeleted Ignore + hi def link plugRelDate Comment + hi def link plugEdge PreProc + hi def link plugSha Identifier + hi def link plugTag Constant + + hi def link plugNotLoaded Comment +endfunction + +function! s:lpad(str, len) + return a:str . repeat(' ', a:len - len(a:str)) +endfunction + +function! s:lines(msg) + return split(a:msg, "[\r\n]") +endfunction + +function! s:lastline(msg) + return get(s:lines(a:msg), -1, '') +endfunction + +function! s:new_window() + execute get(g:, 'plug_window', 'vertical topleft new') +endfunction + +function! s:plug_window_exists() + let buflist = tabpagebuflist(s:plug_tab) + return !empty(buflist) && index(buflist, s:plug_buf) >= 0 +endfunction + +function! s:switch_in() + if !s:plug_window_exists() + return 0 + endif + + if winbufnr(0) != s:plug_buf + let s:pos = [tabpagenr(), winnr(), winsaveview()] + execute 'normal!' s:plug_tab.'gt' + let winnr = bufwinnr(s:plug_buf) + execute winnr.'wincmd w' + call add(s:pos, winsaveview()) + else + let s:pos = [winsaveview()] + endif + + setlocal modifiable + return 1 +endfunction + +function! s:switch_out(...) + call winrestview(s:pos[-1]) + setlocal nomodifiable + if a:0 > 0 + execute a:1 + endif + + if len(s:pos) > 1 + execute 'normal!' s:pos[0].'gt' + execute s:pos[1] 'wincmd w' + call winrestview(s:pos[2]) + endif +endfunction + +function! s:finish_bindings() + nnoremap R :call retry() + nnoremap D :PlugDiff + nnoremap S :PlugStatus + nnoremap U :call status_update() + xnoremap U :call status_update() + nnoremap ]] :silent! call section('') + nnoremap [[ :silent! call section('b') +endfunction + +function! s:prepare(...) + if empty(s:plug_getcwd()) + throw 'Invalid current working directory. Cannot proceed.' + endif + + for evar in ['$GIT_DIR', '$GIT_WORK_TREE'] + if exists(evar) + throw evar.' detected. Cannot proceed.' + endif + endfor + + call s:job_abort() + if s:switch_in() + if b:plug_preview == 1 + pc + endif + enew + else + call s:new_window() + endif + + nnoremap q :if b:plug_preview==1pcendifbd + if a:0 == 0 + call s:finish_bindings() + endif + let b:plug_preview = -1 + let s:plug_tab = tabpagenr() + let s:plug_buf = winbufnr(0) + call s:assign_name() + + for k in ['', 'L', 'o', 'X', 'd', 'dd'] + execute 'silent! unmap ' k + endfor + setlocal buftype=nofile bufhidden=wipe nobuflisted nolist noswapfile nowrap cursorline modifiable nospell + if exists('+colorcolumn') + setlocal colorcolumn= + endif + setf vim-plug + if exists('g:syntax_on') + call s:syntax() + endif +endfunction + +function! s:assign_name() + " Assign buffer name + let prefix = '[Plugins]' + let name = prefix + let idx = 2 + while bufexists(name) + let name = printf('%s (%s)', prefix, idx) + let idx = idx + 1 + endwhile + silent! execute 'f' fnameescape(name) +endfunction + +function! s:chsh(swap) + let prev = [&shell, &shellcmdflag, &shellredir] + if !s:is_win && a:swap + set shell=sh shellredir=>%s\ 2>&1 + endif + return prev +endfunction + +function! s:bang(cmd, ...) + let batchfile = '' + try + let [sh, shellcmdflag, shrd] = s:chsh(a:0) + " FIXME: Escaping is incomplete. We could use shellescape with eval, + " but it won't work on Windows. + let cmd = a:0 ? s:with_cd(a:cmd, a:1) : a:cmd + if s:is_win + let [batchfile, cmd] = s:batchfile(cmd) + endif + let g:_plug_bang = (s:is_win && has('gui_running') ? 'silent ' : '').'!'.escape(cmd, '#!%') + execute "normal! :execute g:_plug_bang\\" + finally + unlet g:_plug_bang + let [&shell, &shellcmdflag, &shellredir] = [sh, shellcmdflag, shrd] + if s:is_win && filereadable(batchfile) + call delete(batchfile) + endif + endtry + return v:shell_error ? 'Exit status: ' . v:shell_error : '' +endfunction + +function! s:regress_bar() + let bar = substitute(getline(2)[1:-2], '.*\zs=', 'x', '') + call s:progress_bar(2, bar, len(bar)) +endfunction + +function! s:is_updated(dir) + return !empty(s:system_chomp('git log --pretty=format:"%h" "HEAD...HEAD@{1}"', a:dir)) +endfunction + +function! s:do(pull, force, todo) + for [name, spec] in items(a:todo) + if !isdirectory(spec.dir) + continue + endif + let installed = has_key(s:update.new, name) + let updated = installed ? 0 : + \ (a:pull && index(s:update.errors, name) < 0 && s:is_updated(spec.dir)) + if a:force || installed || updated + execute 'cd' s:esc(spec.dir) + call append(3, '- Post-update hook for '. name .' ... ') + let error = '' + let type = type(spec.do) + if type == s:TYPE.string + if spec.do[0] == ':' + if !get(s:loaded, name, 0) + let s:loaded[name] = 1 + call s:reorg_rtp() + endif + call s:load_plugin(spec) + try + execute spec.do[1:] + catch + let error = v:exception + endtry + if !s:plug_window_exists() + cd - + throw 'Warning: vim-plug was terminated by the post-update hook of '.name + endif + else + let error = s:bang(spec.do) + endif + elseif type == s:TYPE.funcref + try + let status = installed ? 'installed' : (updated ? 'updated' : 'unchanged') + call spec.do({ 'name': name, 'status': status, 'force': a:force }) + catch + let error = v:exception + endtry + else + let error = 'Invalid hook type' + endif + call s:switch_in() + call setline(4, empty(error) ? (getline(4) . 'OK') + \ : ('x' . getline(4)[1:] . error)) + if !empty(error) + call add(s:update.errors, name) + call s:regress_bar() + endif + cd - + endif + endfor +endfunction + +function! s:hash_match(a, b) + return stridx(a:a, a:b) == 0 || stridx(a:b, a:a) == 0 +endfunction + +function! s:checkout(spec) + let sha = a:spec.commit + let output = s:system('git rev-parse HEAD', a:spec.dir) + if !v:shell_error && !s:hash_match(sha, s:lines(output)[0]) + let output = s:system( + \ 'git fetch --depth 999999 && git checkout '.plug#shellescape(sha).' --', a:spec.dir) + endif + return output +endfunction + +function! s:finish(pull) + let new_frozen = len(filter(keys(s:update.new), 'g:plugs[v:val].frozen')) + if new_frozen + let s = new_frozen > 1 ? 's' : '' + call append(3, printf('- Installed %d frozen plugin%s', new_frozen, s)) + endif + call append(3, '- Finishing ... ') | 4 + redraw + call plug#helptags() + call plug#end() + call setline(4, getline(4) . 'Done!') + redraw + let msgs = [] + if !empty(s:update.errors) + call add(msgs, "Press 'R' to retry.") + endif + if a:pull && len(s:update.new) < len(filter(getline(5, '$'), + \ "v:val =~ '^- ' && v:val !~# 'Already up.to.date'")) + call add(msgs, "Press 'D' to see the updated changes.") + endif + echo join(msgs, ' ') + call s:finish_bindings() +endfunction + +function! s:retry() + if empty(s:update.errors) + return + endif + echo + call s:update_impl(s:update.pull, s:update.force, + \ extend(copy(s:update.errors), [s:update.threads])) +endfunction + +function! s:is_managed(name) + return has_key(g:plugs[a:name], 'uri') +endfunction + +function! s:names(...) + return sort(filter(keys(g:plugs), 'stridx(v:val, a:1) == 0 && s:is_managed(v:val)')) +endfunction + +function! s:check_ruby() + silent! ruby require 'thread'; VIM::command("let g:plug_ruby = '#{RUBY_VERSION}'") + if !exists('g:plug_ruby') + redraw! + return s:warn('echom', 'Warning: Ruby interface is broken') + endif + let ruby_version = split(g:plug_ruby, '\.') + unlet g:plug_ruby + return s:version_requirement(ruby_version, [1, 8, 7]) +endfunction + +function! s:update_impl(pull, force, args) abort + let sync = index(a:args, '--sync') >= 0 || has('vim_starting') + let args = filter(copy(a:args), 'v:val != "--sync"') + let threads = (len(args) > 0 && args[-1] =~ '^[1-9][0-9]*$') ? + \ remove(args, -1) : get(g:, 'plug_threads', 16) + + let managed = filter(copy(g:plugs), 's:is_managed(v:key)') + let todo = empty(args) ? filter(managed, '!v:val.frozen || !isdirectory(v:val.dir)') : + \ filter(managed, 'index(args, v:key) >= 0') + + if empty(todo) + return s:warn('echo', 'No plugin to '. (a:pull ? 'update' : 'install')) + endif + + if !s:is_win && s:git_version_requirement(2, 3) + let s:git_terminal_prompt = exists('$GIT_TERMINAL_PROMPT') ? $GIT_TERMINAL_PROMPT : '' + let $GIT_TERMINAL_PROMPT = 0 + for plug in values(todo) + let plug.uri = substitute(plug.uri, + \ '^https://git::@github\.com', 'https://github.com', '') + endfor + endif + + if !isdirectory(g:plug_home) + try + call mkdir(g:plug_home, 'p') + catch + return s:err(printf('Invalid plug directory: %s. '. + \ 'Try to call plug#begin with a valid directory', g:plug_home)) + endtry + endif + + if has('nvim') && !exists('*jobwait') && threads > 1 + call s:warn('echom', '[vim-plug] Update Neovim for parallel installer') + endif + + let use_job = s:nvim || s:vim8 + let python = (has('python') || has('python3')) && !use_job + let ruby = has('ruby') && !use_job && (v:version >= 703 || v:version == 702 && has('patch374')) && !(s:is_win && has('gui_running')) && threads > 1 && s:check_ruby() + + let s:update = { + \ 'start': reltime(), + \ 'all': todo, + \ 'todo': copy(todo), + \ 'errors': [], + \ 'pull': a:pull, + \ 'force': a:force, + \ 'new': {}, + \ 'threads': (python || ruby || use_job) ? min([len(todo), threads]) : 1, + \ 'bar': '', + \ 'fin': 0 + \ } + + call s:prepare(1) + call append(0, ['', '']) + normal! 2G + silent! redraw + + let s:clone_opt = get(g:, 'plug_shallow', 1) ? + \ '--depth 1' . (s:git_version_requirement(1, 7, 10) ? ' --no-single-branch' : '') : '' + + if has('win32unix') || has('wsl') + let s:clone_opt .= ' -c core.eol=lf -c core.autocrlf=input' + endif + + let s:submodule_opt = s:git_version_requirement(2, 8) ? ' --jobs='.threads : '' + + " Python version requirement (>= 2.7) + if python && !has('python3') && !ruby && !use_job && s:update.threads > 1 + redir => pyv + silent python import platform; print platform.python_version() + redir END + let python = s:version_requirement( + \ map(split(split(pyv)[0], '\.'), 'str2nr(v:val)'), [2, 6]) + endif + + if (python || ruby) && s:update.threads > 1 + try + let imd = &imd + if s:mac_gui + set noimd + endif + if ruby + call s:update_ruby() + else + call s:update_python() + endif + catch + let lines = getline(4, '$') + let printed = {} + silent! 4,$d _ + for line in lines + let name = s:extract_name(line, '.', '') + if empty(name) || !has_key(printed, name) + call append('$', line) + if !empty(name) + let printed[name] = 1 + if line[0] == 'x' && index(s:update.errors, name) < 0 + call add(s:update.errors, name) + end + endif + endif + endfor + finally + let &imd = imd + call s:update_finish() + endtry + else + call s:update_vim() + while use_job && sync + sleep 100m + if s:update.fin + break + endif + endwhile + endif +endfunction + +function! s:log4(name, msg) + call setline(4, printf('- %s (%s)', a:msg, a:name)) + redraw +endfunction + +function! s:update_finish() + if exists('s:git_terminal_prompt') + let $GIT_TERMINAL_PROMPT = s:git_terminal_prompt + endif + if s:switch_in() + call append(3, '- Updating ...') | 4 + for [name, spec] in items(filter(copy(s:update.all), 'index(s:update.errors, v:key) < 0 && (s:update.force || s:update.pull || has_key(s:update.new, v:key))')) + let [pos, _] = s:logpos(name) + if !pos + continue + endif + if has_key(spec, 'commit') + call s:log4(name, 'Checking out '.spec.commit) + let out = s:checkout(spec) + elseif has_key(spec, 'tag') + let tag = spec.tag + if tag =~ '\*' + let tags = s:lines(s:system('git tag --list '.plug#shellescape(tag).' --sort -version:refname 2>&1', spec.dir)) + if !v:shell_error && !empty(tags) + let tag = tags[0] + call s:log4(name, printf('Latest tag for %s -> %s', spec.tag, tag)) + call append(3, '') + endif + endif + call s:log4(name, 'Checking out '.tag) + let out = s:system('git checkout -q '.plug#shellescape(tag).' -- 2>&1', spec.dir) + else + let branch = get(spec, 'branch', 'master') + call s:log4(name, 'Merging origin/'.s:esc(branch)) + let out = s:system('git checkout -q '.plug#shellescape(branch).' -- 2>&1' + \. (has_key(s:update.new, name) ? '' : ('&& git merge --ff-only '.plug#shellescape('origin/'.branch).' 2>&1')), spec.dir) + endif + if !v:shell_error && filereadable(spec.dir.'/.gitmodules') && + \ (s:update.force || has_key(s:update.new, name) || s:is_updated(spec.dir)) + call s:log4(name, 'Updating submodules. This may take a while.') + let out .= s:bang('git submodule update --init --recursive'.s:submodule_opt.' 2>&1', spec.dir) + endif + let msg = s:format_message(v:shell_error ? 'x': '-', name, out) + if v:shell_error + call add(s:update.errors, name) + call s:regress_bar() + silent execute pos 'd _' + call append(4, msg) | 4 + elseif !empty(out) + call setline(pos, msg[0]) + endif + redraw + endfor + silent 4 d _ + try + call s:do(s:update.pull, s:update.force, filter(copy(s:update.all), 'index(s:update.errors, v:key) < 0 && has_key(v:val, "do")')) + catch + call s:warn('echom', v:exception) + call s:warn('echo', '') + return + endtry + call s:finish(s:update.pull) + call setline(1, 'Updated. Elapsed time: ' . split(reltimestr(reltime(s:update.start)))[0] . ' sec.') + call s:switch_out('normal! gg') + endif +endfunction + +function! s:job_abort() + if (!s:nvim && !s:vim8) || !exists('s:jobs') + return + endif + + for [name, j] in items(s:jobs) + if s:nvim + silent! call jobstop(j.jobid) + elseif s:vim8 + silent! call job_stop(j.jobid) + endif + if j.new + call s:rm_rf(g:plugs[name].dir) + endif + endfor + let s:jobs = {} +endfunction + +function! s:last_non_empty_line(lines) + let len = len(a:lines) + for idx in range(len) + let line = a:lines[len-idx-1] + if !empty(line) + return line + endif + endfor + return '' +endfunction + +function! s:job_out_cb(self, data) abort + let self = a:self + let data = remove(self.lines, -1) . a:data + let lines = map(split(data, "\n", 1), 'split(v:val, "\r", 1)[-1]') + call extend(self.lines, lines) + " To reduce the number of buffer updates + let self.tick = get(self, 'tick', -1) + 1 + if !self.running || self.tick % len(s:jobs) == 0 + let bullet = self.running ? (self.new ? '+' : '*') : (self.error ? 'x' : '-') + let result = self.error ? join(self.lines, "\n") : s:last_non_empty_line(self.lines) + call s:log(bullet, self.name, result) + endif +endfunction + +function! s:job_exit_cb(self, data) abort + let a:self.running = 0 + let a:self.error = a:data != 0 + call s:reap(a:self.name) + call s:tick() +endfunction + +function! s:job_cb(fn, job, ch, data) + if !s:plug_window_exists() " plug window closed + return s:job_abort() + endif + call call(a:fn, [a:job, a:data]) +endfunction + +function! s:nvim_cb(job_id, data, event) dict abort + return a:event == 'stdout' ? + \ s:job_cb('s:job_out_cb', self, 0, join(a:data, "\n")) : + \ s:job_cb('s:job_exit_cb', self, 0, a:data) +endfunction + +function! s:spawn(name, cmd, opts) + let job = { 'name': a:name, 'running': 1, 'error': 0, 'lines': [''], + \ 'new': get(a:opts, 'new', 0) } + let s:jobs[a:name] = job + let cmd = has_key(a:opts, 'dir') ? s:with_cd(a:cmd, a:opts.dir, 0) : a:cmd + let argv = s:is_win ? ['cmd', '/s', '/c', '"'.cmd.'"'] : ['sh', '-c', cmd] + + if s:nvim + call extend(job, { + \ 'on_stdout': function('s:nvim_cb'), + \ 'on_exit': function('s:nvim_cb'), + \ }) + let jid = s:plug_call('jobstart', argv, job) + if jid > 0 + let job.jobid = jid + else + let job.running = 0 + let job.error = 1 + let job.lines = [jid < 0 ? argv[0].' is not executable' : + \ 'Invalid arguments (or job table is full)'] + endif + elseif s:vim8 + let jid = job_start(s:is_win ? join(argv, ' ') : argv, { + \ 'out_cb': function('s:job_cb', ['s:job_out_cb', job]), + \ 'exit_cb': function('s:job_cb', ['s:job_exit_cb', job]), + \ 'out_mode': 'raw' + \}) + if job_status(jid) == 'run' + let job.jobid = jid + else + let job.running = 0 + let job.error = 1 + let job.lines = ['Failed to start job'] + endif + else + let job.lines = s:lines(call('s:system', [cmd])) + let job.error = v:shell_error != 0 + let job.running = 0 + endif +endfunction + +function! s:reap(name) + let job = s:jobs[a:name] + if job.error + call add(s:update.errors, a:name) + elseif get(job, 'new', 0) + let s:update.new[a:name] = 1 + endif + let s:update.bar .= job.error ? 'x' : '=' + + let bullet = job.error ? 'x' : '-' + let result = job.error ? join(job.lines, "\n") : s:last_non_empty_line(job.lines) + call s:log(bullet, a:name, empty(result) ? 'OK' : result) + call s:bar() + + call remove(s:jobs, a:name) +endfunction + +function! s:bar() + if s:switch_in() + let total = len(s:update.all) + call setline(1, (s:update.pull ? 'Updating' : 'Installing'). + \ ' plugins ('.len(s:update.bar).'/'.total.')') + call s:progress_bar(2, s:update.bar, total) + call s:switch_out() + endif +endfunction + +function! s:logpos(name) + for i in range(4, line('$')) + if getline(i) =~# '^[-+x*] '.a:name.':' + for j in range(i + 1, line('$')) + if getline(j) !~ '^ ' + return [i, j - 1] + endif + endfor + return [i, i] + endif + endfor + return [0, 0] +endfunction + +function! s:log(bullet, name, lines) + if s:switch_in() + let [b, e] = s:logpos(a:name) + if b > 0 + silent execute printf('%d,%d d _', b, e) + if b > winheight('.') + let b = 4 + endif + else + let b = 4 + endif + " FIXME For some reason, nomodifiable is set after :d in vim8 + setlocal modifiable + call append(b - 1, s:format_message(a:bullet, a:name, a:lines)) + call s:switch_out() + endif +endfunction + +function! s:update_vim() + let s:jobs = {} + + call s:bar() + call s:tick() +endfunction + +function! s:tick() + let pull = s:update.pull + let prog = s:progress_opt(s:nvim || s:vim8) +while 1 " Without TCO, Vim stack is bound to explode + if empty(s:update.todo) + if empty(s:jobs) && !s:update.fin + call s:update_finish() + let s:update.fin = 1 + endif + return + endif + + let name = keys(s:update.todo)[0] + let spec = remove(s:update.todo, name) + let new = empty(globpath(spec.dir, '.git', 1)) + + call s:log(new ? '+' : '*', name, pull ? 'Updating ...' : 'Installing ...') + redraw + + let has_tag = has_key(spec, 'tag') + if !new + let [error, _] = s:git_validate(spec, 0) + if empty(error) + if pull + let fetch_opt = (has_tag && !empty(globpath(spec.dir, '.git/shallow'))) ? '--depth 99999999' : '' + call s:spawn(name, printf('git fetch %s %s 2>&1', fetch_opt, prog), { 'dir': spec.dir }) + else + let s:jobs[name] = { 'running': 0, 'lines': ['Already installed'], 'error': 0 } + endif + else + let s:jobs[name] = { 'running': 0, 'lines': s:lines(error), 'error': 1 } + endif + else + call s:spawn(name, + \ printf('git clone %s %s %s %s 2>&1', + \ has_tag ? '' : s:clone_opt, + \ prog, + \ plug#shellescape(spec.uri, {'script': 0}), + \ plug#shellescape(s:trim(spec.dir), {'script': 0})), { 'new': 1 }) + endif + + if !s:jobs[name].running + call s:reap(name) + endif + if len(s:jobs) >= s:update.threads + break + endif +endwhile +endfunction + +function! s:update_python() +let py_exe = has('python') ? 'python' : 'python3' +execute py_exe "<< EOF" +import datetime +import functools +import os +try: + import queue +except ImportError: + import Queue as queue +import random +import re +import shutil +import signal +import subprocess +import tempfile +import threading as thr +import time +import traceback +import vim + +G_NVIM = vim.eval("has('nvim')") == '1' +G_PULL = vim.eval('s:update.pull') == '1' +G_RETRIES = int(vim.eval('get(g:, "plug_retries", 2)')) + 1 +G_TIMEOUT = int(vim.eval('get(g:, "plug_timeout", 60)')) +G_CLONE_OPT = vim.eval('s:clone_opt') +G_PROGRESS = vim.eval('s:progress_opt(1)') +G_LOG_PROB = 1.0 / int(vim.eval('s:update.threads')) +G_STOP = thr.Event() +G_IS_WIN = vim.eval('s:is_win') == '1' + +class PlugError(Exception): + def __init__(self, msg): + self.msg = msg +class CmdTimedOut(PlugError): + pass +class CmdFailed(PlugError): + pass +class InvalidURI(PlugError): + pass +class Action(object): + INSTALL, UPDATE, ERROR, DONE = ['+', '*', 'x', '-'] + +class Buffer(object): + def __init__(self, lock, num_plugs, is_pull): + self.bar = '' + self.event = 'Updating' if is_pull else 'Installing' + self.lock = lock + self.maxy = int(vim.eval('winheight(".")')) + self.num_plugs = num_plugs + + def __where(self, name): + """ Find first line with name in current buffer. Return line num. """ + found, lnum = False, 0 + matcher = re.compile('^[-+x*] {0}:'.format(name)) + for line in vim.current.buffer: + if matcher.search(line) is not None: + found = True + break + lnum += 1 + + if not found: + lnum = -1 + return lnum + + def header(self): + curbuf = vim.current.buffer + curbuf[0] = self.event + ' plugins ({0}/{1})'.format(len(self.bar), self.num_plugs) + + num_spaces = self.num_plugs - len(self.bar) + curbuf[1] = '[{0}{1}]'.format(self.bar, num_spaces * ' ') + + with self.lock: + vim.command('normal! 2G') + vim.command('redraw') + + def write(self, action, name, lines): + first, rest = lines[0], lines[1:] + msg = ['{0} {1}{2}{3}'.format(action, name, ': ' if first else '', first)] + msg.extend([' ' + line for line in rest]) + + try: + if action == Action.ERROR: + self.bar += 'x' + vim.command("call add(s:update.errors, '{0}')".format(name)) + elif action == Action.DONE: + self.bar += '=' + + curbuf = vim.current.buffer + lnum = self.__where(name) + if lnum != -1: # Found matching line num + del curbuf[lnum] + if lnum > self.maxy and action in set([Action.INSTALL, Action.UPDATE]): + lnum = 3 + else: + lnum = 3 + curbuf.append(msg, lnum) + + self.header() + except vim.error: + pass + +class Command(object): + CD = 'cd /d' if G_IS_WIN else 'cd' + + def __init__(self, cmd, cmd_dir=None, timeout=60, cb=None, clean=None): + self.cmd = cmd + if cmd_dir: + self.cmd = '{0} {1} && {2}'.format(Command.CD, cmd_dir, self.cmd) + self.timeout = timeout + self.callback = cb if cb else (lambda msg: None) + self.clean = clean if clean else (lambda: None) + self.proc = None + + @property + def alive(self): + """ Returns true only if command still running. """ + return self.proc and self.proc.poll() is None + + def execute(self, ntries=3): + """ Execute the command with ntries if CmdTimedOut. + Returns the output of the command if no Exception. + """ + attempt, finished, limit = 0, False, self.timeout + + while not finished: + try: + attempt += 1 + result = self.try_command() + finished = True + return result + except CmdTimedOut: + if attempt != ntries: + self.notify_retry() + self.timeout += limit + else: + raise + + def notify_retry(self): + """ Retry required for command, notify user. """ + for count in range(3, 0, -1): + if G_STOP.is_set(): + raise KeyboardInterrupt + msg = 'Timeout. Will retry in {0} second{1} ...'.format( + count, 's' if count != 1 else '') + self.callback([msg]) + time.sleep(1) + self.callback(['Retrying ...']) + + def try_command(self): + """ Execute a cmd & poll for callback. Returns list of output. + Raises CmdFailed -> return code for Popen isn't 0 + Raises CmdTimedOut -> command exceeded timeout without new output + """ + first_line = True + + try: + tfile = tempfile.NamedTemporaryFile(mode='w+b') + preexec_fn = not G_IS_WIN and os.setsid or None + self.proc = subprocess.Popen(self.cmd, stdout=tfile, + stderr=subprocess.STDOUT, + stdin=subprocess.PIPE, shell=True, + preexec_fn=preexec_fn) + thrd = thr.Thread(target=(lambda proc: proc.wait()), args=(self.proc,)) + thrd.start() + + thread_not_started = True + while thread_not_started: + try: + thrd.join(0.1) + thread_not_started = False + except RuntimeError: + pass + + while self.alive: + if G_STOP.is_set(): + raise KeyboardInterrupt + + if first_line or random.random() < G_LOG_PROB: + first_line = False + line = '' if G_IS_WIN else nonblock_read(tfile.name) + if line: + self.callback([line]) + + time_diff = time.time() - os.path.getmtime(tfile.name) + if time_diff > self.timeout: + raise CmdTimedOut(['Timeout!']) + + thrd.join(0.5) + + tfile.seek(0) + result = [line.decode('utf-8', 'replace').rstrip() for line in tfile] + + if self.proc.returncode != 0: + raise CmdFailed([''] + result) + + return result + except: + self.terminate() + raise + + def terminate(self): + """ Terminate process and cleanup. """ + if self.alive: + if G_IS_WIN: + os.kill(self.proc.pid, signal.SIGINT) + else: + os.killpg(self.proc.pid, signal.SIGTERM) + self.clean() + +class Plugin(object): + def __init__(self, name, args, buf_q, lock): + self.name = name + self.args = args + self.buf_q = buf_q + self.lock = lock + self.tag = args.get('tag', 0) + + def manage(self): + try: + if os.path.exists(self.args['dir']): + self.update() + else: + self.install() + with self.lock: + thread_vim_command("let s:update.new['{0}'] = 1".format(self.name)) + except PlugError as exc: + self.write(Action.ERROR, self.name, exc.msg) + except KeyboardInterrupt: + G_STOP.set() + self.write(Action.ERROR, self.name, ['Interrupted!']) + except: + # Any exception except those above print stack trace + msg = 'Trace:\n{0}'.format(traceback.format_exc().rstrip()) + self.write(Action.ERROR, self.name, msg.split('\n')) + raise + + def install(self): + target = self.args['dir'] + if target[-1] == '\\': + target = target[0:-1] + + def clean(target): + def _clean(): + try: + shutil.rmtree(target) + except OSError: + pass + return _clean + + self.write(Action.INSTALL, self.name, ['Installing ...']) + callback = functools.partial(self.write, Action.INSTALL, self.name) + cmd = 'git clone {0} {1} {2} {3} 2>&1'.format( + '' if self.tag else G_CLONE_OPT, G_PROGRESS, self.args['uri'], + esc(target)) + com = Command(cmd, None, G_TIMEOUT, callback, clean(target)) + result = com.execute(G_RETRIES) + self.write(Action.DONE, self.name, result[-1:]) + + def repo_uri(self): + cmd = 'git rev-parse --abbrev-ref HEAD 2>&1 && git config -f .git/config remote.origin.url' + command = Command(cmd, self.args['dir'], G_TIMEOUT,) + result = command.execute(G_RETRIES) + return result[-1] + + def update(self): + actual_uri = self.repo_uri() + expect_uri = self.args['uri'] + regex = re.compile(r'^(?:\w+://)?(?:[^@/]*@)?([^:/]*(?::[0-9]*)?)[:/](.*?)(?:\.git)?/?$') + ma = regex.match(actual_uri) + mb = regex.match(expect_uri) + if ma is None or mb is None or ma.groups() != mb.groups(): + msg = ['', + 'Invalid URI: {0}'.format(actual_uri), + 'Expected {0}'.format(expect_uri), + 'PlugClean required.'] + raise InvalidURI(msg) + + if G_PULL: + self.write(Action.UPDATE, self.name, ['Updating ...']) + callback = functools.partial(self.write, Action.UPDATE, self.name) + fetch_opt = '--depth 99999999' if self.tag and os.path.isfile(os.path.join(self.args['dir'], '.git/shallow')) else '' + cmd = 'git fetch {0} {1} 2>&1'.format(fetch_opt, G_PROGRESS) + com = Command(cmd, self.args['dir'], G_TIMEOUT, callback) + result = com.execute(G_RETRIES) + self.write(Action.DONE, self.name, result[-1:]) + else: + self.write(Action.DONE, self.name, ['Already installed']) + + def write(self, action, name, msg): + self.buf_q.put((action, name, msg)) + +class PlugThread(thr.Thread): + def __init__(self, tname, args): + super(PlugThread, self).__init__() + self.tname = tname + self.args = args + + def run(self): + thr.current_thread().name = self.tname + buf_q, work_q, lock = self.args + + try: + while not G_STOP.is_set(): + name, args = work_q.get_nowait() + plug = Plugin(name, args, buf_q, lock) + plug.manage() + work_q.task_done() + except queue.Empty: + pass + +class RefreshThread(thr.Thread): + def __init__(self, lock): + super(RefreshThread, self).__init__() + self.lock = lock + self.running = True + + def run(self): + while self.running: + with self.lock: + thread_vim_command('noautocmd normal! a') + time.sleep(0.33) + + def stop(self): + self.running = False + +if G_NVIM: + def thread_vim_command(cmd): + vim.session.threadsafe_call(lambda: vim.command(cmd)) +else: + def thread_vim_command(cmd): + vim.command(cmd) + +def esc(name): + return '"' + name.replace('"', '\"') + '"' + +def nonblock_read(fname): + """ Read a file with nonblock flag. Return the last line. """ + fread = os.open(fname, os.O_RDONLY | os.O_NONBLOCK) + buf = os.read(fread, 100000).decode('utf-8', 'replace') + os.close(fread) + + line = buf.rstrip('\r\n') + left = max(line.rfind('\r'), line.rfind('\n')) + if left != -1: + left += 1 + line = line[left:] + + return line + +def main(): + thr.current_thread().name = 'main' + nthreads = int(vim.eval('s:update.threads')) + plugs = vim.eval('s:update.todo') + mac_gui = vim.eval('s:mac_gui') == '1' + + lock = thr.Lock() + buf = Buffer(lock, len(plugs), G_PULL) + buf_q, work_q = queue.Queue(), queue.Queue() + for work in plugs.items(): + work_q.put(work) + + start_cnt = thr.active_count() + for num in range(nthreads): + tname = 'PlugT-{0:02}'.format(num) + thread = PlugThread(tname, (buf_q, work_q, lock)) + thread.start() + if mac_gui: + rthread = RefreshThread(lock) + rthread.start() + + while not buf_q.empty() or thr.active_count() != start_cnt: + try: + action, name, msg = buf_q.get(True, 0.25) + buf.write(action, name, ['OK'] if not msg else msg) + buf_q.task_done() + except queue.Empty: + pass + except KeyboardInterrupt: + G_STOP.set() + + if mac_gui: + rthread.stop() + rthread.join() + +main() +EOF +endfunction + +function! s:update_ruby() + ruby << EOF + module PlugStream + SEP = ["\r", "\n", nil] + def get_line + buffer = '' + loop do + char = readchar rescue return + if SEP.include? char.chr + buffer << $/ + break + else + buffer << char + end + end + buffer + end + end unless defined?(PlugStream) + + def esc arg + %["#{arg.gsub('"', '\"')}"] + end + + def killall pid + pids = [pid] + if /mswin|mingw|bccwin/ =~ RUBY_PLATFORM + pids.each { |pid| Process.kill 'INT', pid.to_i rescue nil } + else + unless `which pgrep 2> /dev/null`.empty? + children = pids + until children.empty? + children = children.map { |pid| + `pgrep -P #{pid}`.lines.map { |l| l.chomp } + }.flatten + pids += children + end + end + pids.each { |pid| Process.kill 'TERM', pid.to_i rescue nil } + end + end + + def compare_git_uri a, b + regex = %r{^(?:\w+://)?(?:[^@/]*@)?([^:/]*(?::[0-9]*)?)[:/](.*?)(?:\.git)?/?$} + regex.match(a).to_a.drop(1) == regex.match(b).to_a.drop(1) + end + + require 'thread' + require 'fileutils' + require 'timeout' + running = true + iswin = VIM::evaluate('s:is_win').to_i == 1 + pull = VIM::evaluate('s:update.pull').to_i == 1 + base = VIM::evaluate('g:plug_home') + all = VIM::evaluate('s:update.todo') + limit = VIM::evaluate('get(g:, "plug_timeout", 60)') + tries = VIM::evaluate('get(g:, "plug_retries", 2)') + 1 + nthr = VIM::evaluate('s:update.threads').to_i + maxy = VIM::evaluate('winheight(".")').to_i + vim7 = VIM::evaluate('v:version').to_i <= 703 && RUBY_PLATFORM =~ /darwin/ + cd = iswin ? 'cd /d' : 'cd' + tot = VIM::evaluate('len(s:update.todo)') || 0 + bar = '' + skip = 'Already installed' + mtx = Mutex.new + take1 = proc { mtx.synchronize { running && all.shift } } + logh = proc { + cnt = bar.length + $curbuf[1] = "#{pull ? 'Updating' : 'Installing'} plugins (#{cnt}/#{tot})" + $curbuf[2] = '[' + bar.ljust(tot) + ']' + VIM::command('normal! 2G') + VIM::command('redraw') + } + where = proc { |name| (1..($curbuf.length)).find { |l| $curbuf[l] =~ /^[-+x*] #{name}:/ } } + log = proc { |name, result, type| + mtx.synchronize do + ing = ![true, false].include?(type) + bar += type ? '=' : 'x' unless ing + b = case type + when :install then '+' when :update then '*' + when true, nil then '-' else + VIM::command("call add(s:update.errors, '#{name}')") + 'x' + end + result = + if type || type.nil? + ["#{b} #{name}: #{result.lines.to_a.last || 'OK'}"] + elsif result =~ /^Interrupted|^Timeout/ + ["#{b} #{name}: #{result}"] + else + ["#{b} #{name}"] + result.lines.map { |l| " " << l } + end + if lnum = where.call(name) + $curbuf.delete lnum + lnum = 4 if ing && lnum > maxy + end + result.each_with_index do |line, offset| + $curbuf.append((lnum || 4) - 1 + offset, line.gsub(/\e\[./, '').chomp) + end + logh.call + end + } + bt = proc { |cmd, name, type, cleanup| + tried = timeout = 0 + begin + tried += 1 + timeout += limit + fd = nil + data = '' + if iswin + Timeout::timeout(timeout) do + tmp = VIM::evaluate('tempname()') + system("(#{cmd}) > #{tmp}") + data = File.read(tmp).chomp + File.unlink tmp rescue nil + end + else + fd = IO.popen(cmd).extend(PlugStream) + first_line = true + log_prob = 1.0 / nthr + while line = Timeout::timeout(timeout) { fd.get_line } + data << line + log.call name, line.chomp, type if name && (first_line || rand < log_prob) + first_line = false + end + fd.close + end + [$? == 0, data.chomp] + rescue Timeout::Error, Interrupt => e + if fd && !fd.closed? + killall fd.pid + fd.close + end + cleanup.call if cleanup + if e.is_a?(Timeout::Error) && tried < tries + 3.downto(1) do |countdown| + s = countdown > 1 ? 's' : '' + log.call name, "Timeout. Will retry in #{countdown} second#{s} ...", type + sleep 1 + end + log.call name, 'Retrying ...', type + retry + end + [false, e.is_a?(Interrupt) ? "Interrupted!" : "Timeout!"] + end + } + main = Thread.current + threads = [] + watcher = Thread.new { + if vim7 + while VIM::evaluate('getchar(1)') + sleep 0.1 + end + else + require 'io/console' # >= Ruby 1.9 + nil until IO.console.getch == 3.chr + end + mtx.synchronize do + running = false + threads.each { |t| t.raise Interrupt } unless vim7 + end + threads.each { |t| t.join rescue nil } + main.kill + } + refresh = Thread.new { + while true + mtx.synchronize do + break unless running + VIM::command('noautocmd normal! a') + end + sleep 0.2 + end + } if VIM::evaluate('s:mac_gui') == 1 + + clone_opt = VIM::evaluate('s:clone_opt') + progress = VIM::evaluate('s:progress_opt(1)') + nthr.times do + mtx.synchronize do + threads << Thread.new { + while pair = take1.call + name = pair.first + dir, uri, tag = pair.last.values_at *%w[dir uri tag] + exists = File.directory? dir + ok, result = + if exists + chdir = "#{cd} #{iswin ? dir : esc(dir)}" + ret, data = bt.call "#{chdir} && git rev-parse --abbrev-ref HEAD 2>&1 && git config -f .git/config remote.origin.url", nil, nil, nil + current_uri = data.lines.to_a.last + if !ret + if data =~ /^Interrupted|^Timeout/ + [false, data] + else + [false, [data.chomp, "PlugClean required."].join($/)] + end + elsif !compare_git_uri(current_uri, uri) + [false, ["Invalid URI: #{current_uri}", + "Expected: #{uri}", + "PlugClean required."].join($/)] + else + if pull + log.call name, 'Updating ...', :update + fetch_opt = (tag && File.exist?(File.join(dir, '.git/shallow'))) ? '--depth 99999999' : '' + bt.call "#{chdir} && git fetch #{fetch_opt} #{progress} 2>&1", name, :update, nil + else + [true, skip] + end + end + else + d = esc dir.sub(%r{[\\/]+$}, '') + log.call name, 'Installing ...', :install + bt.call "git clone #{clone_opt unless tag} #{progress} #{uri} #{d} 2>&1", name, :install, proc { + FileUtils.rm_rf dir + } + end + mtx.synchronize { VIM::command("let s:update.new['#{name}'] = 1") } if !exists && ok + log.call name, result, ok + end + } if running + end + end + threads.each { |t| t.join rescue nil } + logh.call + refresh.kill if refresh + watcher.kill +EOF +endfunction + +function! s:shellesc_cmd(arg, script) + let escaped = substitute('"'.a:arg.'"', '[&|<>()@^!"]', '^&', 'g') + return substitute(escaped, '%', (a:script ? '%' : '^') . '&', 'g') +endfunction + +function! s:shellesc_ps1(arg) + return "'".substitute(escape(a:arg, '\"'), "'", "''", 'g')."'" +endfunction + +function! s:shellesc_sh(arg) + return "'".substitute(a:arg, "'", "'\\\\''", 'g')."'" +endfunction + +function! plug#shellescape(arg, ...) + let opts = a:0 > 0 && type(a:1) == s:TYPE.dict ? a:1 : {} + let shell = get(opts, 'shell', s:is_win ? 'cmd.exe' : 'sh') + let script = get(opts, 'script', 1) + if shell =~# 'cmd\.exe' + return s:shellesc_cmd(a:arg, script) + elseif shell =~# 'powershell\.exe' || shell =~# 'pwsh$' + return s:shellesc_ps1(a:arg) + endif + return s:shellesc_sh(a:arg) +endfunction + +function! s:glob_dir(path) + return map(filter(s:glob(a:path, '**'), 'isdirectory(v:val)'), 's:dirpath(v:val)') +endfunction + +function! s:progress_bar(line, bar, total) + call setline(a:line, '[' . s:lpad(a:bar, a:total) . ']') +endfunction + +function! s:compare_git_uri(a, b) + " See `git help clone' + " https:// [user@] github.com[:port] / junegunn/vim-plug [.git] + " [git@] github.com[:port] : junegunn/vim-plug [.git] + " file:// / junegunn/vim-plug [/] + " / junegunn/vim-plug [/] + let pat = '^\%(\w\+://\)\='.'\%([^@/]*@\)\='.'\([^:/]*\%(:[0-9]*\)\=\)'.'[:/]'.'\(.\{-}\)'.'\%(\.git\)\=/\?$' + let ma = matchlist(a:a, pat) + let mb = matchlist(a:b, pat) + return ma[1:2] ==# mb[1:2] +endfunction + +function! s:format_message(bullet, name, message) + if a:bullet != 'x' + return [printf('%s %s: %s', a:bullet, a:name, s:lastline(a:message))] + else + let lines = map(s:lines(a:message), '" ".v:val') + return extend([printf('x %s:', a:name)], lines) + endif +endfunction + +function! s:with_cd(cmd, dir, ...) + let script = a:0 > 0 ? a:1 : 1 + return printf('cd%s %s && %s', s:is_win ? ' /d' : '', plug#shellescape(a:dir, {'script': script}), a:cmd) +endfunction + +function! s:system(cmd, ...) + let batchfile = '' + try + let [sh, shellcmdflag, shrd] = s:chsh(1) + let cmd = a:0 > 0 ? s:with_cd(a:cmd, a:1) : a:cmd + if s:is_win + let [batchfile, cmd] = s:batchfile(cmd) + endif + return system(cmd) + finally + let [&shell, &shellcmdflag, &shellredir] = [sh, shellcmdflag, shrd] + if s:is_win && filereadable(batchfile) + call delete(batchfile) + endif + endtry +endfunction + +function! s:system_chomp(...) + let ret = call('s:system', a:000) + return v:shell_error ? '' : substitute(ret, '\n$', '', '') +endfunction + +function! s:git_validate(spec, check_branch) + let err = '' + if isdirectory(a:spec.dir) + let result = s:lines(s:system('git rev-parse --abbrev-ref HEAD 2>&1 && git config -f .git/config remote.origin.url', a:spec.dir)) + let remote = result[-1] + if v:shell_error + let err = join([remote, 'PlugClean required.'], "\n") + elseif !s:compare_git_uri(remote, a:spec.uri) + let err = join(['Invalid URI: '.remote, + \ 'Expected: '.a:spec.uri, + \ 'PlugClean required.'], "\n") + elseif a:check_branch && has_key(a:spec, 'commit') + let result = s:lines(s:system('git rev-parse HEAD 2>&1', a:spec.dir)) + let sha = result[-1] + if v:shell_error + let err = join(add(result, 'PlugClean required.'), "\n") + elseif !s:hash_match(sha, a:spec.commit) + let err = join([printf('Invalid HEAD (expected: %s, actual: %s)', + \ a:spec.commit[:6], sha[:6]), + \ 'PlugUpdate required.'], "\n") + endif + elseif a:check_branch + let branch = result[0] + " Check tag + if has_key(a:spec, 'tag') + let tag = s:system_chomp('git describe --exact-match --tags HEAD 2>&1', a:spec.dir) + if a:spec.tag !=# tag && a:spec.tag !~ '\*' + let err = printf('Invalid tag: %s (expected: %s). Try PlugUpdate.', + \ (empty(tag) ? 'N/A' : tag), a:spec.tag) + endif + " Check branch + elseif a:spec.branch !=# branch + let err = printf('Invalid branch: %s (expected: %s). Try PlugUpdate.', + \ branch, a:spec.branch) + endif + if empty(err) + let [ahead, behind] = split(s:lastline(s:system(printf( + \ 'git rev-list --count --left-right HEAD...origin/%s', + \ a:spec.branch), a:spec.dir)), '\t') + if !v:shell_error && ahead + if behind + " Only mention PlugClean if diverged, otherwise it's likely to be + " pushable (and probably not that messed up). + let err = printf( + \ "Diverged from origin/%s (%d commit(s) ahead and %d commit(s) behind!\n" + \ .'Backup local changes and run PlugClean and PlugUpdate to reinstall it.', a:spec.branch, ahead, behind) + else + let err = printf("Ahead of origin/%s by %d commit(s).\n" + \ .'Cannot update until local changes are pushed.', + \ a:spec.branch, ahead) + endif + endif + endif + endif + else + let err = 'Not found' + endif + return [err, err =~# 'PlugClean'] +endfunction + +function! s:rm_rf(dir) + if isdirectory(a:dir) + call s:system((s:is_win ? 'rmdir /S /Q ' : 'rm -rf ') . plug#shellescape(a:dir)) + endif +endfunction + +function! s:clean(force) + call s:prepare() + call append(0, 'Searching for invalid plugins in '.g:plug_home) + call append(1, '') + + " List of valid directories + let dirs = [] + let errs = {} + let [cnt, total] = [0, len(g:plugs)] + for [name, spec] in items(g:plugs) + if !s:is_managed(name) + call add(dirs, spec.dir) + else + let [err, clean] = s:git_validate(spec, 1) + if clean + let errs[spec.dir] = s:lines(err)[0] + else + call add(dirs, spec.dir) + endif + endif + let cnt += 1 + call s:progress_bar(2, repeat('=', cnt), total) + normal! 2G + redraw + endfor + + let allowed = {} + for dir in dirs + let allowed[s:dirpath(s:plug_fnamemodify(dir, ':h:h'))] = 1 + let allowed[dir] = 1 + for child in s:glob_dir(dir) + let allowed[child] = 1 + endfor + endfor + + let todo = [] + let found = sort(s:glob_dir(g:plug_home)) + while !empty(found) + let f = remove(found, 0) + if !has_key(allowed, f) && isdirectory(f) + call add(todo, f) + call append(line('$'), '- ' . f) + if has_key(errs, f) + call append(line('$'), ' ' . errs[f]) + endif + let found = filter(found, 'stridx(v:val, f) != 0') + end + endwhile + + 4 + redraw + if empty(todo) + call append(line('$'), 'Already clean.') + else + let s:clean_count = 0 + call append(3, ['Directories to delete:', '']) + redraw! + if a:force || s:ask_no_interrupt('Delete all directories?') + call s:delete([6, line('$')], 1) + else + call setline(4, 'Cancelled.') + nnoremap d :set opfunc=delete_opg@ + nmap dd d_ + xnoremap d :call delete_op(visualmode(), 1) + echo 'Delete the lines (d{motion}) to delete the corresponding directories' + endif + endif + 4 + setlocal nomodifiable +endfunction + +function! s:delete_op(type, ...) + call s:delete(a:0 ? [line("'<"), line("'>")] : [line("'["), line("']")], 0) +endfunction + +function! s:delete(range, force) + let [l1, l2] = a:range + let force = a:force + while l1 <= l2 + let line = getline(l1) + if line =~ '^- ' && isdirectory(line[2:]) + execute l1 + redraw! + let answer = force ? 1 : s:ask('Delete '.line[2:].'?', 1) + let force = force || answer > 1 + if answer + call s:rm_rf(line[2:]) + setlocal modifiable + call setline(l1, '~'.line[1:]) + let s:clean_count += 1 + call setline(4, printf('Removed %d directories.', s:clean_count)) + setlocal nomodifiable + endif + endif + let l1 += 1 + endwhile +endfunction + +function! s:upgrade() + echo 'Downloading the latest version of vim-plug' + redraw + let tmp = s:plug_tempname() + let new = tmp . '/plug.vim' + + try + let out = s:system(printf('git clone --depth 1 %s %s', plug#shellescape(s:plug_src), plug#shellescape(tmp))) + if v:shell_error + return s:err('Error upgrading vim-plug: '. out) + endif + + if readfile(s:me) ==# readfile(new) + echo 'vim-plug is already up-to-date' + return 0 + else + call rename(s:me, s:me . '.old') + call rename(new, s:me) + unlet g:loaded_plug + echo 'vim-plug has been upgraded' + return 1 + endif + finally + silent! call s:rm_rf(tmp) + endtry +endfunction + +function! s:upgrade_specs() + for spec in values(g:plugs) + let spec.frozen = get(spec, 'frozen', 0) + endfor +endfunction + +function! s:status() + call s:prepare() + call append(0, 'Checking plugins') + call append(1, '') + + let ecnt = 0 + let unloaded = 0 + let [cnt, total] = [0, len(g:plugs)] + for [name, spec] in items(g:plugs) + let is_dir = isdirectory(spec.dir) + if has_key(spec, 'uri') + if is_dir + let [err, _] = s:git_validate(spec, 1) + let [valid, msg] = [empty(err), empty(err) ? 'OK' : err] + else + let [valid, msg] = [0, 'Not found. Try PlugInstall.'] + endif + else + if is_dir + let [valid, msg] = [1, 'OK'] + else + let [valid, msg] = [0, 'Not found.'] + endif + endif + let cnt += 1 + let ecnt += !valid + " `s:loaded` entry can be missing if PlugUpgraded + if is_dir && get(s:loaded, name, -1) == 0 + let unloaded = 1 + let msg .= ' (not loaded)' + endif + call s:progress_bar(2, repeat('=', cnt), total) + call append(3, s:format_message(valid ? '-' : 'x', name, msg)) + normal! 2G + redraw + endfor + call setline(1, 'Finished. '.ecnt.' error(s).') + normal! gg + setlocal nomodifiable + if unloaded + echo "Press 'L' on each line to load plugin, or 'U' to update" + nnoremap L :call status_load(line('.')) + xnoremap L :call status_load(line('.')) + end +endfunction + +function! s:extract_name(str, prefix, suffix) + return matchstr(a:str, '^'.a:prefix.' \zs[^:]\+\ze:.*'.a:suffix.'$') +endfunction + +function! s:status_load(lnum) + let line = getline(a:lnum) + let name = s:extract_name(line, '-', '(not loaded)') + if !empty(name) + call plug#load(name) + setlocal modifiable + call setline(a:lnum, substitute(line, ' (not loaded)$', '', '')) + setlocal nomodifiable + endif +endfunction + +function! s:status_update() range + let lines = getline(a:firstline, a:lastline) + let names = filter(map(lines, 's:extract_name(v:val, "[x-]", "")'), '!empty(v:val)') + if !empty(names) + echo + execute 'PlugUpdate' join(names) + endif +endfunction + +function! s:is_preview_window_open() + silent! wincmd P + if &previewwindow + wincmd p + return 1 + endif +endfunction + +function! s:find_name(lnum) + for lnum in reverse(range(1, a:lnum)) + let line = getline(lnum) + if empty(line) + return '' + endif + let name = s:extract_name(line, '-', '') + if !empty(name) + return name + endif + endfor + return '' +endfunction + +function! s:preview_commit() + if b:plug_preview < 0 + let b:plug_preview = !s:is_preview_window_open() + endif + + let sha = matchstr(getline('.'), '^ \X*\zs[0-9a-f]\{7,9}') + if empty(sha) + return + endif + + let name = s:find_name(line('.')) + if empty(name) || !has_key(g:plugs, name) || !isdirectory(g:plugs[name].dir) + return + endif + + if exists('g:plug_pwindow') && !s:is_preview_window_open() + execute g:plug_pwindow + execute 'e' sha + else + execute 'pedit' sha + wincmd P + endif + setlocal previewwindow filetype=git buftype=nofile nobuflisted modifiable + let batchfile = '' + try + let [sh, shellcmdflag, shrd] = s:chsh(1) + let cmd = 'cd '.plug#shellescape(g:plugs[name].dir).' && git show --no-color --pretty=medium '.sha + if s:is_win + let [batchfile, cmd] = s:batchfile(cmd) + endif + execute 'silent %!' cmd + finally + let [&shell, &shellcmdflag, &shellredir] = [sh, shellcmdflag, shrd] + if s:is_win && filereadable(batchfile) + call delete(batchfile) + endif + endtry + setlocal nomodifiable + nnoremap q :q + wincmd p +endfunction + +function! s:section(flags) + call search('\(^[x-] \)\@<=[^:]\+:', a:flags) +endfunction + +function! s:format_git_log(line) + let indent = ' ' + let tokens = split(a:line, nr2char(1)) + if len(tokens) != 5 + return indent.substitute(a:line, '\s*$', '', '') + endif + let [graph, sha, refs, subject, date] = tokens + let tag = matchstr(refs, 'tag: [^,)]\+') + let tag = empty(tag) ? ' ' : ' ('.tag.') ' + return printf('%s%s%s%s%s (%s)', indent, graph, sha, tag, subject, date) +endfunction + +function! s:append_ul(lnum, text) + call append(a:lnum, ['', a:text, repeat('-', len(a:text))]) +endfunction + +function! s:diff() + call s:prepare() + call append(0, ['Collecting changes ...', '']) + let cnts = [0, 0] + let bar = '' + let total = filter(copy(g:plugs), 's:is_managed(v:key) && isdirectory(v:val.dir)') + call s:progress_bar(2, bar, len(total)) + for origin in [1, 0] + let plugs = reverse(sort(items(filter(copy(total), (origin ? '' : '!').'(has_key(v:val, "commit") || has_key(v:val, "tag"))')))) + if empty(plugs) + continue + endif + call s:append_ul(2, origin ? 'Pending updates:' : 'Last update:') + for [k, v] in plugs + let range = origin ? '..origin/'.v.branch : 'HEAD@{1}..' + let cmd = 'git log --graph --color=never ' + \ . (s:git_version_requirement(2, 10, 0) ? '--no-show-signature ' : '') + \ . join(map(['--pretty=format:%x01%h%x01%d%x01%s%x01%cr', range], 'plug#shellescape(v:val)')) + if has_key(v, 'rtp') + let cmd .= ' -- '.plug#shellescape(v.rtp) + endif + let diff = s:system_chomp(cmd, v.dir) + if !empty(diff) + let ref = has_key(v, 'tag') ? (' (tag: '.v.tag.')') : has_key(v, 'commit') ? (' '.v.commit) : '' + call append(5, extend(['', '- '.k.':'.ref], map(s:lines(diff), 's:format_git_log(v:val)'))) + let cnts[origin] += 1 + endif + let bar .= '=' + call s:progress_bar(2, bar, len(total)) + normal! 2G + redraw + endfor + if !cnts[origin] + call append(5, ['', 'N/A']) + endif + endfor + call setline(1, printf('%d plugin(s) updated.', cnts[0]) + \ . (cnts[1] ? printf(' %d plugin(s) have pending updates.', cnts[1]) : '')) + + if cnts[0] || cnts[1] + nnoremap (plug-preview) :silent! call preview_commit() + if empty(maparg("\", 'n')) + nmap (plug-preview) + endif + if empty(maparg('o', 'n')) + nmap o (plug-preview) + endif + endif + if cnts[0] + nnoremap X :call revert() + echo "Press 'X' on each block to revert the update" + endif + normal! gg + setlocal nomodifiable +endfunction + +function! s:revert() + if search('^Pending updates', 'bnW') + return + endif + + let name = s:find_name(line('.')) + if empty(name) || !has_key(g:plugs, name) || + \ input(printf('Revert the update of %s? (y/N) ', name)) !~? '^y' + return + endif + + call s:system('git reset --hard HEAD@{1} && git checkout '.plug#shellescape(g:plugs[name].branch).' --', g:plugs[name].dir) + setlocal modifiable + normal! "_dap + setlocal nomodifiable + echo 'Reverted' +endfunction + +function! s:snapshot(force, ...) abort + call s:prepare() + setf vim + call append(0, ['" Generated by vim-plug', + \ '" '.strftime("%c"), + \ '" :source this file in vim to restore the snapshot', + \ '" or execute: vim -S snapshot.vim', + \ '', '', 'PlugUpdate!']) + 1 + let anchor = line('$') - 3 + let names = sort(keys(filter(copy(g:plugs), + \'has_key(v:val, "uri") && !has_key(v:val, "commit") && isdirectory(v:val.dir)'))) + for name in reverse(names) + let sha = s:system_chomp('git rev-parse --short HEAD', g:plugs[name].dir) + if !empty(sha) + call append(anchor, printf("silent! let g:plugs['%s'].commit = '%s'", name, sha)) + redraw + endif + endfor + + if a:0 > 0 + let fn = s:plug_expand(a:1) + if filereadable(fn) && !(a:force || s:ask(a:1.' already exists. Overwrite?')) + return + endif + call writefile(getline(1, '$'), fn) + echo 'Saved as '.a:1 + silent execute 'e' s:esc(fn) + setf vim + endif +endfunction + +function! s:split_rtp() + return split(&rtp, '\\\@s/Y/B +|2,0,1588518816,,"'<,'>s/Y/B" +:'<,'>s/X/A +|2,0,1588518805,,"'<,'>s/X/A" +:42 +|2,0,1588516092,,"42" +:22 +|2,0,1588515833,,"22" +:10 +|2,0,1588515822,,"10" +:%s/adjacent/ownnextto +|2,0,1588515563,,"%s/adjacent/ownnextto" +:a! +|2,0,1588511803,,"a!" +:s/X/H +|2,0,1588511255,,"s/X/H" +:s/Xs/T +|2,0,1588511223,,"s/Xs/T" +:open ~/git/PPD/.git/config +|2,0,1588447851,,"open ~/git/PPD/.git/config" +:Wq! +|2,0,1588447776,,"Wq!" +:split CV-en.tex +|2,0,1588365581,,"split CV-en.tex" +:q!\ +|2,0,1587903389,,"q!\\" +:su nu! +|2,0,1587900859,,"su nu!" +:w! +|2,0,1587820381,,"w!" +:%s/\,$/\. +|2,0,1587815648,,"%s/\\,$/\\." +:%s/\,/\. +|2,0,1587815616,,"%s/\\,/\\." +:PlugInstall +|2,0,1587719997,,"PlugInstall" +:wq!\ +|2,0,1587396685,,"wq!\\" +:pw +|2,0,1587243456,,"pw" +:hi CursorLine cterm=NONE ctermbg=darkred ctermfg=white +|2,0,1587122366,,"hi CursorLine cterm=NONE ctermbg=darkred ctermfg=white" +::set cursorline +|2,0,1587121674,,":set cursorline " +:2 +|2,0,1586954655,,"2" +:%s/guess/wybor/ +|2,0,1586941937,,"%s/guess/wybor/" +:%s/doGuessing/ +|2,0,1586941927,,"%s/doGuessing/" +:%s/doGuessing/zaczynamy/ +|2,0,1586941773,,"%s/doGuessing/zaczynamy/" +:tabnew /bin/screenshot-area +|2,0,1586780831,,"tabnew /bin/screenshot-area" +:'<,'>norm A\\ +|2,0,1586776811,,"'<,'>norm A\\\\" +:norm A\\ +|2,0,1586730482,,"norm A\\\\" +:%s/15em/30em +|2,0,1586727059,,"%s/15em/30em" +:execute "!pdflatex --shell-escape -synctex=1 -interaction=nonstopmode %" +|2,0,1586725257,,"execute \"!pdflatex --shell-escape -synctex=1 -interaction=nonstopmode %\"" +:tabnew ../zaj3/Wozniak_3.hs +|2,0,1586725248,,"tabnew ../zaj3/Wozniak_3.hs" +:execute "!pdflatex --shell-escape -synctex=1 -interaction=nonstopmode" +|2,0,1586725236,,"execute \"!pdflatex --shell-escape -synctex=1 -interaction=nonstopmode\"" +:execute !pdflatex --shell-escape -synctex=1 -interaction=nonstopmode +|2,0,1586725231,,"execute !pdflatex --shell-escape -synctex=1 -interaction=nonstopmode" +:execute "!pdflatex --shell-escape -synctex=1 -interaction=nonstopmode +|2,0,1586725225,,"execute \"!pdflatex --shell-escape -synctex=1 -interaction=nonstopmode" + +# Search String History (newest to oldest): +?/:q! +|2,1,1588927077,47,":q!" +? ^\(ACCT_GROUP_ID\|DIST_AUTHOR\|DESCRIPTION\)= +|2,1,1588865221,,"^\\(ACCT_GROUP_ID\\|DIST_AUTHOR\\|DESCRIPTION\\)=" +? Z +|2,1,1588518848,,"Z" +?/Y +|2,1,1588518841,47,"Y" +? Y +|2,1,1588518816,,"Y" +? X +|2,1,1588518805,,"X" +? adjacent +|2,1,1588515563,,"adjacent" +? Xs +|2,1,1588511223,,"Xs" +?/client +|2,1,1588429581,47,"client" +?/api +|2,1,1588429532,47,"api" +?/lin +|2,1,1588364872,47,"lin" +?/page +|2,1,1588364832,47,"page" +?/hasjkdhakd +|2,1,1587902970,47,"hasjkdhakd" +? \,$ +|2,1,1587815648,,"\\,$" +? \, +|2,1,1587815616,,"\\," +?/color +|2,1,1587720251,47,"color" +?/Color +|2,1,1587720229,47,"Color" +?/search +|2,1,1587719844,47,"search" +?/read +|2,1,1587550467,47,"read" +?/sleep +|2,1,1587307974,47,"sleep" +?/temp +|2,1,1587307848,47,"temp" +?/air +|2,1,1587243550,47,"air" +?/advanced +|2,1,1587240200,47,"advanced" +?/date +|2,1,1587072847,47,"date" +?/kodi +|2,1,1586946747,47,"kodi" +?/show +|2,1,1586954073,47,"show" +?/:w +|2,1,1586943928,47,":w" +? guess +|2,1,1586941937,,"guess" +?/wea +|2,1,1586941911,47,"wea" +? doGuessing +|2,1,1586941773,,"doGuessing" +?/Wez +|2,1,1586953818,47,"Wez" +?/url +|2,1,1586953803,47,"url" +?/Zadanie 6 +|2,1,1586953787,47,"Zadanie 6" +?/zadanie 6 +|2,1,1586953782,47,"zadanie 6" +?/home +|2,1,1586875334,47,"home" +?/\.config +|2,1,1586868174,47,"\\.config" +? \ +|2,1,1586868166,,"\\" +?/native +|2,1,1586863737,47,"native" +?/update +|2,1,1586859501,47,"update" +? 15em +|2,1,1586727059,,"15em" +?/subsec +|2,1,1586725879,47,"subsec" +?/power +|2,1,1586715921,47,"power" +?/fli +|2,1,1586710089,47,"fli" +?/fight +|2,1,1586710083,47,"fight" +?/plusx +|2,1,1586692135,47,"plusx" +?/disk +|2,1,1586617019,47,"disk" +?/drive +|2,1,1586616947,47,"drive" +?// +|2,1,1586554266,47,"/" +?/shut +|2,1,1586440319,47,"shut" +?/value +|2,1,1586266634,47,"value" + +# Expression History (newest to oldest): + +# Input Line History (newest to oldest): +@y +|2,3,1589023832,,"y" + +# Debug Line History (newest to oldest): + +# Registers: +"0 CHAR 0 + { name = "#gentoo-dev-help"; chatnet = "Freenode"; autojoin = "yes"; }, + { name = "#gentoo-proxy-maint"; chatnet = "Freenode"; autojoin = "yes"; } + { name = "#gentoo-guru"; chatnet = "Freenode"; autojoin = "yes"; } + ); + +|3,0,0,0,5,0,1588866607," { name = \"#gentoo-dev-help\"; chatnet = \"Freenode\"; autojoin = \"yes\"; },"," { name = \"#gentoo-proxy-maint\"; chatnet = \"Freenode\"; autojoin = \"yes\"; }"," { name = \"#gentoo-guru\"; chatnet = \"Freenode\"; autojoin = \"yes\"; }",");","" +""1 LINE 0 + module Parsing +|3,1,1,1,1,0,1588967062,"module Parsing" +"2 LINE 0 + return (x, y) +|3,0,2,1,1,0,1588967062," return (x, y)" +"3 LINE 0 + y <- item +|3,0,3,1,1,0,1588967062," y <- item" +"4 LINE 0 + item +|3,0,4,1,1,0,1588967062," item" +"5 LINE 0 + p = do x <- item +|3,0,5,1,1,0,1588967062,"p = do x <- item" +"6 LINE 0 + p :: Parser (Char, Char) +|3,0,6,1,1,0,1588967062,"p :: Parser (Char, Char)" +"7 LINE 0 + +|3,0,7,1,1,0,1588967061,"" +"8 LINE 0 + parse p inp = p inp +|3,0,8,1,1,0,1588967061,"parse p inp = p inp" +"9 LINE 0 + parse :: Parser a -> String -> [(a, String)] +|3,0,9,1,1,0,1588967061,"parse :: Parser a -> String -> [(a, String)]" +"- CHAR 0 + w +|3,0,36,0,1,0,1588966969,"w" + +# File marks: +'0 85 0 ~/.zshrc +|4,48,85,0,1589023834,"~/.zshrc" +'1 86 1 /mnt/mega/Systems/Linux/dwm/config.h +|4,49,86,1,1589023231,"/mnt/mega/Systems/Linux/dwm/config.h" +'2 1 0 ~/luke/dwmblocks/config.h +|4,50,1,0,1589022758,"~/luke/dwmblocks/config.h" +'3 1 0 ~/luke/dwmblocks/config.h +|4,51,1,0,1589022659,"~/luke/dwmblocks/config.h" +'4 1 0 ~/luke/dwmblocks/config.h +|4,52,1,0,1589022624,"~/luke/dwmblocks/config.h" +'5 1 0 ~/luke/dwmblocks/config.h +|4,53,1,0,1589022624,"~/luke/dwmblocks/config.h" +'6 1 0 ~/luke/dwmblocks/dwmblocks +|4,54,1,0,1589022609,"~/luke/dwmblocks/dwmblocks" +'7 1 18 ~/passwd-blizard +|4,55,1,18,1588972114,"~/passwd-blizard" +'8 6 0 /mnt/mega/Documents/Collage/Semestr6/PPD/zaj8/haskell.hs +|4,56,6,0,1588967165,"/mnt/mega/Documents/Collage/Semestr6/PPD/zaj8/haskell.hs" +'9 40 0 /mnt/mega/Documents/Collage/Semestr6/PPD/zaj7/Wozniak_7.hs +|4,57,40,0,1588966506,"/mnt/mega/Documents/Collage/Semestr6/PPD/zaj7/Wozniak_7.hs" + +# Jumplist (newest first): +-' 85 0 ~/.zshrc +|4,39,85,0,1589023834,"~/.zshrc" +-' 81 0 ~/.zshrc +|4,39,81,0,1589023765,"~/.zshrc" +-' 86 1 /mnt/mega/Systems/Linux/dwm/config.h +|4,39,86,1,1589023231,"/mnt/mega/Systems/Linux/dwm/config.h" +-' 86 1 /mnt/mega/Systems/Linux/dwm/config.h +|4,39,86,1,1589023231,"/mnt/mega/Systems/Linux/dwm/config.h" +-' 10 0 /mnt/mega/Systems/Linux/dwm/config.h +|4,39,10,0,1589023122,"/mnt/mega/Systems/Linux/dwm/config.h" +-' 10 0 /mnt/mega/Systems/Linux/dwm/config.h +|4,39,10,0,1589023122,"/mnt/mega/Systems/Linux/dwm/config.h" +-' 1 0 ~/luke/dwmblocks/config.h +|4,39,1,0,1589022758,"~/luke/dwmblocks/config.h" +-' 1 0 ~/luke/dwmblocks/config.h +|4,39,1,0,1589022758,"~/luke/dwmblocks/config.h" +-' 1 0 ~/luke/dwmblocks/config.h +|4,39,1,0,1589022758,"~/luke/dwmblocks/config.h" +-' 1 0 ~/luke/dwmblocks/config.h +|4,39,1,0,1589022758,"~/luke/dwmblocks/config.h" +-' 1 0 ~/luke/dwmblocks/config.h +|4,39,1,0,1589022659,"~/luke/dwmblocks/config.h" +-' 1 0 ~/luke/dwmblocks/config.h +|4,39,1,0,1589022659,"~/luke/dwmblocks/config.h" +-' 1 0 ~/luke/dwmblocks/config.h +|4,39,1,0,1589022659,"~/luke/dwmblocks/config.h" +-' 1 0 ~/luke/dwmblocks/config.h +|4,39,1,0,1589022659,"~/luke/dwmblocks/config.h" +-' 1 0 ~/luke/dwmblocks/config.h +|4,39,1,0,1589022624,"~/luke/dwmblocks/config.h" +-' 1 0 ~/luke/dwmblocks/config.h +|4,39,1,0,1589022624,"~/luke/dwmblocks/config.h" +-' 1 0 ~/luke/dwmblocks/config.h +|4,39,1,0,1589022624,"~/luke/dwmblocks/config.h" +-' 1 0 ~/luke/dwmblocks/config.h +|4,39,1,0,1589022624,"~/luke/dwmblocks/config.h" +-' 1 0 ~/luke/dwmblocks/dwmblocks +|4,39,1,0,1589022609,"~/luke/dwmblocks/dwmblocks" +-' 1 0 ~/luke/dwmblocks/dwmblocks +|4,39,1,0,1589022609,"~/luke/dwmblocks/dwmblocks" +-' 1 0 ~/luke/dwmblocks/dwmblocks +|4,39,1,0,1589022609,"~/luke/dwmblocks/dwmblocks" +-' 1 0 ~/luke/dwmblocks/dwmblocks +|4,39,1,0,1589022609,"~/luke/dwmblocks/dwmblocks" +-' 1 0 ~/luke/dwmblocks/dwmblocks +|4,39,1,0,1589022609,"~/luke/dwmblocks/dwmblocks" +-' 1 0 ~/luke/dwmblocks/dwmblocks +|4,39,1,0,1589022609,"~/luke/dwmblocks/dwmblocks" +-' 1 0 ~/luke/dwmblocks/dwmblocks +|4,39,1,0,1589022609,"~/luke/dwmblocks/dwmblocks" +-' 1 0 ~/luke/dwmblocks/dwmblocks +|4,39,1,0,1589022609,"~/luke/dwmblocks/dwmblocks" +-' 1 0 ~/luke/dwmblocks/dwmblocks +|4,39,1,0,1589022609,"~/luke/dwmblocks/dwmblocks" +-' 1 0 ~/luke/dwmblocks/dwmblocks +|4,39,1,0,1589022609,"~/luke/dwmblocks/dwmblocks" +-' 1 0 ~/luke/dwmblocks/dwmblocks +|4,39,1,0,1589022609,"~/luke/dwmblocks/dwmblocks" +-' 1 0 ~/luke/dwmblocks/dwmblocks +|4,39,1,0,1589022609,"~/luke/dwmblocks/dwmblocks" +-' 1 0 ~/luke/dwmblocks/dwmblocks +|4,39,1,0,1589022609,"~/luke/dwmblocks/dwmblocks" +-' 1 0 ~/luke/dwmblocks/dwmblocks +|4,39,1,0,1589022609,"~/luke/dwmblocks/dwmblocks" +-' 1 0 ~/luke/dwmblocks/dwmblocks +|4,39,1,0,1589022609,"~/luke/dwmblocks/dwmblocks" +-' 1 0 ~/luke/dwmblocks/dwmblocks +|4,39,1,0,1589022609,"~/luke/dwmblocks/dwmblocks" +-' 1 0 ~/luke/dwmblocks/dwmblocks +|4,39,1,0,1589022609,"~/luke/dwmblocks/dwmblocks" +-' 1 0 ~/luke/dwmblocks/dwmblocks +|4,39,1,0,1589022609,"~/luke/dwmblocks/dwmblocks" +-' 1 0 ~/luke/dwmblocks/dwmblocks +|4,39,1,0,1589022609,"~/luke/dwmblocks/dwmblocks" +-' 1 0 ~/luke/dwmblocks/dwmblocks +|4,39,1,0,1589022609,"~/luke/dwmblocks/dwmblocks" +-' 1 0 ~/luke/dwmblocks/dwmblocks +|4,39,1,0,1589022609,"~/luke/dwmblocks/dwmblocks" +-' 1 0 ~/luke/dwmblocks/dwmblocks +|4,39,1,0,1589022609,"~/luke/dwmblocks/dwmblocks" +-' 1 0 ~/luke/dwmblocks/dwmblocks +|4,39,1,0,1589022609,"~/luke/dwmblocks/dwmblocks" +-' 1 0 ~/luke/dwmblocks/dwmblocks +|4,39,1,0,1589022609,"~/luke/dwmblocks/dwmblocks" +-' 1 0 ~/luke/dwmblocks/dwmblocks +|4,39,1,0,1589022609,"~/luke/dwmblocks/dwmblocks" +-' 1 0 ~/luke/dwmblocks/dwmblocks +|4,39,1,0,1589022609,"~/luke/dwmblocks/dwmblocks" +-' 1 0 ~/luke/dwmblocks/dwmblocks +|4,39,1,0,1589022609,"~/luke/dwmblocks/dwmblocks" +-' 1 0 ~/luke/dwmblocks/dwmblocks +|4,39,1,0,1589022609,"~/luke/dwmblocks/dwmblocks" +-' 1 0 ~/luke/dwmblocks/dwmblocks +|4,39,1,0,1589022609,"~/luke/dwmblocks/dwmblocks" +-' 1 0 ~/luke/dwmblocks/dwmblocks +|4,39,1,0,1589022609,"~/luke/dwmblocks/dwmblocks" +-' 1 0 ~/luke/dwmblocks/dwmblocks +|4,39,1,0,1589022609,"~/luke/dwmblocks/dwmblocks" +-' 1 0 ~/luke/dwmblocks/dwmblocks +|4,39,1,0,1589022609,"~/luke/dwmblocks/dwmblocks" +-' 1 18 ~/passwd-blizard +|4,39,1,18,1588972114,"~/passwd-blizard" +-' 1 18 ~/passwd-blizard +|4,39,1,18,1588972114,"~/passwd-blizard" +-' 1 18 ~/passwd-blizard +|4,39,1,18,1588972114,"~/passwd-blizard" +-' 1 18 ~/passwd-blizard +|4,39,1,18,1588972114,"~/passwd-blizard" +-' 1 18 ~/passwd-blizard +|4,39,1,18,1588972114,"~/passwd-blizard" +-' 1 18 ~/passwd-blizard +|4,39,1,18,1588972114,"~/passwd-blizard" +-' 1 18 ~/passwd-blizard +|4,39,1,18,1588972114,"~/passwd-blizard" +-' 1 18 ~/passwd-blizard +|4,39,1,18,1588972114,"~/passwd-blizard" +-' 1 18 ~/passwd-blizard +|4,39,1,18,1588972114,"~/passwd-blizard" +-' 1 18 ~/passwd-blizard +|4,39,1,18,1588972114,"~/passwd-blizard" +-' 1 18 ~/passwd-blizard +|4,39,1,18,1588972114,"~/passwd-blizard" +-' 1 18 ~/passwd-blizard +|4,39,1,18,1588972114,"~/passwd-blizard" +-' 1 18 ~/passwd-blizard +|4,39,1,18,1588972114,"~/passwd-blizard" +-' 1 18 ~/passwd-blizard +|4,39,1,18,1588972114,"~/passwd-blizard" +-' 1 18 ~/passwd-blizard +|4,39,1,18,1588972114,"~/passwd-blizard" +-' 1 18 ~/passwd-blizard +|4,39,1,18,1588972114,"~/passwd-blizard" +-' 1 18 ~/passwd-blizard +|4,39,1,18,1588972114,"~/passwd-blizard" +-' 1 18 ~/passwd-blizard +|4,39,1,18,1588972114,"~/passwd-blizard" +-' 1 18 ~/passwd-blizard +|4,39,1,18,1588972114,"~/passwd-blizard" +-' 1 18 ~/passwd-blizard +|4,39,1,18,1588972114,"~/passwd-blizard" +-' 1 18 ~/passwd-blizard +|4,39,1,18,1588972114,"~/passwd-blizard" +-' 1 18 ~/passwd-blizard +|4,39,1,18,1588972114,"~/passwd-blizard" +-' 1 18 ~/passwd-blizard +|4,39,1,18,1588972114,"~/passwd-blizard" +-' 1 18 ~/passwd-blizard +|4,39,1,18,1588972114,"~/passwd-blizard" +-' 1 18 ~/passwd-blizard +|4,39,1,18,1588972114,"~/passwd-blizard" +-' 1 18 ~/passwd-blizard +|4,39,1,18,1588972114,"~/passwd-blizard" +-' 1 18 ~/passwd-blizard +|4,39,1,18,1588972114,"~/passwd-blizard" +-' 1 18 ~/passwd-blizard +|4,39,1,18,1588972114,"~/passwd-blizard" +-' 1 18 ~/passwd-blizard +|4,39,1,18,1588972114,"~/passwd-blizard" +-' 1 18 ~/passwd-blizard +|4,39,1,18,1588972114,"~/passwd-blizard" +-' 1 18 ~/passwd-blizard +|4,39,1,18,1588972114,"~/passwd-blizard" +-' 1 18 ~/passwd-blizard +|4,39,1,18,1588972114,"~/passwd-blizard" +-' 1 18 ~/passwd-blizard +|4,39,1,18,1588972114,"~/passwd-blizard" +-' 1 18 ~/passwd-blizard +|4,39,1,18,1588972114,"~/passwd-blizard" +-' 1 18 ~/passwd-blizard +|4,39,1,18,1588972114,"~/passwd-blizard" +-' 1 18 ~/passwd-blizard +|4,39,1,18,1588972114,"~/passwd-blizard" +-' 1 18 ~/passwd-blizard +|4,39,1,18,1588972114,"~/passwd-blizard" +-' 1 18 ~/passwd-blizard +|4,39,1,18,1588972114,"~/passwd-blizard" +-' 1 18 ~/passwd-blizard +|4,39,1,18,1588972114,"~/passwd-blizard" +-' 1 18 ~/passwd-blizard +|4,39,1,18,1588972114,"~/passwd-blizard" +-' 1 18 ~/passwd-blizard +|4,39,1,18,1588972114,"~/passwd-blizard" +-' 1 18 ~/passwd-blizard +|4,39,1,18,1588972114,"~/passwd-blizard" +-' 1 18 ~/passwd-blizard +|4,39,1,18,1588972114,"~/passwd-blizard" +-' 1 18 ~/passwd-blizard +|4,39,1,18,1588972114,"~/passwd-blizard" +-' 1 18 ~/passwd-blizard +|4,39,1,18,1588972114,"~/passwd-blizard" +-' 1 18 ~/passwd-blizard +|4,39,1,18,1588972114,"~/passwd-blizard" +-' 1 18 ~/passwd-blizard +|4,39,1,18,1588972114,"~/passwd-blizard" +-' 1 18 ~/passwd-blizard +|4,39,1,18,1588972114,"~/passwd-blizard" +-' 1 18 ~/passwd-blizard +|4,39,1,18,1588972114,"~/passwd-blizard" +-' 1 18 ~/passwd-blizard +|4,39,1,18,1588972114,"~/passwd-blizard" + +# History of marks within files (newest to oldest): + +> ~/.zshrc + * 1589023834 0 + " 85 0 + ^ 81 19 + . 81 18 + + 84 144 + + 84 56 + + 12 0 + + 12 8 + + 12 0 + + 14 0 + + 14 86 + + 84 37 + + 86 0 + + 85 12 + + 86 0 + + 77 48 + + 78 55 + + 79 8 + + 78 9 + + 79 9 + + 78 9 + + 80 9 + + 79 46 + + 80 55 + + 80 0 + + 14 0 + + 68 0 + + 69 0 + + 68 0 + + 69 84 + + 81 18 + +> /mnt/mega/Systems/Linux/dwm/config.h + * 1589023230 0 + " 86 1 + ^ 10 60 + . 10 60 + + 10 60 + +> ~/luke/dwmblocks/config.h + * 1589022756 0 + " 1 0 + +> ~/luke/dwmblocks/dwmblocks + * 1589022608 0 + " 1 0 + +> ~/passwd-blizard + * 1588972113 0 + " 1 18 + ^ 1 19 + . 1 18 + + 1 18 + +> /mnt/mega/Documents/Collage/Semestr6/PPD/zaj8/haskell.hs + * 1588967157 0 + " 6 0 + ^ 91 46 + . 91 45 + + 1 22 + + 1 12 + + 1 0 + + 1 13 + + 1 17 + + 1 13 + + 1 27 + + 1 37 + + 1 39 + + 1 0 + + 1 44 + + 1 18 + + 1 24 + + 1 0 + + 1 7 + + 1 0 + + 1 4 + + 1 0 + + 1 7 + + 1 0 + + 1 18 + + 1 23 + + 1 0 + + 1 6 + + 1 5 + + 1 4 + + 1 20 + + 1 0 + + 1 14 + + 1 19 + + 91 45 + +> /mnt/mega/Documents/Collage/Semestr6/PPD/zaj7/Wozniak_7.hs + * 1588966504 0 + " 40 0 + . 47 0 + + 62 18 + + 62 36 + + 62 31 + + 64 15 + + 65 0 + + 64 15 + + 65 0 + + 62 57 + + 62 56 + + 64 14 + + 67 15 + + 62 31 + + 62 18 + + 62 2 + + 62 0 + + 59 2 + + 59 0 + + 62 18 + + 61 0 + + 65 15 + + 65 0 + + 68 25 + + 62 36 + + 62 18 + + 61 2 + + 61 11 + + 53 16 + + 53 18 + + 53 17 + + 53 118 + + 53 12 + + 62 20 + + 72 3 + + 62 20 + + 71 2 + + 62 46 + + 71 50 + + 62 51 + + 71 8 + + 71 0 + + 62 18 + + 63 0 + + 66 15 + + 54 0 + + 55 130 + + 56 39 + + 66 29 + + 56 31 + + 53 8 + + 54 0 + + 55 21 + + 66 37 + + 69 36 + + 66 36 + + 55 12 + + 56 31 + + 67 0 + + 70 0 + + 60 3 + + 51 28 + + 71 0 + + 60 0 + + 46 48 + + 42 27 + + 45 39 + + 45 51 + + 45 0 + + 39 1 + + 40 0 + + 46 50 + + 46 61 + + 46 10 + + 46 39 + + 39 0 + + 43 43 + + 41 31 + + 43 35 + + 44 41 + + 45 45 + + 44 38 + + 45 23 + + 44 46 + + 45 50 + + 44 24 + + 28 12 + + 46 52 + + 44 18 + + 45 0 + + 44 32 + + 45 36 + + 44 36 + + 45 40 + + 46 0 + + 45 37 + + 44 33 + + 46 108 + + 46 35 + + 46 0 + + 47 0 + +> /mnt/mega/Documents/Collage/Semestr6/EGOS/zaj6.txt + * 1588941246 0 + " 11 49 + ^ 8 58 + . 11 0 + + 10 13 + + 8 101 + + 6 14 + + 11 48 + + 7 4 + + 1 18 + + 2 9 + + 3 0 + + 11 57 + + 11 0 + +> /tmp/crontab.WBucql + * 1588927565 0 + " 2 21 + ^ 2 22 + . 2 21 + + 2 21 + +> /mnt/mega/Systems/Linux/bin/git-init-folder + * 1588927077 0 + " 1 0 + +> /mnt/mega/www/public/vimrc + * 1588922955 0 + " 58 0 + . 26 0 + + 8 0 + + 70 0 + + 68 0 + + 65 0 + + 64 0 + + 27 0 + + 26 0 + +> /mnt/mega/Systems/Linux/komendy + * 1588881152 0 + " 1 41 + ^ 1 42 + . 1 41 + + 1 41 + +> /mnt/backup/kodi/userdata/addon_data/pvr.iptvsimple/settings.xml + * 1588872876 0 + " 15 4 + +> /mnt/backup/kodi/tv2.m3u + * 1588872842 0 + " 1 0 + +> /mnt/backup/kodi/tv-beata.m3u + * 1588872773 0 + " 1 0 + +> /mnt/backup/kodi/tv1.php?login=yorune&password=e2c157b497421608ff50b5ede000e920 + * 1588872762 0 + " 1 0 + +> /mnt/mega/www/public/public-key.pub + * 1588867054 0 + " 1 0 + +> ~/.ssh/id_rsa.pub + * 1588867054 0 + " 1 0 + +> ~/.irssi/config.autosave + * 1588866637 0 + " 97 63 + ^ 163 24 + . 163 23 + + 161 30 + + 161 52 + + 161 70 + + 162 3 + + 162 33 + + 162 55 + + 162 75 + + 163 23 + +> ~/.irssi/config + * 1588866635 0 + " 97 91 + ^ 161 0 + . 165 0 + + 165 0 + + 161 0 + + 165 0 + +> ~/.irssi/diff + * 1588866568 0 + " 1 0 + +> /mnt/backup/repos/guru/.git/COMMIT_EDITMSG + * 1588866096 0 + " 2 0 + ^ 2 0 + . 3 0 + + 1 26 + + 2 46 + + 3 0 + + 2 0 + + 3 0 + +> /mnt/backup/repos/gentoo/.git/COMMIT_EDITMSG + * 1588865971 0 + " 2 0 + ^ 2 0 + . 2 0 + + 1 32 + + 2 0 + +> /tmp/tmp2nl77_fh.repoman.msg/COMMIT_EDITMSG + * 1588865804 0 + " 1 40 + ^ 1 41 + . 1 40 + + 1 40 + +> /tmp/tmpx39qjrpi.repoman.msg/COMMIT_EDITMSG + * 1588865717 0 + " 1 25 + ^ 1 26 + . 1 26 + + 1 26 + +> /mnt/backup/repos/gentoo/net-im/discord-canary/discord-canary-0.0.103.ebuild + * 1588865691 0 + " 17 28 + ^ 17 29 + . 17 28 + + 58 0 + + 1 20 + + 17 28 + +> /mnt/backup/repos/gentoo/net-im/discord-bin/discord-bin-0.0.9.ebuild + * 1588865685 0 + " 1 28 + ^ 1 29 + . 1 28 + + 1 28 + +> /mnt/backup/repos/gentoo/net-im/discord-canary/metadata.xml + * 1588865654 0 + " 6 2 + ^ 6 23 + . 6 22 + + 5 22 + + 6 17 + + 8 0 + + 5 22 + + 6 22 + +> /mnt/backup/repos/guru/net-im/discord-canary/discord-canary-0.0.103.ebuild + * 1588865251 0 + " 1 20 + ^ 1 21 + . 1 20 + + 1 20 + +> net-im/discord-canary/discord-canary-0.0.103.ebuild + * 1588865221 0 + " 6 13 + . 17 0 + + 17 0 + +> /etc/portage/package.mask + * 1588855948 0 + " 2 0 + . 3 0 + + 3 0 + +> /etc/portage/package.accept_keywords + * 1588855933 0 + " 1 0 + ^ 2 1 + . 2 0 + + 2 0 + +> /etc/portage/package.use + * 1588848565 0 + " 3 0 + +> /mnt/mega/Documents/Collage/Semestr6/KDA/KDA/1.py + * 1588693580 0 + " 36 0 + +> ~/cosiqwoiqw + * 1588527403 0 + " 1 0 + +> /etc/bitcoin/bitcoin.conf + * 1588522163 0 + " 1 0 + +> /mnt/mega/Documents/Collage/Semestr6/PPD/.git/COMMIT_EDITMSG + * 1588518879 0 + " 1 4 + ^ 1 5 + . 1 4 + + 1 4 + +> /mnt/mega/Documents/Collage/Semestr6/PPD/zaj10-prolog/Wozniak_10.pl + * 1588518863 0 + " 43 0 + . 43 0 + + 10 11 + + 12 52 + + 10 26 + + 11 0 + + 12 0 + + 11 16 + + 12 0 + + 11 18 + + 11 40 + + 12 17 + + 23 18 + + 23 61 + + 23 0 + + 21 0 + + 23 0 + + 22 0 + + 21 15 + + 23 11 + + 21 12 + + 12 14 + + 13 38 + + 23 0 + + 26 0 + + 28 0 + + 26 13 + + 29 15 + + 30 0 + + 27 0 + + 26 10 + + 31 13 + + 33 18 + + 34 33 + + 33 15 + + 32 16 + + 35 0 + + 34 46 + + 40 10 + + 37 0 + + 37 54 + + 37 8 + + 37 0 + + 37 31 + + 37 0 + + 39 0 + + 37 52 + + 37 0 + + 37 25 + + 39 10 + + 37 13 + + 38 13 + + 37 19 + + 38 36 + + 17 0 + + 18 0 + + 19 0 + + 1 17 + + 4 2 + + 3 0 + + 2 0 + + 3 0 + + 1 1 + + 2 0 + + 3 0 + + 4 2 + + 22 0 + + 40 45 + + 40 13 + + 40 26 + + 40 28 + + 40 23 + + 40 21 + + 40 18 + + 40 22 + + 40 40 + + 40 33 + + 40 69 + + 40 13 + + 40 69 + + 40 13 + + 43 0 + + 42 69 + + 42 60 + + 43 47 + + 40 0 + + 42 37 + + 40 13 + + 42 0 + + 42 37 + + 43 0 + + 41 2 + + 43 11 + + 42 11 + + 43 11 + + 41 13 + + 43 0 + + 41 0 + + 43 0 + + 42 0 + + 43 0 + +> /mnt/backup/repos/gentoo-yorune/.git/COMMIT_EDITMSG + * 1588508878 0 + " 5 22 + ^ 5 24 + . 5 22 + + 1 7 + + 2 0 + + 1 4 + + 5 22 + +> /usr/repos/chaoslab/.git/config + * 1588508642 0 + " 7 1 + ^ 7 48 + . 7 47 + + 7 47 + +> /mnt/backup/repos/gentoo/net-im/discord-bin/metadata.xml + * 1588508282 0 + " 5 0 + +> ~/cos.txt + * 1588453613 0 + " 1 0 + ^ 1 59 + . 1 58 + + 1 58 + +> ~/cos2.txt + * 1588453604 0 + " 1 0 + ^ 1 59 + . 1 58 + + 1 58 + +> ~/distccflags + * 1588453590 0 + " 1 0 + +> /mnt/backup/repos/gentoo/net-im/discord-canary/Manifest + * 1588452701 0 + " 1 0 + +> /mnt/backup/repos/gentoo-yorune/net-im/discord-canary/Manifest + * 1588452599 0 + " 1 0 + +> /mnt/backup/repos/gentoo/.git/config + * 1588449273 0 + " 7 21 + ^ 7 22 + . 7 21 + + 7 21 + +> /mnt/backup/repos/gentoo-yorune/net-im/discord-canary/discord-canary-0.0.103.ebuild + * 1588448413 0 + " 55 21 + ^ 55 22 + . 55 21 + + 53 47 + + 56 0 + + 55 21 + +> /mnt/backup/repos/gentoo-yorune/dev-python/pycparser/metadata.xml + * 1588448087 0 + " 1 0 + +> /mnt/backup/repos/gentoo-yorune/.git/config + * 1588447923 0 + " 7 45 + ^ 7 46 + . 7 45 + + 7 45 + +> /mnt/mega/Documents/Collage/Semestr6/PPD/.git/config + * 1588447875 0 + " 1 0 + ^ 1 22 + . 1 21 + + 1 21 + +> /mnt/backup/repos/gentoo-yorune/net-im/discord/discord-canary-0.0.98.ebuild + * 1588447656 0 + " 1 0 + +> /mnt/backup/repos/gentoo-yorune/net-im/discord/discord-0.0.103.ebuild + * 1588447630 0 + " 1 20 + ^ 1 21 + . 1 20 + + 1 20 + +> /mnt/backup/repos/gentoo-yorune/net-im/discord-canary/discord-0.0.98.ebuild + * 1588447463 0 + " 5 0 + ^ 5 0 + . 57 1 + + 1 0 + + 1 36 + + 57 1 + +> ~/cos.py + * 1588422778 0 + " 31 5 + ^ 31 6 + . 31 5 + + 1 42 + + 1 41 + + 35 41 + + 31 5 + + 1 0 + + 3 0 + + 5 0 + + 9 0 + + 15 0 + + 17 0 + + 19 0 + + 20 0 + + 21 0 + + 22 0 + + 23 0 + + 24 0 + + 25 0 + + 28 0 + + 29 0 + + 31 0 + + 35 0 + + 33 0 + + 31 5 + +> /mnt/mega/Documents/LateX/CV-en.tex + * 1588365683 0 + " 1 0 + +> /mnt/mega/Documents/LateX/inz.tex + * 1588365657 0 + " 5 0 + ^ 5 0 + . 4 38 + + 1 38 + + 1 0 + + 1 15 + + 1 14 + + 1 12 + + 1 7 + + 1 0 + + 1 18 + + 1 0 + + 1 16 + + 1 0 + + 1 7 + + 1 27 + + 1 0 + + 1 21 + + 1 0 + + 1 65 + + 41 64 + + 1 65 + + 2 17 + + 2 19 + + 3 21 + + 4 38 + +> /mnt/mega/Documents/LateX/inz.tx + * 1588364731 0 + " 1 0 + +> /mnt/mega/Systems/Linux/bin/cleaner + * 1588331618 0 + " 7 0 + +> /etc/conf.d/distccd + * 1588331213 0 + " 42 13 + ^ 32 73 + . 32 72 + + 3 82 + + 32 72 + +> ~/.distcc/hosts + * 1588326544 0 + " 1 0 + . 1 0 + + 1 0 + +> ~/main.c + * 1588326510 0 + " 6 0 + ^ 6 1 + . 6 0 + + 6 0 + +> ~/make.c + * 1588324916 0 + " 6 0 + ^ 6 1 + . 6 0 + + 6 0 + +> /etc/portage/package.unmask + * 1588323436 0 + " 1 0 + +> ~/.dwm/autostart.sh + * 1588247174 0 + " 21 0 + ^ 21 1 + . 22 0 + + 10 0 + + 11 0 + + 10 0 + + 11 0 + + 10 0 + + 7 0 + + 6 0 + + 10 0 + + 10 49 + + 10 0 + + 7 0 + + 6 0 + + 10 0 + + 6 0 + + 7 0 + + 10 0 + + 18 0 + + 123 21 + + 159 0 + + 11 0 + + 11 53 + + 13 14 + + 11 11 + + 38 37 + + 39 49 + + 39 185 + + 38 164 + + 10 0 + + 10 95 + + 69 36 + + 155 7 + + 6 0 + + 7 0 + + 155 0 + + 115 1 + + 154 48 + + 6 0 + + 7 0 + + 8 0 + + 69 34 + + 7 0 + + 6 0 + + 7 0 + + 6 0 + + 57 0 + + 60 209 + + 55 0 + + 57 0 + + 59 0 + + 58 0 + + 59 0 + + 60 150 + + 60 152 + + 61 0 + + 60 273 + + 60 15 + + 60 156 + + 60 278 + + 60 139 + + 60 265 + + 60 8 + + 60 141 + + 53 0 + + 52 12 + + 11 0 + + 8 0 + + 39 0 + + 40 45 + + 38 0 + + 40 0 + + 101 0 + + 51 36 + + 47 84 + + 47 141 + + 47 84 + + 47 91 + + 47 59 + + 51 0 + + 38 64 + + 40 0 + + 43 0 + + 41 0 + + 42 0 + + 41 0 + + 42 138 + + 42 0 + + 41 0 + + 6 12 + + 6 0 + + 8 4 + + 6 0 + + 21 0 + + 22 6 + + 8 0 + + 11 36 + + 22 17 + + 21 25 + + 22 11 + + 21 0 + + 22 0 + +> ~/haskell.txt + * 1588236732 0 + " 17 0 + ^ 43 0 + . 57 2 + + 1 1 + + 2 0 + + 1 36 + + 6 0 + + 10 0 + + 11 35 + + 16 66 + + 25 21 + + 29 9 + + 28 4 + + 29 9 + + 28 6 + + 29 30 + + 40 8 + + 33 0 + + 41 0 + + 43 25 + + 42 0 + + 53 27 + + 57 2 + +> ~/.haskell.txt.swp + * 1588224953 0 + " 1 0 + +> /mnt/mega/Documents/Collage/Semestr6/PPD/zaj3/Wozniak_3.hs + * 1588174087 0 + " 81 0 + +> /mnt/mega/Documents/Collage/Semestr6/STAT/PDF/STT.tex + * 1588159643 0 + " 574 74 + ^ 574 75 + . 574 74 + + 186 0 + + 209 0 + + 188 9 + + 189 0 + + 188 31 + + 191 9 + + 196 2 + + 198 0 + + 196 5 + + 191 7 + + 194 0 + + 191 15 + + 191 11 + + 188 31 + + 188 1 + + 188 0 + + 199 1 + + 201 9 + + 208 0 + + 201 9 + + 206 16 + + 207 0 + + 201 32 + + 204 25 + + 206 14 + + 208 0 + + 201 8 + + 199 2 + + 186 2 + + 188 33 + + 181 33 + + 201 33 + + 224 5 + + 216 20 + + 224 4 + + 216 8 + + 217 17 + + 218 17 + + 219 32 + + 221 4 + + 222 2 + + 223 0 + + 224 3 + + 229 63 + + 235 0 + + 232 39 + + 235 1 + + 232 33 + + 234 0 + + 235 0 + + 239 99 + + 240 93 + + 12 19 + + 240 113 + + 243 35 + + 253 2 + + 244 23 + + 246 0 + + 246 4 + + 248 0 + + 246 4 + + 248 7 + + 247 3 + + 248 0 + + 255 0 + + 253 3 + + 255 12 + + 253 4 + + 264 14 + + 258 22 + + 259 281 + + 258 0 + + 259 95 + + 259 200 + + 259 283 + + 1 32 + + 421 14 + + 25 0 + + 212 0 + + 216 29 + + 215 25 + + 422 0 + + 423 0 + + 290 93 + + 291 38 + + 292 0 + + 291 0 + + 17 17 + + 1 16 + + 25 7 + + 19 0 + + 21 3 + + 21 0 + + 16 24 + + 16 0 + + 14 0 + + 21 0 + + 551 0 + + 576 0 + + 574 74 + +> ~/.ssh/config + * 1588145883 0 + " 1 0 + +> ~/.sshservers + * 1588141245 0 + " 4 1 + ^ 4 41 + . 5 47 + + 5 47 + +> /mnt/mega/Documents/Collage/Semestr6/PPD/zaj9-prolog/Wozniak_9_POPRAWIONE.pl + * 1588108151 0 + " 319 0 + +> /mnt/mega/Documents/Collage/Semestr6/PPD/zaj9-prolog/Wozniak_9.pl + * 1588108150 0 + " 319 0 + ^ 340 0 + . 82 0 + + 1 12 + + 81 0 + + 57 9 + + 56 2 + + 58 0 + + 81 2 + + 82 0 + +> /usr/share/vim/vim82/doc/help.txt + * 1588107780 0 + " 1 0 + +> /mnt/mega/Documents/Collage/Semestr6/PPD/zaj9-prolog/Prolog+cw+9+PPD.pdf + * 1588107763 0 + " 22 0 + +> /mnt/mega/Systems/Linux/bin/rasp + * 1587927369 0 + " 3 23 + ^ 3 24 + . 3 23 + + 3 23 + +> /bin/rasp + * 1587927337 0 + " 3 0 + +> /mnt/mega/Documents/Collage/Semestr6/PPD/zaj9-prolog/klocki_1.pl + * 1587903389 0 + " 56 0 + ^ 42 0 + . 54 4 + + 1 11 + + 5 10 + + 6 0 + + 5 2 + + 4 2 + + 1 14 + + 2 8 + + 7 3 + + 56 0 + + 19 0 + + 54 4 + +> /mnt/mega/Documents/Collage/Semestr6/PPD/zaj9-prolog/klocki_2.pl + * 1587903378 0 + " 1 0 + +> /mnt/mega/Documents/Collage/Semestr6/PPD/zaj9-prolog/dane.pl + * 1587903329 0 + " 14 0 + . 14 0 + + 223 7 + + 222 7 + + 221 7 + + 222 11 + + 221 11 + + 223 14 + + 228 19 + + 243 43 + + 234 21 + + 234 72 + + 243 44 + + 234 20 + + 243 0 + + 237 13 + + 237 55 + + 243 44 + + 237 52 + + 237 70 + + 241 9 + + 237 55 + + 238 0 + + 236 3 + + 238 0 + + 236 2 + + 239 2 + + 241 10 + + 239 3 + + 240 0 + + 243 0 + + 244 3 + + 245 24 + + 20 0 + + 245 40 + + 252 7 + + 246 0 + + 245 42 + + 246 15 + + 249 8 + + 246 1 + + 250 2 + + 246 0 + + 254 0 + + 253 78 + + 254 0 + + 256 0 + + 260 0 + + 259 8 + + 262 7 + + 288 0 + + 263 17 + + 223 11 + + 263 43 + + 265 0 + + 271 1 + + 270 11 + + 266 15 + + 270 9 + + 271 0 + + 273 7 + + 275 0 + + 274 0 + + 274 58 + + 285 0 + + 277 17 + + 283 0 + + 286 66 + + 286 55 + + 288 2 + + 289 17 + + 290 8 + + 291 0 + + 301 2 + + 295 2 + + 300 15 + + 301 0 + + 300 8 + + 302 2 + + 302 0 + + 302 6 + + 302 0 + + 14 0 + +> /mnt/mega/Documents/Collage/Semestr6/PPD/zaj9-prolog/baza.pl + * 1587820287 0 + " 2 0 + ^ 3 0 + . 2 0 + + 58 0 + + 1 12 + + 4 0 + + 2 0 + +> /mnt/mega/Systems/Linux/configs/newsboat/config + * 1587757216 0 + " 16 19 + ^ 16 20 + . 16 19 + + 16 19 + +> /mnt/backup/repos/gentoo-yorune/media-plugins/kodi-addon-signals/kodi-addon-signals-0.0.3.ebuild + * 1587756117 0 + " 27 0 + +> ~/.vimrc + * 1587754044 0 + " 34 0 + ^ 14 22 + . 14 21 + + 5 13 + + 6 0 + + 6 55 + + 6 0 + + 11 0 + + 13 0 + + 11 0 + + 10 0 + + 11 0 + + 10 0 + + 13 0 + + 33 14 + + 34 14 + + 13 22 + + 11 0 + + 69 0 + + 16 0 + + 27 22 + + 28 0 + + 14 21 + +> /mnt/mega/Systems/Linux/configs/.git/COMMIT_EDITMSG + * 1587720892 0 + " 1 4 + ^ 1 5 + . 1 4 + + 1 4 + +> /mnt/mega/Systems/Linux/configs/add + * 1587720815 0 + " 1 0 + +> /mnt/mega/Systems/Linux/configs/vimrc + * 1587720797 0 + " 14 0 + . 14 0 + + 71 0 + + 14 0 + +> ~/.tmux.conf + * 1587720746 0 + " 34 0 + . 34 0 + + 1 0 + + 1 96 + + 1 19 + + 1 0 + + 37 58 + + 37 0 + + 22 0 + + 37 0 + + 20 26 + + 24 0 + + 22 0 + + 26 0 + + 27 0 + + 26 0 + + 25 0 + + 28 0 + + 37 0 + + 30 0 + + 37 0 + + 28 0 + + 37 0 + + 28 0 + + 30 0 + + 28 0 + + 30 0 + + 34 0 + +> ~/.config/nvim/init.vim + * 1587720026 0 + " 81 0 + ^ 9 39 + . 9 38 + + 9 38 + +> ~/.vimr + * 1587719769 0 + " 1 0 + +> /mnt/mega/Systems/Linux/portage/.git/COMMIT_EDITMSG + * 1587579841 0 + " 1 12 + ^ 1 13 + . 1 12 + + 1 12 + +> /mnt/mega/Systems/Linux/bin/.git/COMMIT_EDITMSG + * 1587396695 0 + " 1 0 + ^ 1 6 + . 1 0 + + 1 0 + +> /mnt/mega/Documents/Collage/Semestr6/STAT/.git/COMMIT_EDITMSG + * 1587325810 0 + " 1 0 + ^ 1 5 + . 1 4 + + 1 5 + + 1 22 + + 2 0 + + 1 4 + +> /mnt/mega/Systems/Linux/additional-to-dwm.sh + * 1587307602 0 + " 1 0 + . 26 0 + + 1 0 + + 2 0 + + 18 0 + + 26 0 + +> /mnt/mega/Systems/Linux/dwm/dwm_status + * 1587307600 0 + " 42 211 + ^ 42 212 + . 42 170 + + 20 0 + + 59 0 + + 98 0 + + 97 0 + + 53 0 + + 54 12 + + 57 0 + + 101 11 + + 100 46 + + 57 0 + + 56 10 + + 41 96 + + 41 235 + + 42 170 + +> /mnt/mega/Systems/Linux/NERD_tree_1 + * 1587305580 0 + " 22 0 + . 1 0 + + 1 0 + +> /mnt/mega/Documents/Collage/Semestr6/PPD/zaj6/Wozniak_6.hs + * 1587243242 0 + " 20 0 + ^ 74 0 + . 72 63 + + 1 17 + + 14 7 + + 6 11 + + 14 5 + + 7 0 + + 4 0 + + 1 0 + + 16 2 + + 15 0 + + 16 8 + + 6 8 + + 17 0 + + 44 8 + + 29 0 + + 74 8 + + 46 0 + + 17 12 + + 26 28 + + 27 0 + + 43 47 + + 44 0 + + 72 63 + +> /mnt/backup/kodi/userdata/advancedsettings.xml + * 1587240223 0 + " 3 18 + ^ 3 19 + . 3 18 + + 3 18 + +> /mnt/backup/kodi/userdata/guisettings.xml + * 1587240200 0 + " 496 4 + +> /bin/google-chrome-scale + * 1587216844 0 + " 1 0 + ^ 1 52 + . 1 51 + + 1 51 diff --git a/.vimrc b/.vimrc new file mode 100644 index 0000000..aea7135 --- /dev/null +++ b/.vimrc @@ -0,0 +1,115 @@ +" settings +set laststatus=2 +set shiftwidth=4 +set softtabstop=4 +set tabstop=4 +au BufWritePre * let &bex = '@' . strftime("%F.%H:%M") + +" plugins +call plug#begin('~/.vim/plugged') +Plug 'scrooloose/nerdtree', "{ 'on': 'NERDTreeToggle' } +Plug 'nmante/vim-latex-live-preview' +Plug 'lervag/vimtex' +Plug 'junegunn/goyo.vim' +call plug#end() + +" Status-line +set statusline= +set statusline+=%#IncSearch# +set statusline+=\ %y +set statusline+=\ %r +set statusline+=%#CursorLineNr# +set statusline+=\ %F +set statusline+=%= "Right side settings +set statusline+=%#Search# +set statusline+=\ %l/%L +set statusline+=\ [%c] + +set nocompatible +set hlsearch +set incsearch +set noshowmode +set cursorline +set cmdheight=1 +let g:livepreview_previewer = 'mupdf' +syntax on +filetype plugin indent on + +set encoding=utf-8 + +" line numbers +set number +set ruler +set title + +" indent +set backspace=indent,eol,start +set shiftwidth=4 +set expandtab + +" editing +runtime! macros/matchit.vim +set backspace=indent,eol,start + +" visual feedback +set laststatus=2 +set showmode +set showcmd + +" disable pcspkr beep +set visualbell +set t_vb= + +" searching +set incsearch +set smartcase + +" colors +colorscheme desert +hi CursorLine cterm=NONE term=NONE ctermbg=NONE guibg=NONE +hi CursorLine ctermbg=235 + +" map +nnoremap ee :!mupdf $(echo % \| sed 's/tex$/pdf/') & disown +map :NERDTreeToggle +nnoremap :tabnew +nnoremap :Goyo +nnoremap :tabprevious +nnoremap ww :w! +nnoremap :tabnext +nnoremap :GoRun + +command W :execute ':silent w !sudo tee % > /dev/null' | :edit! + +" latex +autocmd BufWritePost *.tex silent! execute "!pdflatex --shell-escape -synctex=1 -interaction=nonstopmode % > /dev/null " | redraw! +autocmd BufWritePost *.tex silent! execute "!latexmk -pdf -silent % > /dev/null" | redraw! +autocmd BufWritePost *.tex silent! execute "!sudo rm -rf *.fls *.ilg *.nav *.snm *.toc *.idx *.lof *.lot *.synctex.gz *.aux *.fdb_latexmk *.fls *.log *.out > /dev/null" | redraw! +autocmd BufWritePost *.tex silent! execute "!sudo pkill -HUP mupdf > /dev/null" | redraw! +autocmd FileType tex inoremap ,fr \begin{frame}\frametitle{}<++>\end{frame}<++>6kf}i +autocmd FileType tex inoremap ,fi \begin{fitch}\end{fitch}<++>3kA +autocmd FileType tex inoremap ,exe \begin{exe}\ex\end{exe}<++>3kA +autocmd FileType tex inoremap ,bf \textbf{}T{i +autocmd FileType tex inoremap ,co \coun{}\\T{i +autocmd FileType tex inoremap ,nbf \noindent\textbf{}\\T{i +autocmd FileType tex inoremap ,noi \noindentT{i +autocmd FileType tex inoremap ,ln \par\noindent \line(1,0){400}\T{i +autocmd FileType tex vnoremap , ``>2la}?\\{a +autocmd FileType tex inoremap ,it \textit{}<++>T{i +autocmd FileType tex inoremap ,ct \textcite{}<++>T{i +autocmd FileType tex inoremap ,glos {\gll<++>\\<++>\\\trans{``<++>''}}2k2bcw +autocmd FileType tex inoremap ,x \begin{xlist}\ex\end{xlist}kA +autocmd FileType tex inoremap ,ol \begin{enumerate}\end{enumerate}<++>3kA\item +autocmd FileType tex inoremap ,ul \begin{itemize}\end{itemize}<++>3kA\item +autocmd FileType tex inoremap ,li \item +autocmd FileType tex inoremap ,ref \ref{}<++>T{i +autocmd FileType tex inoremap ,tab \begin{tabular}<++>\end{tabular}<++>4kA{}i +autocmd FileType tex inoremap ,a \href{}{<++>}<++>2T{i +autocmd FileType tex inoremap ,chap \chapter{}<++>2kf}i +autocmd FileType tex inoremap ,sec \section{}<++>2kf}i +autocmd FileType tex inoremap ,ssec \subsection{}<++>2kf}i +autocmd FileType tex inoremap ,sssec \subsubsection{}<++>2kf}i +autocmd FileType tex inoremap ,st F{i*f}i +autocmd FileType tex inoremap ,tt \texttt{}<++>T{i +autocmd FileType tex inoremap ,bt {\blindtext} +autocmd FileType tex inoremap ,rn (\ref{})<++>F}i diff --git a/.zshrc b/.zshrc new file mode 100644 index 0000000..1051a5b --- /dev/null +++ b/.zshrc @@ -0,0 +1,86 @@ +cd $HOME +parse_git_branch() { + git symbolic-ref --short HEAD 2> /dev/null +} + +[ -f /etc/gentoo-release ] && export ZSH="/usr/share/zsh/site-contrib/oh-my-zsh" +[ -f /etc/centos-release ] && export ZSH="$HOME/.oh-my-zsh" + +HISTFILE=$HOME/.history_zsh +HISTSIZE=10000 +SAVEHIST=10000000 +autoload -U colors && colors +setopt PROMPT_SUBST +PS1='%B%{$fg[red]%}[%{$fg[yellow]%}%n%{$fg[green]%}@%{$fg[blue]%}%m %{$fg[magenta]%}%~%{$fg[red]%} $(parse_git_branch)]%{$reset_color%}$%b ' +plugins=(rake ruby vagrant knife knife_ssh kitchen ) + +ZSH_DISABLE_COMPFIX=true +source $ZSH/oh-my-zsh.sh +source $HOME/.sshservers +source $HOME/Linux/configs/zsh-autosuggestions/zsh-autosuggestions.plugin.zsh &>> /dev/null +source $HOME/Linux/configs/zsh-syntax-highlighting/zsh-syntax-highlighting.zsh &>> /dev/null +[ ! -d $HOME/.config/fzf ] && git clone https://github.com/junegunn/fzf.git $HOME/.config/fzf +[ -f $HOME/.config/fzf/shell/key-bindings.zsh ] && source $HOME/.config/fzf/shell/key-bindings.zsh +FPATH=/usr/local/share/zsh/site-functions:$FPATH +xset s off -dpms &>> /dev/null +xset b off &>> /dev/null +xset s off &>> /dev/null +xset -dpms &>> /dev/null +set bell-style none &>> /dev/null +setxkbmap pl &>> /dev/null + +export TERM=xterm-256color +export SHELL=/bin/bash +export GTK_IM_MODULE=ibus +export XMODIFIERS=@im=ibus +export QT_IM_MODULE=ibus +export _JAVA_AWT_WM_NONREPARENTING=1 +export CCACHE_DIR="/mnt/backup/ccache" +export LC_ALL="en_US.UTF-8" +export LANG=en_US.UTF-8 +export LC_ALL=en_US.UTF-8 +export BROWSER=/usr/bin/firefox +export FZF_DEFAULT_OPTS='--height 40% --layout=reverse' +export EIX_LIMIT_COMPACT=0 +export TERMINAL="st" +export QT_SCALE_FACTOR=1.5 +export VISUAL='vim' +export EDITOR='vim' +alias svm="sudo vim /etc/portage/make.conf" +alias svr="sudo vim /etc/portage/repos.conf" +alias svp="sudo vim /etc/portage/package.use" +alias emerge="sudo emerge" +alias channel-check='sudo iwlist wlan0 scan | egrep -i "essid|frequency"' +alias grep="grep --color=always" +alias egrep="egrep --color=always" +alias ls='ls -h --color=auto' +alias ll='ls -lha' +alias myip="curl ipinfo.io/ip" +alias logi="journalctl -f" +alias pl="setxkbmap pl" +alias graphic-card="glxinfo|egrep 'OpenGL vendor|OpenGL renderer'" +alias mylaptop-components="inxi -Fxz" +alias r="ranger" +alias v="vim" +alias feh="feh --scale-down" +alias changefont="figlet" +alias gmaster="git checkout master" +alias gcommit="git commit --author='Marcin Woźniak '" +alias gcommitwork="git commit --author='Marcin Woźniak '" +alias gadd="git add" +alias gpush="git push" +alias gpull="git pull" +alias glog="git log --color --graph --pretty=format:'%Cred%h%Creset -%C(yellow)%d%Creset %s %Cgreen(%cr) %C(bold blue)<%an>%Creset' --abbrev-commit --branches" +alias gfg="git checkout master && git fetch upstream && git pull upstream master" +alias cal="cal -3" +alias code="vscodium" +alias vpn="sudo /root/.local/bin/protonvpn c -f" +alias vpnch="sudo /root/.local/bin/protonvpn c --cc CH" +alias vpnd="sudo /root/.local/bin/protonvpn d" +alias vpnstatus="sudo /root/.local/bin/protonvpn status" +alias prolog="swipl" + +# Cleaning-up +export KODI_DATA="$HOME/.config/kodi" +export PATH=$HOME/.local/bin:$PATH +XDG_DATA_DIRS="$HOME/.local/share/flatpak/exports/share:/var/lib/flatpak/exports/share:$XDG_DATA_DIRS"