From ab7320297f5aaade4fb40d440b6f65a12286c7e3 Mon Sep 17 00:00:00 2001 From: Keanu Date: Thu, 31 Dec 2020 16:02:00 +0000 Subject: [PATCH 01/45] [scripts/discord-stream] Now uses separate file. --- nvim/dotfiles/plugins-list.vim | 1 + scripts/discord-stream-desktop-audio | 4 ++-- 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/nvim/dotfiles/plugins-list.vim b/nvim/dotfiles/plugins-list.vim index f8ec28c..9098d92 100644 --- a/nvim/dotfiles/plugins-list.vim +++ b/nvim/dotfiles/plugins-list.vim @@ -2,6 +2,7 @@ Plug 'tpope/vim-eunuch' if g:vim_ide Plug 'francoiscabrol/ranger.vim' + Plug 'rbgrouleff/bclose.vim' endif " }}} diff --git a/scripts/discord-stream-desktop-audio b/scripts/discord-stream-desktop-audio index 603e5a4..dd82faa 100755 --- a/scripts/discord-stream-desktop-audio +++ b/scripts/discord-stream-desktop-audio @@ -7,7 +7,7 @@ import os guild_id = int(sys.argv[1]) voice_channel_id = int(sys.argv[2]) -with open(os.path.expanduser("~/.config/dotfiles/discord-tools-bot-token.txt")) as f: +with open(os.path.expanduser("~/.config/dotfiles/discord-tools-user-token.txt")) as f: bot_token = f.read().strip() @@ -34,4 +34,4 @@ async def on_ready(): ) -bot.run(bot_token) +bot.run(bot_token, bot=False) From 5e2ea81830cb34a1db99376f1d6cd7f8e0d6c01c Mon Sep 17 00:00:00 2001 From: Keanu Date: Sat, 2 Jan 2021 18:39:31 +0100 Subject: [PATCH 02/45] [scripts/copy-emote] Removed requirement of 'safe' --- scripts/copy-crosscode-emoji-url | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/scripts/copy-crosscode-emoji-url b/scripts/copy-crosscode-emoji-url index ddca297..5354f37 100755 --- a/scripts/copy-crosscode-emoji-url +++ b/scripts/copy-crosscode-emoji-url @@ -53,7 +53,9 @@ def emote_downloader_and_iterator(): assert emote_registry_data["version"] == 1 - emotes = [emote for emote in emote_registry_data["list"] if emote["safe"]] + emotes = [emote for emote in emote_registry_data["list"] + # if emote["safe"] + ] for emote in emotes: yield "{emote[ref]} [{emote[guild_name]}]".format(emote=emote) From 51a3ea7777f55cd01be96fe62e1866088a0d89ee Mon Sep 17 00:00:00 2001 From: Keanu Date: Sat, 2 Jan 2021 18:41:31 +0100 Subject: [PATCH 03/45] [nvim] Added Lua to coc. --- nvim/coc-languages/lua.vim | 3 +++ 1 file changed, 3 insertions(+) create mode 100644 nvim/coc-languages/lua.vim diff --git a/nvim/coc-languages/lua.vim b/nvim/coc-languages/lua.vim new file mode 100644 index 0000000..e68ab5d --- /dev/null +++ b/nvim/coc-languages/lua.vim @@ -0,0 +1,3 @@ +let g:coc_global_extensions += ['coc-lua'] +let s:filetypes = ['lua'] +let g:coc_filetypes += s:filetypes From 0ddb5c5777da5a52724550ab7f33fe7befd12abb Mon Sep 17 00:00:00 2001 From: Keanu Date: Sat, 2 Jan 2021 18:41:54 +0100 Subject: [PATCH 04/45] [zsh] Added completions for gh cli. --- zsh/completions/_gh | 159 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 159 insertions(+) create mode 100644 zsh/completions/_gh diff --git a/zsh/completions/_gh b/zsh/completions/_gh new file mode 100644 index 0000000..b872834 --- /dev/null +++ b/zsh/completions/_gh @@ -0,0 +1,159 @@ +#compdef _gh gh + +# zsh completion for gh -*- shell-script -*- + +__gh_debug() +{ + local file="$BASH_COMP_DEBUG_FILE" + if [[ -n ${file} ]]; then + echo "$*" >> "${file}" + fi +} + +_gh() +{ + local shellCompDirectiveError=1 + local shellCompDirectiveNoSpace=2 + local shellCompDirectiveNoFileComp=4 + local shellCompDirectiveFilterFileExt=8 + local shellCompDirectiveFilterDirs=16 + + local lastParam lastChar flagPrefix requestComp out directive compCount comp lastComp + local -a completions + + __gh_debug "\n========= starting completion logic ==========" + __gh_debug "CURRENT: ${CURRENT}, words[*]: ${words[*]}" + + # The user could have moved the cursor backwards on the command-line. + # We need to trigger completion from the $CURRENT location, so we need + # to truncate the command-line ($words) up to the $CURRENT location. + # (We cannot use $CURSOR as its value does not work when a command is an alias.) + words=("${=words[1,CURRENT]}") + __gh_debug "Truncated words[*]: ${words[*]}," + + lastParam=${words[-1]} + lastChar=${lastParam[-1]} + __gh_debug "lastParam: ${lastParam}, lastChar: ${lastChar}" + + # For zsh, when completing a flag with an = (e.g., gh -n=) + # completions must be prefixed with the flag + setopt local_options BASH_REMATCH + if [[ "${lastParam}" =~ '-.*=' ]]; then + # We are dealing with a flag with an = + flagPrefix="-P ${BASH_REMATCH}" + fi + + # Prepare the command to obtain completions + requestComp="${words[1]} __complete ${words[2,-1]}" + if [ "${lastChar}" = "" ]; then + # If the last parameter is complete (there is a space following it) + # We add an extra empty parameter so we can indicate this to the go completion code. + __gh_debug "Adding extra empty parameter" + requestComp="${requestComp} \"\"" + fi + + __gh_debug "About to call: eval ${requestComp}" + + # Use eval to handle any environment variables and such + out=$(eval ${requestComp} 2>/dev/null) + __gh_debug "completion output: ${out}" + + # Extract the directive integer following a : from the last line + local lastLine + while IFS='\n' read -r line; do + lastLine=${line} + done < <(printf "%s\n" "${out[@]}") + __gh_debug "last line: ${lastLine}" + + if [ "${lastLine[1]}" = : ]; then + directive=${lastLine[2,-1]} + # Remove the directive including the : and the newline + local suffix + (( suffix=${#lastLine}+2)) + out=${out[1,-$suffix]} + else + # There is no directive specified. Leave $out as is. + __gh_debug "No directive found. Setting do default" + directive=0 + fi + + __gh_debug "directive: ${directive}" + __gh_debug "completions: ${out}" + __gh_debug "flagPrefix: ${flagPrefix}" + + if [ $((directive & shellCompDirectiveError)) -ne 0 ]; then + __gh_debug "Completion received error. Ignoring completions." + return + fi + + compCount=0 + while IFS='\n' read -r comp; do + if [ -n "$comp" ]; then + # If requested, completions are returned with a description. + # The description is preceded by a TAB character. + # For zsh's _describe, we need to use a : instead of a TAB. + # We first need to escape any : as part of the completion itself. + comp=${comp//:/\\:} + + local tab=$(printf '\t') + comp=${comp//$tab/:} + + ((compCount++)) + __gh_debug "Adding completion: ${comp}" + completions+=${comp} + lastComp=$comp + fi + done < <(printf "%s\n" "${out[@]}") + + if [ $((directive & shellCompDirectiveFilterFileExt)) -ne 0 ]; then + # File extension filtering + local filteringCmd + filteringCmd='_files' + for filter in ${completions[@]}; do + if [ ${filter[1]} != '*' ]; then + # zsh requires a glob pattern to do file filtering + filter="\*.$filter" + fi + filteringCmd+=" -g $filter" + done + filteringCmd+=" ${flagPrefix}" + + __gh_debug "File filtering command: $filteringCmd" + _arguments '*:filename:'"$filteringCmd" + elif [ $((directive & shellCompDirectiveFilterDirs)) -ne 0 ]; then + # File completion for directories only + local subDir + subdir="${completions[1]}" + if [ -n "$subdir" ]; then + __gh_debug "Listing directories in $subdir" + pushd "${subdir}" >/dev/null 2>&1 + else + __gh_debug "Listing directories in ." + fi + + _arguments '*:dirname:_files -/'" ${flagPrefix}" + if [ -n "$subdir" ]; then + popd >/dev/null 2>&1 + fi + elif [ $((directive & shellCompDirectiveNoSpace)) -ne 0 ] && [ ${compCount} -eq 1 ]; then + __gh_debug "Activating nospace." + # We can use compadd here as there is no description when + # there is only one completion. + compadd -S '' "${lastComp}" + elif [ ${compCount} -eq 0 ]; then + if [ $((directive & shellCompDirectiveNoFileComp)) -ne 0 ]; then + __gh_debug "deactivating file completion" + else + # Perform file completion + __gh_debug "activating file completion" + _arguments '*:filename:_files'" ${flagPrefix}" + fi + else + _describe "completions" completions $(echo $flagPrefix) + fi +} + +# don't run the completion function when being source-ed or eval-ed +if [ "$funcstack[1]" = "_gh" ]; then + _gh +fi From 5425d38058ee150c9bc38b23e13df1ef7ace9ba0 Mon Sep 17 00:00:00 2001 From: Keanu Date: Sat, 16 Jan 2021 14:17:26 +0100 Subject: [PATCH 05/45] Add pull config. --- .github/pull.yml | 6 ++++++ 1 file changed, 6 insertions(+) create mode 100644 .github/pull.yml diff --git a/.github/pull.yml b/.github/pull.yml new file mode 100644 index 0000000..2950aad --- /dev/null +++ b/.github/pull.yml @@ -0,0 +1,6 @@ +version: "1" +rules: + - base: master + upstream: dmitmel:master + mergeMethod: merge + mergeUnstable: true From 62611bb01e4a87a7f00b5d1dec9729127f8aec2e Mon Sep 17 00:00:00 2001 From: Keanu Date: Sun, 17 Jan 2021 12:07:14 +0100 Subject: [PATCH 06/45] [nvim] Added WakaTime plugin. --- nvim/dotfiles/plugins-list.vim | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/nvim/dotfiles/plugins-list.vim b/nvim/dotfiles/plugins-list.vim index 9098d92..69dfedd 100644 --- a/nvim/dotfiles/plugins-list.vim +++ b/nvim/dotfiles/plugins-list.vim @@ -65,3 +65,7 @@ Plug 'dag/vim2hs' endif " }}} + +" Misc {{{ + Plug 'wakatime/vim-wakatime' +" }}} From 159a142967fb08f3227eca60982ba4e57883e76a Mon Sep 17 00:00:00 2001 From: Keanu Date: Sun, 17 Jan 2021 12:07:31 +0100 Subject: [PATCH 07/45] Removed fasd stuff. --- zsh/plugins.zsh | 32 ++++++++++++++++---------------- 1 file changed, 16 insertions(+), 16 deletions(-) diff --git a/zsh/plugins.zsh b/zsh/plugins.zsh index edba661..0687e21 100644 --- a/zsh/plugins.zsh +++ b/zsh/plugins.zsh @@ -64,22 +64,22 @@ _plugin completions 'zsh-users/zsh-completions' "$_checkout_latest_version" # fasd {{{ -unalias j -j() { - local _fasd_ret - _fasd_ret="$( - # -l: list all paths in the database (without scores) - # -d: list only directories - # -R: in the reverse order - fasd -l -d -R | - fzf --height=40% --layout=reverse --tiebreak=index --query="$*" - )" - if [[ -d "$_fasd_ret" ]]; then - cd -- "$_fasd_ret" - elif [[ -n "$_fasd_ret" ]]; then - print -- "$_fasd_ret" - fi -} +#unalias j +#j() { +# local _fasd_ret +# _fasd_ret="$( +# # -l: list all paths in the database (without scores) +# # -d: list only directories +# # -R: in the reverse order +# fasd -l -d -R | +# fzf --height=40% --layout=reverse --tiebreak=index --query="$*" +# )" +# if [[ -d "$_fasd_ret" ]]; then +# cd -- "$_fasd_ret" +# elif [[ -n "$_fasd_ret" ]]; then +# print -- "$_fasd_ret" +# fi +#} # }}} From 4d6ff353f944cd47774386542af6f290b6f22d8a Mon Sep 17 00:00:00 2001 From: Keanu Date: Sun, 17 Jan 2021 14:26:01 +0100 Subject: [PATCH 08/45] Updated merge strategy. --- .github/pull.yml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/.github/pull.yml b/.github/pull.yml index 2950aad..a1afdb1 100644 --- a/.github/pull.yml +++ b/.github/pull.yml @@ -1,6 +1,6 @@ -version: "1" +version: '1' rules: - base: master upstream: dmitmel:master - mergeMethod: merge + mergeMethod: rebase mergeUnstable: true From 6998226ea195d95dff1f9c7d2b45e5e65d0b656b Mon Sep 17 00:00:00 2001 From: "pull[bot]" <39814207+pull[bot]@users.noreply.github.com> Date: Sun, 17 Jan 2021 14:28:31 +0100 Subject: [PATCH 09/45] updated --- scripts/copy-crosscode-emoji-url | 13 +++++++++++-- 1 file changed, 11 insertions(+), 2 deletions(-) diff --git a/scripts/copy-crosscode-emoji-url b/scripts/copy-crosscode-emoji-url index 5354f37..a72caf2 100755 --- a/scripts/copy-crosscode-emoji-url +++ b/scripts/copy-crosscode-emoji-url @@ -5,6 +5,7 @@ import os from configparser import ConfigParser import requests import json +import urllib.parse sys.path.insert(1, os.path.join(os.path.dirname(__file__), "..", "script-resources")) @@ -66,12 +67,20 @@ chosen_index = common_script_utils.run_chooser( ) chosen_emote = emotes[chosen_index] -emote_url = chosen_emote["url"] +emote_url = urllib.parse.urlparse(chosen_emote["url"]) +emote_url_query = urllib.parse.parse_qs(emote_url.query) + default_emote_image_size = config.getint( "default", "default_emote_image_size", fallback=None ) if default_emote_image_size is not None: - emote_url += "?size={}".format(default_emote_image_size) + emote_url_query["size"] = [str(default_emote_image_size)] + +if config.getboolean("default", "add_emote_name_to_url", fallback=False): + emote_url_query["name"] = [chosen_emote["name"]] + +emote_url_query = urllib.parse.urlencode(emote_url_query, doseq=True) +emote_url = urllib.parse.urlunparse(emote_url._replace(query=emote_url_query)) common_script_utils.set_clipboard(emote_url) From 3d7078d8a14d4a282e0251ef41e08b76a9233133 Mon Sep 17 00:00:00 2001 From: Dmytro Meleshko Date: Mon, 18 Jan 2021 11:18:34 +0200 Subject: [PATCH 10/45] [scripts/copy-crosscode-emoji-url] change the order of URL params --- scripts/copy-crosscode-emoji-url | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/scripts/copy-crosscode-emoji-url b/scripts/copy-crosscode-emoji-url index a72caf2..03d26cd 100755 --- a/scripts/copy-crosscode-emoji-url +++ b/scripts/copy-crosscode-emoji-url @@ -70,15 +70,15 @@ chosen_emote = emotes[chosen_index] emote_url = urllib.parse.urlparse(chosen_emote["url"]) emote_url_query = urllib.parse.parse_qs(emote_url.query) +if config.getboolean("default", "add_emote_name_to_url", fallback=False): + emote_url_query["name"] = [chosen_emote["name"]] + default_emote_image_size = config.getint( "default", "default_emote_image_size", fallback=None ) if default_emote_image_size is not None: emote_url_query["size"] = [str(default_emote_image_size)] -if config.getboolean("default", "add_emote_name_to_url", fallback=False): - emote_url_query["name"] = [chosen_emote["name"]] - emote_url_query = urllib.parse.urlencode(emote_url_query, doseq=True) emote_url = urllib.parse.urlunparse(emote_url._replace(query=emote_url_query)) From 819e5e5a33d70eea8dc7c79365d17eeb3dc58517 Mon Sep 17 00:00:00 2001 From: Dmytro Meleshko Date: Wed, 20 Jan 2021 10:45:30 +0200 Subject: [PATCH 11/45] update the copyright years --- LICENSE | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/LICENSE b/LICENSE index 5258a2b..98d3340 100644 --- a/LICENSE +++ b/LICENSE @@ -1,6 +1,6 @@ MIT License -Copyright (c) 2018-2020 Dmytro Meleshko +Copyright (c) 2018-2021 Dmytro Meleshko Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal From 4cc4389455b9d885ebe615dab2108c49085e07f5 Mon Sep 17 00:00:00 2001 From: Dmytro Meleshko Date: Wed, 20 Jan 2021 17:37:55 +0200 Subject: [PATCH 12/45] [nvim] make the airline theme match my syntax theme even more --- nvim/autoload/airline/themes/dotfiles.vim | 24 +++++++++++++++++++---- 1 file changed, 20 insertions(+), 4 deletions(-) diff --git a/nvim/autoload/airline/themes/dotfiles.vim b/nvim/autoload/airline/themes/dotfiles.vim index 752d247..374b6a3 100644 --- a/nvim/autoload/airline/themes/dotfiles.vim +++ b/nvim/autoload/airline/themes/dotfiles.vim @@ -1,4 +1,12 @@ -let s:palette = {} +let s:palette = { +\ "inactive" : {}, +\ "replace" : {}, +\ "normal" : {}, +\ "visual" : {}, +\ "insert" : {}, +\ "terminal" : {}, +\ "commandline" : {}, +\ } let s:colors = g:dotfiles_colorscheme_base16_colors function! s:base16_color(fg, bg) @@ -16,9 +24,11 @@ let s:palette.normal = airline#themes#generate_color_map( \ s:section_c) let s:section_a_overrides = { -\ 'insert' : s:base16_color(0x1, 0xD), -\ 'replace': s:base16_color(0x1, 0x8), -\ 'visual' : s:base16_color(0x1, 0xE), +\ 'insert' : s:base16_color(0x1, 0xD), +\ 'visual' : s:base16_color(0x1, 0xE), +\ 'replace' : s:base16_color(0x1, 0x8), +\ 'terminal' : s:base16_color(0x1, 0xD), +\ 'commandline' : s:base16_color(0x1, 0xC), \ } for [s:mode, s:color] in items(s:section_a_overrides) let s:palette[s:mode] = { 'airline_a': s:color, 'airline_z': s:color } @@ -40,4 +50,10 @@ if get(g:, 'loaded_ctrlp', 0) \ s:ctrlp_white) endif +for s:mode in keys(s:palette) + let s:palette[s:mode]['airline_warning'] = s:base16_color(0x0, 0xA) + let s:palette[s:mode]['airline_error'] = s:base16_color(0x0, 0x8) + let s:palette[s:mode]['airline_term'] = s:base16_color(0x9, 0x1) +endfor + let airline#themes#dotfiles#palette = s:palette From 06ff96bf30dd53c3331fa633326e699a5e45d04d Mon Sep 17 00:00:00 2001 From: Dmytro Meleshko Date: Thu, 21 Jan 2021 12:49:13 +0200 Subject: [PATCH 13/45] [nvim] add a plugin for RON --- nvim/dotfiles/plugins-list.vim | 1 + 1 file changed, 1 insertion(+) diff --git a/nvim/dotfiles/plugins-list.vim b/nvim/dotfiles/plugins-list.vim index 69dfedd..fbde4f6 100644 --- a/nvim/dotfiles/plugins-list.vim +++ b/nvim/dotfiles/plugins-list.vim @@ -60,6 +60,7 @@ " Programming {{{ Plug 'sheerun/vim-polyglot' Plug 'chikamichi/mediawiki.vim' + Plug 'ron-rs/ron.vim' if g:vim_ide Plug 'neoclide/coc.nvim', { 'branch': 'release' } Plug 'dag/vim2hs' From 4b6cf8c56a7492bbb7715a06b40a9831677fc7e7 Mon Sep 17 00:00:00 2001 From: Dmytro Meleshko Date: Mon, 25 Jan 2021 11:04:02 +0200 Subject: [PATCH 14/45] [nvim] fix the commentstring in po files --- nvim/after/syntax/nginx.vim | 2 +- nvim/after/syntax/po.vim | 1 + 2 files changed, 2 insertions(+), 1 deletion(-) create mode 100644 nvim/after/syntax/po.vim diff --git a/nvim/after/syntax/nginx.vim b/nvim/after/syntax/nginx.vim index 3ef6892..fb06acc 100644 --- a/nvim/after/syntax/nginx.vim +++ b/nvim/after/syntax/nginx.vim @@ -5,4 +5,4 @@ " set in `ftplugin/nginx.vim` and sets `comments` to some garbage. This script " undoes that damage. let &l:comments = &g:comments -let &l:commentstring = '# %s' +let &l:commentstring = '#%s' diff --git a/nvim/after/syntax/po.vim b/nvim/after/syntax/po.vim new file mode 100644 index 0000000..d345d77 --- /dev/null +++ b/nvim/after/syntax/po.vim @@ -0,0 +1 @@ +setl commentstring=#%s From e277f19ed3af53372af0aae719731e34edeb4e86 Mon Sep 17 00:00:00 2001 From: Dmytro Meleshko Date: Mon, 25 Jan 2021 18:37:50 +0200 Subject: [PATCH 15/45] [zsh] fix the manpath-caused errors on shell startup once and for all --- zsh/path.zsh | 2 +- zsh/zplg.zsh | 2 +- zsh/zshrc | 11 ++++++++--- 3 files changed, 10 insertions(+), 5 deletions(-) diff --git a/zsh/path.zsh b/zsh/path.zsh index 7bf8cac..19c4695 100644 --- a/zsh/path.zsh +++ b/zsh/path.zsh @@ -12,7 +12,7 @@ path_prepend() { fi local var_name="$1"; shift local value; for value in "$@"; do - if eval "(( \${${var_name}[(ie)\$value]} > \${#${var_name}} ))"; then + if eval "(( \${${var_name}[(ie)\$value]-1} > \${#${var_name}} ))"; then eval "${var_name}=(\"\$value\" \"\${${var_name}[@]}\")" fi done diff --git a/zsh/zplg.zsh b/zsh/zplg.zsh index d0a3355..f6a16bf 100644 --- a/zsh/zplg.zsh +++ b/zsh/zplg.zsh @@ -399,7 +399,7 @@ plugin() { else value="${plugin_dir}/${value}" fi - if eval "(( \${${var_name}[(ie)\$value]} > \${#${var_name}} ))"; then + if eval "(( \${${var_name}[(ie)\$value]-1} > \${#${var_name}} ))"; then case "$operator" in prepend) eval "$var_name=(\"\$value\" \${$var_name[@]})" ;; append) eval "$var_name=(\${$var_name[@]} \"\$value\")" ;; diff --git a/zsh/zshrc b/zsh/zshrc index 729b50e..3513103 100644 --- a/zsh/zshrc +++ b/zsh/zshrc @@ -46,15 +46,20 @@ _perf_timer_start "total" fi # }}} +# For some reason manpath is not always set when logging with ssh for instance. +# Let's ensure that it is always set and exported. The additional colon ensures +# that the system manpath isn't overwritten (see manpath(1)), though in reality +# two colons get added for some reason, which is also valid, but means +# something slightly different (again, see manpath(1)). Hope this won't cause +# any problems in the future. +export MANPATH="$MANPATH:" + for script in functions options path env plugins aliases completion zle prompt colorscheme; do _perf_timer_start "$script.zsh" source "$ZSH_DOTFILES/$script.zsh" _perf_timer_stop "$script.zsh" done -# add colon after MANPATH so that it doesn't overwrite system MANPATH -MANPATH="$MANPATH:" - command_exists rbenv && eval "$(rbenv init -)" _perf_timer_stop "total" From 7f3dfb96bea906b439778562386dd0249eec77b3 Mon Sep 17 00:00:00 2001 From: Keanu Date: Thu, 28 Jan 2021 16:23:34 +0100 Subject: [PATCH 16/45] [nvim] Added plugin coc-explorer. --- nvim/dotfiles/plugins-list.vim | 1 + 1 file changed, 1 insertion(+) diff --git a/nvim/dotfiles/plugins-list.vim b/nvim/dotfiles/plugins-list.vim index fbde4f6..fd4b244 100644 --- a/nvim/dotfiles/plugins-list.vim +++ b/nvim/dotfiles/plugins-list.vim @@ -4,6 +4,7 @@ Plug 'francoiscabrol/ranger.vim' Plug 'rbgrouleff/bclose.vim' endif + Plug 'weirongxu/coc-explorer' " }}} " Editing {{{ From 1e50762fcbd7244678d15f6d95d55715c13798e0 Mon Sep 17 00:00:00 2001 From: Dmytro Meleshko Date: Fri, 29 Jan 2021 01:37:49 +0200 Subject: [PATCH 17/45] [nvim+zsh] fix the need for resetting FZF_DEFAULT_OPTS on Ubuntu and derivatives --- nvim/plugin/interface.vim | 2 +- zsh/env.zsh | 2 -- 2 files changed, 1 insertion(+), 3 deletions(-) diff --git a/nvim/plugin/interface.vim b/nvim/plugin/interface.vim index 7a196d3..3f2e4e2 100644 --- a/nvim/plugin/interface.vim +++ b/nvim/plugin/interface.vim @@ -147,7 +147,7 @@ endif nnoremap f Files nnoremap b Buffers let g:fzf_layout = { 'down': '~40%' } - let $FZF_DEFAULT_OPTS = '--preview-window=sharp' + let g:fzf_preview_window = ['right:noborder', 'ctrl-/'] " }}} diff --git a/zsh/env.zsh b/zsh/env.zsh index 796896d..eca6fb0 100644 --- a/zsh/env.zsh +++ b/zsh/env.zsh @@ -30,6 +30,4 @@ jq_colors=( export JQ_COLORS="${(j.:.)jq_colors}" unset jq_colors -export FZF_DEFAULT_OPTS='--preview-window=sharp' - export HOMEBREW_NO_AUTO_UPDATE=1 From b45d969f0cd9779d303b309947318c35925a90a8 Mon Sep 17 00:00:00 2001 From: Dmytro Meleshko Date: Fri, 29 Jan 2021 12:34:26 +0200 Subject: [PATCH 18/45] [git] add temporary files to the gitignore --- git/gitignore_global | 1 + 1 file changed, 1 insertion(+) diff --git a/git/gitignore_global b/git/gitignore_global index 36465da..d5cb4b8 100644 --- a/git/gitignore_global +++ b/git/gitignore_global @@ -2,3 +2,4 @@ Session.vim .project.vim .DS_Store .ropeproject +*~ From a659106248bdf63841ec19efdae210f684f25bd8 Mon Sep 17 00:00:00 2001 From: Keanu Date: Sat, 30 Jan 2021 14:17:07 +0100 Subject: [PATCH 19/45] [scripts/copy-env-var] Script to copy envvars. --- scripts/copy-env-var | 11 +++++++++++ 1 file changed, 11 insertions(+) create mode 100755 scripts/copy-env-var diff --git a/scripts/copy-env-var b/scripts/copy-env-var new file mode 100755 index 0000000..9a4d88d --- /dev/null +++ b/scripts/copy-env-var @@ -0,0 +1,11 @@ +#!/usr/bin/env bash +set -euo pipefail + +if variable="$(set -euo pipefail; { + awk 'BEGIN{for(v in ENVIRON) print v}' +} | rofi -dmenu)" && [[ -n $variable ]]; then + + variable="${variable%% *}" + + echo ${!variable} | xclip -sel clip +fi From 57f0e01b511f459a43f792723c8948f0746b5165 Mon Sep 17 00:00:00 2001 From: Dmytro Meleshko Date: Mon, 1 Feb 2021 12:44:49 +0200 Subject: [PATCH 20/45] [nvim] disable rust-analyzer's diagnostics and autoimports --- nvim/coc-languages/rust.vim | 20 +++++++------------- 1 file changed, 7 insertions(+), 13 deletions(-) diff --git a/nvim/coc-languages/rust.vim b/nvim/coc-languages/rust.vim index dac412a..8deabe8 100644 --- a/nvim/coc-languages/rust.vim +++ b/nvim/coc-languages/rust.vim @@ -2,19 +2,13 @@ let g:coc_filetypes += ['rust'] let g:coc_global_extensions += ['coc-rust-analyzer'] let g:coc_user_config['rust-analyzer'] = { \ 'serverPath': 'rust-analyzer', -\ 'lens': { -\ 'enable': v:false, -\ }, -\ 'inlayHints': { -\ 'typeHints': v:false, -\ 'chainingHints': v:false, -\ }, -\ 'checkOnSave': { -\ 'command': 'clippy', -\ }, -\ 'cargo': { -\ 'loadOutDirsFromCheck': v:true, -\ }, +\ 'lens.enable': v:false, +\ 'inlayHints.typeHints': v:false, +\ 'inlayHints.chainingHints': v:false, +\ 'diagnostics.enable': v:false, +\ 'completion.autoimport.enable': v:false, +\ 'checkOnSave.command': 'clippy', +\ 'cargo.loadOutDirsFromCheck': v:true, \ } " let g:coc_global_extensions += ['coc-rls'] From ed93c816f90795828bfe45c2c3db1d97e899254f Mon Sep 17 00:00:00 2001 From: Dmytro Meleshko Date: Tue, 2 Feb 2021 22:28:48 +0200 Subject: [PATCH 21/45] [nvim] bring back a fix removed in 14e64127e4fd068f28581bc11a52d73d8dc772c0 --- nvim/after/ftplugin/javascript.vim | 1 + 1 file changed, 1 insertion(+) create mode 100644 nvim/after/ftplugin/javascript.vim diff --git a/nvim/after/ftplugin/javascript.vim b/nvim/after/ftplugin/javascript.vim new file mode 100644 index 0000000..d4217f4 --- /dev/null +++ b/nvim/after/ftplugin/javascript.vim @@ -0,0 +1 @@ +setlocal matchpairs-=<:> From 60f8ca378893a5e2d19126f948fef152d64fd7dd Mon Sep 17 00:00:00 2001 From: Dmytro Meleshko Date: Tue, 2 Feb 2021 22:50:51 +0200 Subject: [PATCH 22/45] [zsh] display the current pyenv version in the prompt --- zsh/prompt.zsh | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/zsh/prompt.zsh b/zsh/prompt.zsh index 0644c0a..aa79b0e 100644 --- a/zsh/prompt.zsh +++ b/zsh/prompt.zsh @@ -1,7 +1,5 @@ #!/usr/bin/env zsh -export VIRTUAL_ENV_DISABLE_PROMPT=false - # Escapes `%` in all arguments by replacing it with `%%`. Escaping is needed so # that untrusted input (e.g. git branch names) doesn't affect prompt rendering. prompt_escape() { @@ -102,6 +100,11 @@ PROMPT+='$(prompt_vcs_info 2>/dev/null)' # Python's virtualenv PROMPT+='${VIRTUAL_ENV:+" %F{blue}venv:%F{magenta}${VIRTUAL_ENV:t}%f"}' +VIRTUAL_ENV_DISABLE_PROMPT=true + +# pyenv +PROMPT+='${PYENV_VERSION:+" %F{blue}pyenv:%F{magenta}${PYENV_VERSION:t}%f"}' +PYENV_VIRTUAL_ENV_DISABLE_PROMPT=true PROMPT+=' ' From 18700a8198434b63961b0a9afbccd9d3a69d8516 Mon Sep 17 00:00:00 2001 From: Dmytro Meleshko Date: Thu, 4 Feb 2021 14:52:53 +0200 Subject: [PATCH 23/45] [scripts/welcome] add logo for Manjaro ARM --- script-resources/welcome/logos/manjaro-arm | 1 + 1 file changed, 1 insertion(+) create mode 120000 script-resources/welcome/logos/manjaro-arm diff --git a/script-resources/welcome/logos/manjaro-arm b/script-resources/welcome/logos/manjaro-arm new file mode 120000 index 0000000..aae509e --- /dev/null +++ b/script-resources/welcome/logos/manjaro-arm @@ -0,0 +1 @@ +manjaro \ No newline at end of file From bcf58ced93a261e941809095073fabd7264c0714 Mon Sep 17 00:00:00 2001 From: Dmytro Meleshko Date: Thu, 4 Feb 2021 19:29:41 +0200 Subject: [PATCH 24/45] [kitty] enable the only two layouts I actually use --- kitty/kitty.conf | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/kitty/kitty.conf b/kitty/kitty.conf index 1c2dc19..f420e22 100644 --- a/kitty/kitty.conf +++ b/kitty/kitty.conf @@ -236,7 +236,7 @@ bell_on_tab yes #: suffix of "c" on the width/height values to have them interpreted #: as number of cells instead of pixels. -# enabled_layouts * +enabled_layouts horizontal, vertical #: The enabled window layouts. A comma separated list of layout names. #: The special value all means all layouts. The first listed layout From f2882476712fcdc450c5edd35b6a9d0806e25a35 Mon Sep 17 00:00:00 2001 From: Dmytro Meleshko Date: Thu, 4 Feb 2021 19:58:19 +0200 Subject: [PATCH 25/45] [kitty] remove the sample config and keep only the changed bits --- kitty/kitty.conf | 916 ++--------------------------------------------- 1 file changed, 28 insertions(+), 888 deletions(-) diff --git a/kitty/kitty.conf b/kitty/kitty.conf index f420e22..d06cc3b 100644 --- a/kitty/kitty.conf +++ b/kitty/kitty.conf @@ -1,772 +1,52 @@ include ../colorschemes/out/kitty.conf -#: Fonts {{{ - -#: kitty has very powerful font management. You can configure -#: individual font faces and even specify special fonts for particular -#: characters. - -# font_family monospace -# bold_font auto -# italic_font auto -# bold_italic_font auto - -#: You can specify different fonts for the bold/italic/bold-italic -#: variants. By default they are derived automatically, by the OSes -#: font system. Setting them manually is useful for font families that -#: have many weight variants like Book, Medium, Thick, etc. For -#: example:: - -#: font_family Operator Mono Book -#: bold_font Operator Mono Medium -#: italic_font Operator Mono Book Italic -#: bold_italic_font Operator Mono Medium Italic - -# font_size 14.0 - -#: Font size (in pts) - -# adjust_line_height 0 -# adjust_column_width 0 - -#: Change the size of each character cell kitty renders. You can use -#: either numbers, which are interpreted as pixels or percentages -#: (number followed by %), which are interpreted as percentages of the -#: unmodified values. You can use negative pixels or percentages less -#: than 100% to reduce sizes (but this might cause rendering -#: artifacts). - -# symbol_map U+E0A0-U+E0A2,U+E0B0-U+E0B3 PowerlineSymbols - -#: Map the specified unicode codepoints to a particular font. Useful -#: if you need special rendering for some symbols, such as for -#: Powerline. Avoids the need for patched fonts. Each unicode code -#: point is specified in the form U+. You -#: can specify multiple code points, separated by commas and ranges -#: separated by hyphens. symbol_map itself can be specified multiple -#: times. Syntax is:: - -#: symbol_map codepoints Font Family Name - -# box_drawing_scale 0.001, 1, 1.5, 2 - -#: Change the sizes of the lines used for the box drawing unicode -#: characters These values are in pts. They will be scaled by the -#: monitor DPI to arrive at a pixel value. There must be four values -#: corresponding to thin, normal, thick, and very thick lines. - -#: }}} - -#: Cursor customization {{{ - -# cursor #cccccc - -#: Default cursor color - -# cursor_text_color #111111 - -#: Choose the color of text under the cursor. If you want it rendered -#: with the background color of the cell underneath instead, use the -#: special keyword: background - -# cursor_shape block - -#: The cursor shape can be one of (block, beam, underline) - +# Mouse {{{ +# Disable cursor blinking cursor_blink_interval 0 cursor_stop_blinking_after 0 +mouse_hide_wait 1 +# }}} -#: The interval (in seconds) at which to blink the cursor. Set to zero -#: to disable blinking. Note that numbers smaller than repaint_delay -#: will be limited to repaint_delay. Stop blinking cursor after the -#: specified number of seconds of keyboard inactivity. Set to zero to -#: never stop blinking. - -#: }}} - -#: Scrollback {{{ - -# scrollback_lines 2000 - -#: Number of lines of history to keep in memory for scrolling back. -#: Memory is allocated on demand. Negative numbers are (effectively) -#: infinite scrollback. Note that using very large scrollback is not -#: recommended a it can slow down resizing of the terminal and also -#: use large amounts of RAM. - -# scrollback_pager less --chop-long-lines --RAW-CONTROL-CHARS +INPUT_LINE_NUMBER - -#: Program with which to view scrollback in a new window. The -#: scrollback buffer is passed as STDIN to this program. If you change -#: it, make sure the program you use can handle ANSI escape sequences -#: for colors and text formatting. INPUT_LINE_NUMBER in the command -#: line above will be replaced by an integer representing which line -#: should be at the top of the screen. - -# wheel_scroll_multiplier 5.0 - -#: Modify the amount scrolled by the mouse wheel. Note this is only -#: used for low precision scrolling devices, not for high precision -#: scrolling on platforms such as macOS and Wayland. Use negative -#: numbers to change scroll direction. - -#: }}} - -#: Mouse {{{ - -# url_color #0087bd -url_style single - -#: The color and style for highlighting URLs on mouse-over. url_style -#: can be one of: none, single, double, curly - -# open_url_modifiers kitty_mod - -#: The modifier keys to press when clicking with the mouse on URLs to -#: open the URL - -# open_url_with default - -#: The program with which to open URLs that are clicked on. The -#: special value default means to use the operating system's default -#: URL handler. - -# copy_on_select no - -#: Copy to clipboard on select. With this enabled, simply selecting -#: text with the mouse will cause the text to be copied to clipboard. -#: Useful on platforms such as macOS/Wayland that do not have the -#: concept of primary selections. Note that this is a security risk, -#: as all programs, including websites open in your browser can read -#: the contents of the clipboard. - -# rectangle_select_modifiers ctrl+alt - -#: The modifiers to use rectangular selection (i.e. to select text in -#: a rectangular block with the mouse) - -# select_by_word_characters :@-./_~?&=%+# - -#: Characters considered part of a word when double clicking. In -#: addition to these characters any character that is marked as an -#: alpha-numeric character in the unicode database will be matched. - -# click_interval 0.5 - -#: The interval between successive clicks to detect double/triple -#: clicks (in seconds) - -mouse_hide_wait 3.0 - -#: Hide mouse cursor after the specified number of seconds of the -#: mouse not being used. Set to zero to disable mouse cursor hiding. - -focus_follows_mouse no - -#: Set the active window to the window under the mouse when moving the -#: mouse around - -#: }}} - -#: Performance tuning {{{ - -# repaint_delay 10 - -#: Delay (in milliseconds) between screen updates. Decreasing it, -#: increases frames-per-second (FPS) at the cost of more CPU usage. -#: The default value yields ~100 FPS which is more than sufficient for -#: most uses. Note that to actually achieve 100 FPS you have to either -#: set sync_to_monitor to no or use a monitor with a high refresh -#: rate. - -# input_delay 3 - -#: Delay (in milliseconds) before input from the program running in -#: the terminal is processed. Note that decreasing it will increase -#: responsiveness, but also increase CPU usage and might cause flicker -#: in full screen programs that redraw the entire screen on each loop, -#: because kitty is so fast that partial screen updates will be drawn. - -sync_to_monitor yes - -#: Sync screen updates to the refresh rate of the monitor. This -#: prevents tearing (https://en.wikipedia.org/wiki/Screen_tearing) -#: when scrolling. However, it limits the rendering speed to the -#: refresh rate of your monitor. With a very high speed mouse/high -#: keyboard repeat rate, you may notice some slight input latency. If -#: so, set this to no. - -#: }}} - -#: Terminal bell {{{ - -# enable_audio_bell yes - -#: Enable/disable the audio bell. Useful in environments that require -#: silence. - -# visual_bell_duration 0.0 - -#: Visual bell duration. Flash the screen when a bell occurs for the -#: specified number of seconds. Set to zero to disable. - -window_alert_on_bell yes - -#: Request window attention on bell. Makes the dock icon bounce on -#: macOS or the taskbar flash on linux. - -bell_on_tab yes - -#: Show a bell symbol on the tab if a bell occurs in one of the -#: windows in the tab and the window is not the currently focused -#: window - -#: }}} - -#: Window layout {{{ - -# remember_window_size yes -# initial_window_width 640 -# initial_window_height 400 - -#: If enabled, the window size will be remembered so that new -#: instances of kitty will have the same size as the previous -#: instance. If disabled, the window will initially have size -#: configured by initial_window_width/height, in pixels. You can use a -#: suffix of "c" on the width/height values to have them interpreted -#: as number of cells instead of pixels. - -enabled_layouts horizontal, vertical - -#: The enabled window layouts. A comma separated list of layout names. -#: The special value all means all layouts. The first listed layout -#: will be used as the startup layout. For a list of available -#: layouts, see the -#: https://sw.kovidgoyal.net/kitty/index.html#layouts. - -# window_resize_step_cells 2 -# window_resize_step_lines 2 - -#: The step size (in units of cell width/cell height) to use when -#: resizing windows. The cells value is used for horizontal resizing -#: and the lines value for vertical resizing. - -# window_border_width 1.0 - -#: The width (in pts) of window borders. Will be rounded to the -#: nearest number of pixels based on screen resolution. Note that -#: borders are displayed only when more than one window is visible. -#: They are meant to separate multiple windows. - -# draw_minimal_borders no - -#: Draw only the minimum borders needed. This means that only the -#: minimum needed borders for inactive windows are drawn. That is only -#: the borders that separate the inactive window from a neighbor. Note -#: that setting a non-zero window margin overrides this and causes all -#: borders to be drawn. - -window_margin_width 1.0 - -#: The window margin (in pts) (blank area outside the border) - -# single_window_margin_width -1000.0 - -#: The window margin (in pts) to use when only a single window is -#: visible. Negative values will cause the value of -#: window_margin_width to be used instead. - -window_padding_width 2.0 - -#: The window padding (in pts) (blank area between the text and the -#: window border) - -# active_border_color #00ff00 - -#: The color for the border of the active window - -# inactive_border_color #cccccc - -#: The color for the border of inactive windows - -# bell_border_color #ff5a00 - -#: The color for the border of inactive windows in which a bell has -#: occurred - -inactive_text_alpha 0.5 - -#: Fade the text in inactive windows by the specified amount (a number -#: between zero and one, with zero being fully faded). - +# OS Windows {{{ +# Always ask for confirmation before closing OS windows confirm_os_window_close 1 -#: Ask for confirmation when closing an OS window that has at least this -#: number of kitty windows in it. A value of zero disables confirmation. -#: This confirmation also applies to requests to quit the entire application (all -#: OS windows, via the quite action). +# }}} -#: }}} - -#: Tab bar {{{ +# Windows {{{ +# These are the only layouts I use: +enabled_layouts horizontal, vertical +window_margin_width 1.0 +window_padding_width 2.0 +inactive_text_alpha 0.5 +# }}} +# Tabs {{{ tab_bar_edge top - -#: Which edge to show the tab bar on, top or bottom - -# tab_bar_margin_width 0.0 - -#: The margin to the left and right of the tab bar (in pts) - -# TODO: change this to "separator" if maintainer of kitty agrees with me. -# see https://github.com/kovidgoyal/kitty/pull/2480 -# fortunately, kitty seems to have built-in powerline character support tab_bar_style powerline - -#: The tab bar style, can be one of: fade or separator. In the fade -#: style, each tab's edges fade into the background color, in the -#: separator style, tabs are separated by a configurable separator. - -# tab_fade 0.25 0.5 0.75 1 - -#: Control how each tab fades into the background when using fade for -#: the tab_bar_style. Each number is an alpha (between zero and one) -#: that controls how much the corresponding cell fades into the -#: background, with zero being no fade and one being full fade. You -#: can change the number of cells used by adding/removing entries to -#: this list. - +# This option doesn't really do anything when the tab bar style is `powerline`, +# but this Unicode character is a nice find, so let's keep it just in case. tab_separator " │ " - -#: The separator between tabs in the tab bar when using separator as -#: the tab_bar_style. - +# Always show the tab bar tab_bar_min_tabs 1 - -# active_tab_foreground #000 -# active_tab_background #eee active_tab_font_style bold -# inactive_tab_foreground #444 -# inactive_tab_background #999 inactive_tab_font_style none +# }}} -#: Tab bar colors and styles - -#: }}} - -#: Color scheme {{{ - -# foreground #dddddd -# background #000000 - -#: The foreground and background colors - -# background_opacity 1.0 -# dynamic_background_opacity no - -#: The opacity of the background. A number between 0 and 1, where 1 is -#: opaque and 0 is fully transparent. This will only work if -#: supported by the OS (for instance, when using a compositor under -#: X11). Note that it only sets the default background color's -#: opacity. This is so that things like the status bar in vim, -#: powerline prompts, etc. still look good. But it means that if you -#: use a color theme with a background color in your editor, it will -#: not be rendered as transparent. Instead you should change the -#: default background color in your kitty config and not use a -#: background color in the editor color scheme. Or use the escape -#: codes to set the terminals default colors in a shell script to -#: launch your editor. Be aware that using a value less than 1.0 is a -#: (possibly significant) performance hit. If you want to dynamically -#: change transparency of windows set dynamic_background_opacity to -#: yes (this is off by default as it has a performance cost) - -# dim_opacity 0.75 - -#: How much to dim text that has the DIM/FAINT attribute set. One -#: means no dimming and zero means fully dimmed (i.e. invisible). - -# selection_foreground #000000 -# selection_background #fffacd - -#: The foreground and background for text selected with the mouse - - -#: The 16 terminal colors. There are 8 basic colors, each color has a -#: dull and bright version. You can also set the remaining colors from -#: the 256 color table as color16 to color255. - -# color0 #000000 -# color8 #767676 - -#: black - -# color1 #cc0403 -# color9 #f2201f - -#: red - -# color2 #19cb00 -# color10 #23fd00 - -#: green - -# color3 #cecb00 -# color11 #fffd00 - -#: yellow - -# color4 #0d73cc -# color12 #1a8fff - -#: blue - -# color5 #cb1ed1 -# color13 #fd28ff - -#: magenta - -# color6 #0dcdcd -# color14 #14ffff - -#: cyan - -# color7 #dddddd -# color15 #ffffff - -#: white - -#: }}} - -#: Advanced {{{ - -# shell sh -c 'exec login -f -p $USER' -# shell zsh --login - -#: The shell program to execute. The default value of . means to use -#: whatever shell is set as the default shell for the current user. -#: Note that on macOS if you change this, you might need to add -#: --login to ensure that the shell starts in interactive mode and -#: reads its startup rc files. - -# editor . - -#: The console editor to use when editing the kitty config file or -#: similar tasks. A value of . means to use the environment variable -#: EDITOR. Note that this environment variable has to be set not just -#: in your shell startup scripts but system-wide, otherwise kitty will -#: not see it. - -# close_on_child_death no - -#: Close the window when the child process (shell) exits. If no (the -#: default), the terminal will remain open when the child exits as -#: long as there are still processes outputting to the terminal (for -#: example disowned or backgrounded processes). If yes, the window -#: will close as soon as the child process exits. Note that setting it -#: to yes means that any background processes still using the terminal -#: can fail silently because their stdout/stderr/stdin no longer work. - -# allow_remote_control no - -#: Allow other programs to control kitty. If you turn this on other -#: programs can control all aspects of kitty, including sending text -#: to kitty windows, opening new windows, closing windows, reading the -#: content of windows, etc. Note that this even works over ssh -#: connections. - -# env - -#: Specify environment variables to set in all child processes. Note -#: that environment variables are expanded recursively, so if you -#: use:: - -#: env MYVAR1=a -#: env MYVAR2=${MYVAR}/${HOME}/b - -#: The value of MYVAR2 will be a//b. - -# startup_session none - -#: Path to a session file to use for all kitty instances. Can be -#: overridden by using the kitty --session command line option for -#: individual instances. See -#: https://sw.kovidgoyal.net/kitty/index.html#sessions in the kitty -#: documentation for details. Note that relative paths are interpreted -#: with respect to the kitty config directory. Environment variables -#: in the path are expanded. - -# clipboard_control write-clipboard write-primary - -#: Allow programs running in kitty to read and write from the -#: clipboard. You can control exactly which actions are allowed. The -#: set of possible actions is: write-clipboard read-clipboard write- -#: primary read-primary The default is to allow writing to the -#: clipboard and primary selection. Note that enabling the read -#: functionality is a security risk as it means that any program, even -#: one running on a remote server via SSH can read your clipboard. - -# term xterm-kitty +# Miscellaneous {{{ +# Tip: on high-DPI screens the `double` style is more discernible +url_style single +# To be honest I don't have even a slightest clue as for why I changed the TERM term xterm-256color +# }}} -#: The value of the TERM environment variable to set. Changing this -#: can break many terminal programs, only change it if you know what -#: you are doing, not because you read some advice on Stack Overflow -#: to change it. The TERM variable if used by various programs to get -#: information about the capabilities and behavior of the terminal. If -#: you change it, depending on what programs you run, and how -#: different the terminal you are changing it to is, various things -#: from key-presses, to colors, to various advanced features may not -#: work. - -#: }}} - -#: OS specific tweaks {{{ - -# macos_titlebar_color system - -#: Change the color of the kitty window's titlebar on macOS. A value -#: of system means to use the default system color, a value of -#: background means to use the background color of the currently -#: active window and finally you can use an arbitrary color, such as -#: #12af59 or red. WARNING: This option works by using a hack, as -#: there is no proper Cocoa API for it. It sets the background color -#: of the entire window and makes the titlebar transparent. As such it -#: is incompatible with background_opacity. If you want to use both, -#: you are probably better off just hiding the titlebar with -#: macos_hide_titlebar. - -# macos_hide_titlebar no - -#: Hide the kitty window's title bar on macOS. - -# x11_hide_window_decorations no - -#: Hide the window decorations (title bar and window borders) on X11 -#: and Wayland. Whether this works and exactly what effect it has -#: depends on the window manager, as it is the job of the window -#: manager/compositor to draw window decorations. - +# macOS-specific settings {{{ macos_option_as_alt yes - -#: Use the option key as an alt key. With this set to no, kitty will -#: use the macOS native Option+Key = unicode character behavior. This -#: will break any Alt+key keyboard shortcuts in your terminal -#: programs, but you can use the macOS unicode input technique. - -# macos_hide_from_tasks no - -#: Hide the kitty window from running tasks (Option+Tab) on macOS. - -# macos_quit_when_last_window_closed no - -#: Have kitty quit when all the top-level windows are closed. By -#: default, kitty will stay running, even with no open windows, as is -#: the expected behavior on macOS. - -# macos_window_resizable yes - -#: Disable this if you want kitty top-level (OS) windows to not be -#: resizable on macOS. - -# macos_thicken_font 0 - -#: Draw an extra border around the font with the given width, to -#: increase legibility at small font sizes. For example, a value of -#: 0.75 will result in rendering that looks similar to sub-pixel -#: antialiasing at common font sizes. - -# macos_traditional_fullscreen no - -#: Use the traditional full-screen transition, that is faster, but -#: less pretty. - macos_custom_beam_cursor yes - -#: Enable/disable custom mouse cursor for macOS that is easier to see -#: on both light and dark backgrounds. WARNING: this might make your -#: mouse cursor invisible on dual GPU machines. - macos_show_window_title_in window +# open_url_modifiers cmd +# }}} -#: }}} - -#: Keyboard shortcuts {{{ - -#: For a list of key names, see: GLFW keys -#: . The name to use -#: is the part after the GLFW_KEY_ prefix. For a list of modifier -#: names, see: GLFW mods -#: - -#: On Linux you can also use XKB key names to bind keys that are not -#: supported by GLFW. See XKB keys -#: -#: for a list of key names. The name to use is the part after the XKB_KEY_ -#: prefix. Note that you should only use an XKB key name for keys that are not -#: present in the list of GLFW keys. - -#: Finally, you can use raw system key codes to map keys. To see the -#: system key code for a key, start kitty with the kitty --debug- -#: keyboard option. Then kitty will output some debug text for every -#: key event. In that text look for ``native_code`` the value of that -#: becomes the key name in the shortcut. For example: - -#: .. code-block:: none - -#: on_key_input: glfw key: 65 native_code: 0x61 action: PRESS mods: 0x0 text: 'a' - -#: Here, the key name for the A key is 0x61 and you can use it with:: - -#: map ctrl+0x61 something - -#: to map ctrl+a to something. - -#: You can use the special action no_op to unmap a keyboard shortcut -#: that is assigned in the default configuration. - -#: You can combine multiple actions to be triggered by a single -#: shortcut, using the syntax below:: - -#: map key combine action1 action2 action3 ... - -#: For example:: - -#: map kitty_mod+e combine : new_window : next_layout - -#: this will create a new window and switch to the next available -#: layout - -#: You can use multi-key shortcuts using the syntax shown below:: - -#: map key1>key2>key3 action - -#: For example:: - -#: map ctrl+f>2 set_font_size 20 - -# kitty_mod ctrl+shift - -#: The value of kitty_mod is used as the modifier for all default -#: shortcuts, you can change it in your kitty.conf to change the -#: modifiers for all the default shortcuts. - -# clear_all_shortcuts no - -#: You can have kitty remove all shortcut definition seen up to this -#: point. Useful, for instance, to remove the default shortcuts. - -#: Clipboard {{{ - -# map cmd+c copy_to_clipboard -# map kitty_mod+c copy_to_clipboard -# map cmd+v paste_from_clipboard -# map kitty_mod+v paste_from_clipboard -# map kitty_mod+s paste_from_selection -# map shift+insert paste_from_selection -# map kitty_mod+o pass_selection_to_program - -#: You can also pass the contents of the current selection to any -#: program using pass_selection_to_program. By default, the system's -#: open program is used, but you can specify your own, for example:: - -#: map kitty_mod+o pass_selection_to_program firefox - -#: You can pass the current selection to a terminal program running in -#: a new kitty window, by using the @selection placeholder:: - -#: map kitty_mod+y new_window less @selection - -#: }}} - -#: Scrolling {{{ - -# map kitty_mod+up scroll_line_up -# map kitty_mod+k scroll_line_up -# map kitty_mod+down scroll_line_down -# map kitty_mod+j scroll_line_down -# map kitty_mod+page_up scroll_page_up -# map kitty_mod+page_down scroll_page_down -# map kitty_mod+home scroll_home -# map kitty_mod+end scroll_end -# map kitty_mod+h show_scrollback - -#: You can pipe the contents of the current screen + history buffer as -#: STDIN to an arbitrary program using the ``pipe`` function. For -#: example, the following opens the scrollback buffer in less in an -#: overlay window:: - -#: map f1 pipe @ansi overlay less +G -R - -#: Placeholders available are: @text (which is plain text) and @ansi -#: (which includes text styling escape codes). For only the current -#: screen, use @screen or @ansi_screen. For the secondary screen, use -#: @alternate and @ansi_alternate. The secondary screen is the screen -#: not currently displayed. For example if you run a fullscreen -#: terminal application, the secondary screen will be the screen you -#: return to when quitting the application. You can also use ``none`` -#: for no STDIN input. - -#: To open in a new window, tab or new OS window, use ``window``, -#: ``tab``, or ``os_window`` respectively. You can also use ``none`` -#: in which case the data will be piped into the program without -#: creating any windows, useful if the program is a GUI program that -#: creates its own windows. - -#: }}} - -#: Window management {{{ - -# map kitty_mod+enter new_window - -#: You can open a new window running an arbitrary program, for -#: example:: - -#: map kitty_mod+y new_window mutt - -#: You can open a new window with the current working directory set to -#: the working directory of the current window using:: - -#: map ctrl+alt+enter new_window_with_cwd - -#: You can open a new window that is allowed to control kitty via the -#: kitty remote control facility by prefixing the command line with @. -#: Any programs running in that window will be allowed to control -#: kitty. For example:: - -#: map ctrl+enter new_window @ some_program - -# map cmd+n new_os_window -# map kitty_mod+n new_os_window -# map kitty_mod+w close_window -# map kitty_mod+] next_window -# map kitty_mod+[ previous_window -# map kitty_mod+f move_window_forward -# map kitty_mod+b move_window_backward -# map kitty_mod+` move_window_to_top -# map kitty_mod+r start_resizing_window -# map kitty_mod+1 first_window -# map kitty_mod+2 second_window -# map kitty_mod+3 third_window -# map kitty_mod+4 fourth_window -# map kitty_mod+5 fifth_window -# map kitty_mod+6 sixth_window -# map kitty_mod+7 seventh_window -# map kitty_mod+8 eighth_window -# map kitty_mod+9 ninth_window -# map kitty_mod+0 tenth_window -#: }}} - -#: Tab management {{{ - -# map ctrl+tab next_tab -# map kitty_mod+right next_tab -# map ctrl+shift+tab previous_tab -# map kitty_mod+left previous_tab -# map kitty_mod+t new_tab -# map kitty_mod+q close_tab -# map kitty_mod+. move_tab_forward -# map kitty_mod+, move_tab_backward -# map kitty_mod+alt+t set_tab_title - +# Keybindings {{{ map kitty_mod+1 goto_tab 1 map kitty_mod+2 goto_tab 2 map kitty_mod+3 goto_tab 3 @@ -777,144 +57,4 @@ map kitty_mod+7 goto_tab 7 map kitty_mod+8 goto_tab 8 map kitty_mod+9 goto_tab 9 map kitty_mod+0 goto_tab 10 - -#: You can also create shortcuts to go to specific tabs, with 1 being -#: the first tab:: - -#: map ctrl+alt+1 goto_tab 1 -#: map ctrl+alt+2 goto_tab 2 - -#: Just as with new_window above, you can also pass the name of -#: arbitrary commands to run when using new_tab and use -#: new_tab_with_cwd. Finally, if you want the new tab to open next to -#: the current tab rather than at the end of the tabs list, use:: - -#: map ctrl+t new_tab !neighbor [optional cmd to run] -#: }}} - -#: Layout management {{{ - -# map kitty_mod+l next_layout - -#: You can also create shortcuts to switch to specific layouts:: - -#: map ctrl+alt+t goto_layout tall -#: map ctrl+alt+s goto_layout stack - -#: Similarly, to switch back to the previous layout:: - -#: map ctrl+alt+p last_used_layout -#: }}} - -#: Font sizes {{{ - -#: You can change the font size for all top-level kitty windows at a -#: time or only the current one. - -# map kitty_mod+equal change_font_size all +2.0 -# map kitty_mod+minus change_font_size all -2.0 -# map kitty_mod+backspace change_font_size all 0 - -#: To setup shortcuts for specific font sizes:: - -#: map kitty_mod+f6 change_font_size all 10.0 - -#: To setup shortcuts to change only the current window's font size:: - -#: map kitty_mod+f6 change_font_size current 10.0 -#: }}} - -#: Select and act on visible text {{{ - -#: Use the hints kitten to select text and either pass it to an -#: external program or insert it into the terminal or copy it to the -#: clipboard. - -# map kitty_mod+e kitten hints - -#: Open a currently visible URL using the keyboard. The program used -#: to open the URL is specified in open_url_with. - -# map kitty_mod+p>f kitten hints --type path --program - - -#: Select a path/filename and insert it into the terminal. Useful, for -#: instance to run git commands on a filename output from a previous -#: git command. - -# map kitty_mod+p>shift+f kitten hints --type path - -#: Select a path/filename and open it with the default open program. - -# map kitty_mod+p>l kitten hints --type line --program - - -#: Select a line of text and insert it into the terminal. Use for the -#: output of things like: ls -1 - -# map kitty_mod+p>w kitten hints --type word --program - - -#: Select words and insert into terminal. - -# map kitty_mod+p>h kitten hints --type hash --program - - -#: Select something that looks like a hash and insert it into the -#: terminal. Useful with git, which uses sha1 hashes to identify -#: commits - - -#: The hints kitten has many more modes of operation that you can map -#: to different shortcuts. For a full description see kittens/hints. -#: }}} - -#: Miscellaneous {{{ - -# map kitty_mod+f11 toggle_fullscreen -# map kitty_mod+u kitten unicode_input -# map kitty_mod+f2 edit_config_file -# map kitty_mod+escape kitty_shell window - -#: Open the kitty shell in a new window/tab/overlay/os_window to -#: control kitty using commands. - -# map kitty_mod+a>m set_background_opacity +0.1 -# map kitty_mod+a>l set_background_opacity -0.1 -# map kitty_mod+a>1 set_background_opacity 1 -# map kitty_mod+a>d set_background_opacity default -# map kitty_mod+delete clear_terminal reset active - -#: You can create shortcuts to clear/reset the terminal. For example:: - -#: map kitty_mod+f9 clear_terminal reset active -#: map kitty_mod+f10 clear_terminal clear active -#: map kitty_mod+f11 clear_terminal scrollback active - -#: These will reset screen/clear screen/clear screen+scrollback -#: respectively. If you want to operate on all windows instead of just -#: the current one, use all instead of :italic`active`. - - -#: You can tell kitty to send arbitrary (UTF-8) encoded text to the -#: client program when pressing specified shortcut keys. For example:: - -#: map ctrl+alt+a send_text all Special text - -#: This will send "Special text" when you press the ctrl+alt+a key -#: combination. The text to be sent is a python string literal so you -#: can use escapes like \x1b to send control codes or \u21fb to send -#: unicode characters (or you can just input the unicode characters -#: directly as UTF-8 text). The first argument to send_text is the -#: keyboard modes in which to activate the shortcut. The possible -#: values are normal or application or kitty or a comma separated -#: combination of them. The special keyword all means all modes. The -#: modes normal and application refer to the DECCKM cursor key mode -#: for terminals, and kitty refers to the special kitty extended -#: keyboard protocol. - -#: Another example, that outputs a word and then moves the cursor to -#: the start of the line (same as pressing the Home key):: - -#: map ctrl+alt+a send_text normal Word\x1b[H -#: map ctrl+alt+a send_text application Word\x1bOH - -#: }}} - # }}} From a27c05856a790e268a323a8be9f317204f38fc4f Mon Sep 17 00:00:00 2001 From: Dmytro Meleshko Date: Fri, 5 Feb 2021 11:13:25 +0200 Subject: [PATCH 26/45] [zsh] add a timestamp printing function --- zsh/functions.zsh | 1 + 1 file changed, 1 insertion(+) diff --git a/zsh/functions.zsh b/zsh/functions.zsh index 88edb32..e008988 100644 --- a/zsh/functions.zsh +++ b/zsh/functions.zsh @@ -83,6 +83,7 @@ declare -A date_formats=( compact '%Y%m%d%H%M%S' only-date '%Y-%m-%d' only-time '%H:%M:%S' + timestamp '%s' ) for format_name format in "${(kv)date_formats[@]}"; do From 618995cc7f1893648df9d5f38ab49edfed024ca0 Mon Sep 17 00:00:00 2001 From: Dmytro Meleshko Date: Fri, 5 Feb 2021 11:54:51 +0200 Subject: [PATCH 27/45] [nvim] add functions to workaround some interesting behaviors of vim --- nvim/plugin/editing.vim | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/nvim/plugin/editing.vim b/nvim/plugin/editing.vim index 817f7cc..c042cd2 100644 --- a/nvim/plugin/editing.vim +++ b/nvim/plugin/editing.vim @@ -152,6 +152,11 @@ set commentstring=//%s \|xmap # call VisualStarSearch('?')N augroup END + " + command! -nargs=+ Search let @/ = escape(, '/') | normal // + " + command! -nargs=+ SearchLiteral let @/ = '\V'.escape(, '/\') | normal // + " }}} From da7c44af354bbc3d8233fcbbf2e2ed0d3fe6b714 Mon Sep 17 00:00:00 2001 From: Dmytro Meleshko Date: Fri, 5 Feb 2021 11:57:28 +0200 Subject: [PATCH 28/45] [nvim] fix FixWhitespaceOnSave flooding the search history --- nvim/plugin/files.vim | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/nvim/plugin/files.vim b/nvim/plugin/files.vim index f07659f..b9266d5 100644 --- a/nvim/plugin/files.vim +++ b/nvim/plugin/files.vim @@ -144,9 +144,9 @@ nnoremap empty(&buftype) ? ":writewall\" : "\" function s:FixWhitespaceOnSave() let l:pos = getpos('.') " remove trailing whitespace - %s/\s\+$//e + keeppatterns %s/\s\+$//e " remove trailing newlines - %s/\($\n\s*\)\+\%$//e + keeppatterns %s/\($\n\s*\)\+\%$//e call setpos('.', l:pos) endfunction " }}} From a59a693e98a56e93a9d26855abc40f397da72824 Mon Sep 17 00:00:00 2001 From: Dmytro Meleshko Date: Sun, 7 Feb 2021 19:49:38 +0200 Subject: [PATCH 29/45] [zsh] use Python 3 by default on macOS --- zsh/path.zsh | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/zsh/path.zsh b/zsh/path.zsh index 19c4695..16e85bd 100644 --- a/zsh/path.zsh +++ b/zsh/path.zsh @@ -44,9 +44,11 @@ if (( _is_macos )); then if [[ -d "$formula_path/lib/pkgconfig" ]]; then path_prepend pkg_config_path "$formula_path/lib/pkgconfig" fi - done + done; unset formula - unset formula + # Use Python 3 executables by default, i.e. when a version suffix (`python3`) + # is not specified. + path_prepend path /usr/local/opt/python@3/libexec/bin fi if (( _is_macos )); then From 33ed3720c813d9623ceaea2c1c84315746932606 Mon Sep 17 00:00:00 2001 From: Dmytro Meleshko Date: Mon, 8 Feb 2021 20:07:02 +0200 Subject: [PATCH 30/45] [ranger] add ranger config --- ranger/rc.conf | 3 +++ 1 file changed, 3 insertions(+) create mode 100644 ranger/rc.conf diff --git a/ranger/rc.conf b/ranger/rc.conf new file mode 100644 index 0000000..9e4bf36 --- /dev/null +++ b/ranger/rc.conf @@ -0,0 +1,3 @@ +set show_hidden true +set preview_images true +set preview_images_method kitty From b15a03c3f91678242655e17716ff2afc6828d830 Mon Sep 17 00:00:00 2001 From: Dmytro Meleshko Date: Mon, 8 Feb 2021 20:07:14 +0200 Subject: [PATCH 31/45] [kitty] stop changing TERM to something non-default --- kitty/kitty.conf | 2 -- 1 file changed, 2 deletions(-) diff --git a/kitty/kitty.conf b/kitty/kitty.conf index d06cc3b..714c9eb 100644 --- a/kitty/kitty.conf +++ b/kitty/kitty.conf @@ -35,8 +35,6 @@ inactive_tab_font_style none # Miscellaneous {{{ # Tip: on high-DPI screens the `double` style is more discernible url_style single -# To be honest I don't have even a slightest clue as for why I changed the TERM -term xterm-256color # }}} # macOS-specific settings {{{ From 851a494eb0b6be7bc6f48f6d6e3c7d358dd53b40 Mon Sep 17 00:00:00 2001 From: Dmytro Meleshko Date: Mon, 8 Feb 2021 21:51:59 +0200 Subject: [PATCH 32/45] [nvim] properly display wavy underlines under spelling mistakes now that I have enabled all termcap features of kitty --- nvim/colors/dotfiles.vim | 13 +++++++++---- nvim/plugin/interface.vim | 4 ++-- 2 files changed, 11 insertions(+), 6 deletions(-) diff --git a/nvim/colors/dotfiles.vim b/nvim/colors/dotfiles.vim index 6ca399f..03ab4e9 100644 --- a/nvim/colors/dotfiles.vim +++ b/nvim/colors/dotfiles.vim @@ -137,10 +137,15 @@ hi! link ctrlsfMatch Search hi! link ctrlsfLnumMatch ctrlsfMatch - call s:hi('SpellBad', 'bg', '', 'undercurl', 0x8) - call s:hi('SpellLocal', 'bg', '', 'undercurl', 0xC) - call s:hi('SpellCap', 'bg', '', 'undercurl', 0xD) - call s:hi('SpellRare', 'bg', '', 'undercurl', 0xE) + let s:is_kitty = $TERM ==# 'xterm-kitty' + let s:spell_fg = s:is_kitty ? '' : 'bg' + let s:spell_bg = s:is_kitty ? 'NONE' : '' + let s:spell_attr = s:is_kitty ? 'undercurl' : '' + call s:hi('SpellBad', s:spell_fg, s:spell_bg, s:spell_attr, 0x8) + call s:hi('SpellLocal', s:spell_fg, s:spell_bg, s:spell_attr, 0xC) + call s:hi('SpellCap', s:spell_fg, s:spell_bg, s:spell_attr, 0xD) + call s:hi('SpellRare', s:spell_fg, s:spell_bg, s:spell_attr, 0xE) + unlet s:is_kitty s:spell_fg s:spell_bg s:spell_attr call s:hi('Sneak', 'bg', 0xB, 'bold', '') hi! link SneakScope Visual diff --git a/nvim/plugin/interface.vim b/nvim/plugin/interface.vim index 3f2e4e2..03693c7 100644 --- a/nvim/plugin/interface.vim +++ b/nvim/plugin/interface.vim @@ -44,9 +44,9 @@ endif let l:cmd = a:cmd if &modified let l:answer = confirm("Save changes?", "&Yes\n&No\n&Cancel") - if l:answer is# 1 " Yes + if l:answer ==# 1 " Yes write - elseif l:answer is# 2 " No + elseif l:answer ==# 2 " No let l:cmd .= '!' else " Cancel/Other return From 6bd741c2368af99ddfcf9d74eda95ce0f7b104e6 Mon Sep 17 00:00:00 2001 From: Dmytro Meleshko Date: Tue, 9 Feb 2021 12:29:15 +0200 Subject: [PATCH 33/45] [nvim] disable matchpairs in all other JS-like filetypes --- nvim/after/ftplugin/javascriptreact.vim | 1 + nvim/after/ftplugin/typescript.vim | 1 + nvim/after/ftplugin/typescriptreact.vim | 1 + 3 files changed, 3 insertions(+) create mode 100644 nvim/after/ftplugin/javascriptreact.vim create mode 100644 nvim/after/ftplugin/typescript.vim create mode 100644 nvim/after/ftplugin/typescriptreact.vim diff --git a/nvim/after/ftplugin/javascriptreact.vim b/nvim/after/ftplugin/javascriptreact.vim new file mode 100644 index 0000000..2d9e54a --- /dev/null +++ b/nvim/after/ftplugin/javascriptreact.vim @@ -0,0 +1 @@ +source :h/javascript.vim diff --git a/nvim/after/ftplugin/typescript.vim b/nvim/after/ftplugin/typescript.vim new file mode 100644 index 0000000..2d9e54a --- /dev/null +++ b/nvim/after/ftplugin/typescript.vim @@ -0,0 +1 @@ +source :h/javascript.vim diff --git a/nvim/after/ftplugin/typescriptreact.vim b/nvim/after/ftplugin/typescriptreact.vim new file mode 100644 index 0000000..6a77e28 --- /dev/null +++ b/nvim/after/ftplugin/typescriptreact.vim @@ -0,0 +1 @@ +source :h/typescript.vim From 2a0ffb0cf59554bbfa981e17cd91f8507b2c6e0d Mon Sep 17 00:00:00 2001 From: Dmytro Meleshko Date: Fri, 12 Feb 2021 10:21:53 +0200 Subject: [PATCH 34/45] [crosscode] add a mod for binding mouse buttons to actions --- crosscode/btw-i-use-arch-mod/prestart.js | 154 +++++++++++++++++++++++ 1 file changed, 154 insertions(+) diff --git a/crosscode/btw-i-use-arch-mod/prestart.js b/crosscode/btw-i-use-arch-mod/prestart.js index bc03b9a..9be33fe 100644 --- a/crosscode/btw-i-use-arch-mod/prestart.js +++ b/crosscode/btw-i-use-arch-mod/prestart.js @@ -5,3 +5,157 @@ sc.OPTIONS_DEFINITION['keys-btw-i-use-arch.open-map-menu'] = { hasDivider: true, header: 'btw-i-use-arch', }; + +ig.KEY.MOUSE_LEFT = ig.KEY.MOUSE1; +ig.KEY.MOUSE_RIGHT = ig.KEY.MOUSE2; +ig.KEY.MOUSE_MIDDLE = -6; +ig.KEY.MOUSE_BACK = -7; +ig.KEY.MOUSE_FORWARD = -8; + +// As for the copied implementations of ig.Input#keydown and ig.Input#keyup: +// there is probably a way to avoid copying, most notably by abusing the logic +// of the keyCode check. See, in both methods it is basically the same, just +// with differing event names, but the logic is as follows: if the event is a +// keyboard event, get the `keyCode` property, otherwise check if +// `event.button` is 2, then assume the key is `ig.KEY.MOUSE2`, otherwise +// `ig.KEY.MOUSE1`. This means that I could replace the value of the `MOUSE1` +// constant to the keyCode determined with my custom logic, and so the fallback +// path will read my value, but ultimately I didn't do that because I figured +// there might be other parts of these functions which can use some +// refactoring. +ig.Input.inject({ + keydown(event) { + if ( + ig.system.crashed || + this.isInIframeAndUnfocused() || + (this.ignoreKeyboard && event.type !== 'mousedown') + ) { + return; + } + + if (ig.system.hasFocusLost()) { + if (event.type === 'mousedown') { + ig.system.regainFocus(); + } + return; + } + + if (event.type === 'mousedown') { + this.mouseGuiActive = true; + } + this.currentDevice = ig.INPUT_DEVICES.KEYBOARD_AND_MOUSE; + + if (event.target.type === 'text') { + return; + } + + let keyCode = this.getKeyCodeFromEvent(event); + + if ( + // It's quite interesting that the game kinda supports touch events, but + // they are never actually used in practice. + event.type === 'touchstart' || + event.type === 'mousedown' + ) { + this.mousemove(event); + } + + let action = this.bindings[keyCode]; + if (action != null) { + this.actions[action] = true; + // Not sure what are locks supposed to do. Oh wait, I figured it out: + // this is so that if a button is detected to be pressed in a frame, but + // if an un-press event is caught during the processing of the frame, the + // button... Hmmm, still not sure. Entirety of the game logic blocks the + // main thread, so it's impossible to catch two events during processing + // of the frame. + if (!this.locks[action]) { + this.presses[action] = true; + this.locks[action] = true; + } + event.stopPropagation(); + event.preventDefault(); + } + }, + + keyup(event) { + if ( + ig.system.crashed || + this.isInIframeAndUnfocused() || + (this.ignoreKeyboard && event.type !== 'mouseup') || + event.target.type === 'text' || + (ig.system.hasFocusLost() && event.type === 'mouseup') + ) { + return; + } + + this.currentDevice = ig.INPUT_DEVICES.KEYBOARD_AND_MOUSE; + + let keyCode = this.getKeyCodeFromEvent(event); + + let action = this.bindings[keyCode]; + if (action != null) { + this.keyups[action] = true; + this.delayedKeyup.push(action); + event.stopPropagation(); + event.preventDefault(); + } + }, + + getKeyCodeFromEvent(event) { + switch (event.type) { + case 'keyup': + case 'keydown': + return event.keyCode; + + case 'mouseup': + case 'mousedown': + switch (event.button) { + case 0: + return ig.KEY.MOUSE_LEFT; + case 1: + return ig.KEY.MOUSE_MIDDLE; + case 2: + return ig.KEY.MOUSE_RIGHT; + case 3: + return ig.KEY.MOUSE_BACK; + case 4: + return ig.KEY.MOUSE_FORWARD; + } + } + + // idk, fall back to the left mouse button. That's kind of what the default + // implementation does though. + return ig.KEY.MOUSE_LEFT; + }, +}); + +// Finally, some nice injection places. +sc.KeyBinderGui.inject({ + show(...args) { + this.parent(...args); + window.addEventListener('mousedown', this.bindedKeyCheck, false); + }, + + hide(...args) { + this.parent(...args); + window.removeEventListener('mousedown', this.bindedKeyCheck); + }, + + onKeyCheck(event) { + event.preventDefault(); + + let keyCode = ig.input.getKeyCodeFromEvent(event); + if (ig.interact.isBlocked() || this._isBlackedListed(keyCode)) return; + + // This call was added by me. Just in case. Because the `stopPropagation` + // call in `ig.Input` saved me from re-binds of left/right mouse buttons to + // whatever else other than interactions with menus. + event.stopPropagation(); + + if (this.finishCallback != null) { + this.finishCallback(keyCode, this.isAlternative, false); + } + this.hide(); + }, +}); From b0eef7960236b686f6ac562f569402c7caac583b Mon Sep 17 00:00:00 2001 From: Dmytro Meleshko Date: Fri, 12 Feb 2021 10:43:39 +0200 Subject: [PATCH 35/45] [nvim] disable ESLint integration for Prettier, sync configs --- nvim/coc-languages/javascript.vim | 12 ++++++++++-- 1 file changed, 10 insertions(+), 2 deletions(-) diff --git a/nvim/coc-languages/javascript.vim b/nvim/coc-languages/javascript.vim index e6b8c5a..98b3f26 100644 --- a/nvim/coc-languages/javascript.vim +++ b/nvim/coc-languages/javascript.vim @@ -5,10 +5,18 @@ let g:coc_user_config['eslint'] = { \ 'filetypes': s:filetypes, \ 'autoFixOnSave': v:true, \ } +" See let g:coc_user_config['prettier'] = { +\ 'printWidth': 100, +\ 'tabWidth': 2, +\ 'useTabs': v:false, +\ 'semi': v:true, \ 'singleQuote': v:true, +\ 'quoteProps': 'as-needed', +\ 'jsxSingleQuote': v:false, \ 'trailingComma': 'all', +\ 'bracketSpacing': v:true, \ 'jsxBracketSameLine': v:true, -\ 'eslintIntegration': v:true, -\ 'disableSuccessMessage': v:true +\ 'arrowParens': 'always', +\ 'disableSuccessMessage': v:true, \ } From 6fc06191a5dbd93b90bc84b496d6df49323a7cfc Mon Sep 17 00:00:00 2001 From: Dmytro Meleshko Date: Fri, 12 Feb 2021 10:51:34 +0200 Subject: [PATCH 36/45] [scripts/discord-stream-desktop-audio] allow specifying the audio device --- scripts/discord-stream-desktop-audio | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/scripts/discord-stream-desktop-audio b/scripts/discord-stream-desktop-audio index dd82faa..0161def 100755 --- a/scripts/discord-stream-desktop-audio +++ b/scripts/discord-stream-desktop-audio @@ -6,6 +6,7 @@ import os guild_id = int(sys.argv[1]) voice_channel_id = int(sys.argv[2]) +pulseaudio_device = sys.argv[3] with open(os.path.expanduser("~/.config/dotfiles/discord-tools-user-token.txt")) as f: bot_token = f.read().strip() @@ -28,7 +29,7 @@ async def on_ready(): voice_client = await voice_channel.connect() print("connected to {0} ({0.id}) in {1} ({1.id})".format(voice_channel, guild)) - source = discord.FFmpegPCMAudio("default", before_options="-f pulse") + source = discord.FFmpegPCMAudio(pulseaudio_device, before_options="-f pulse") voice_client.play( source, after=lambda e: print("Player error: %s" % e) if e else None ) From 9555e5f7068ee579f723080bc43d9a7abd665c20 Mon Sep 17 00:00:00 2001 From: Dmytro Meleshko Date: Fri, 12 Feb 2021 15:27:03 +0200 Subject: [PATCH 37/45] [x11] add my xprofile --- x11/xprofile.sh | 5 +++++ 1 file changed, 5 insertions(+) create mode 100755 x11/xprofile.sh diff --git a/x11/xprofile.sh b/x11/xprofile.sh new file mode 100755 index 0000000..eddbe8f --- /dev/null +++ b/x11/xprofile.sh @@ -0,0 +1,5 @@ +#!/usr/bin/env sh + +export XDG_MENU_PREFIX=lxde- +export MOZ_USE_XINPUT2=1 +export QT_QPA_PLATFORMTHEME=qt5ct From f9051aff76bdf2c3e9a0ebd862db6b7d48df2ca7 Mon Sep 17 00:00:00 2001 From: Keanu Date: Fri, 19 Feb 2021 21:47:22 +0100 Subject: [PATCH 38/45] Why was this on `rebase` again? --- .github/pull.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/pull.yml b/.github/pull.yml index a1afdb1..08de30a 100644 --- a/.github/pull.yml +++ b/.github/pull.yml @@ -2,5 +2,5 @@ version: '1' rules: - base: master upstream: dmitmel:master - mergeMethod: rebase + mergeMethod: merge mergeUnstable: true From 81d185be53bf31dce6ba4fbd5337807651e37fe9 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Mon, 1 Mar 2021 20:56:44 +0000 Subject: [PATCH 39/45] Bump prismjs from 1.21.0 to 1.23.0 in /script-resources/markdown2htmldoc Bumps [prismjs](https://github.com/PrismJS/prism) from 1.21.0 to 1.23.0. - [Release notes](https://github.com/PrismJS/prism/releases) - [Changelog](https://github.com/PrismJS/prism/blob/master/CHANGELOG.md) - [Commits](https://github.com/PrismJS/prism/compare/v1.21.0...v1.23.0) Signed-off-by: dependabot[bot] --- script-resources/markdown2htmldoc/package.json | 2 +- script-resources/markdown2htmldoc/yarn.lock | 8 ++++---- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/script-resources/markdown2htmldoc/package.json b/script-resources/markdown2htmldoc/package.json index cc1dae8..9bdddea 100644 --- a/script-resources/markdown2htmldoc/package.json +++ b/script-resources/markdown2htmldoc/package.json @@ -7,7 +7,7 @@ "markdown-it": "*", "markdown-it-emoji": "*", "markdown-it-task-checkbox": "*", - "prismjs": "^1.21.0" + "prismjs": "^1.23.0" }, "devDependencies": { "eslint": "*", diff --git a/script-resources/markdown2htmldoc/yarn.lock b/script-resources/markdown2htmldoc/yarn.lock index ecb8902..7da943a 100644 --- a/script-resources/markdown2htmldoc/yarn.lock +++ b/script-resources/markdown2htmldoc/yarn.lock @@ -708,10 +708,10 @@ prettier@*: resolved "https://registry.yarnpkg.com/prettier/-/prettier-2.1.1.tgz#d9485dd5e499daa6cb547023b87a6cf51bee37d6" integrity sha512-9bY+5ZWCfqj3ghYBLxApy2zf6m+NJo5GzmLTpr9FsApsfjriNnS2dahWReHMi7qNPhhHl9SYHJs2cHZLgexNIw== -prismjs@^1.21.0: - version "1.21.0" - resolved "https://registry.yarnpkg.com/prismjs/-/prismjs-1.21.0.tgz#36c086ec36b45319ec4218ee164c110f9fc015a3" - integrity sha512-uGdSIu1nk3kej2iZsLyDoJ7e9bnPzIgY0naW/HdknGj61zScaprVEVGHrPoXqI+M9sP0NDnTK2jpkvmldpuqDw== +prismjs@^1.23.0: + version "1.23.0" + resolved "https://registry.yarnpkg.com/prismjs/-/prismjs-1.23.0.tgz#d3b3967f7d72440690497652a9d40ff046067f33" + integrity sha512-c29LVsqOaLbBHuIbsTxaKENh1N2EQBOHaWv7gkHN4dgRbxSREqDnDbtFJYdpPauS4YCplMSNCABQ6Eeor69bAA== optionalDependencies: clipboard "^2.0.0" From 65777555555253421d2ab120582590a69e21062c Mon Sep 17 00:00:00 2001 From: Dmytro Meleshko Date: Fri, 5 Mar 2021 14:59:33 +0200 Subject: [PATCH 40/45] [nvim] switch from coc-python to coc-pyright --- nvim/coc-languages/python.vim | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/nvim/coc-languages/python.vim b/nvim/coc-languages/python.vim index 25d9663..ff6cd12 100644 --- a/nvim/coc-languages/python.vim +++ b/nvim/coc-languages/python.vim @@ -1,8 +1,8 @@ -let g:coc_global_extensions += ['coc-python'] +let g:coc_global_extensions += ['coc-pyright'] let g:coc_filetypes += ['python'] -let g:coc_user_config['pyls.plugins.pycodestyle.ignore'] = ['E501'] +" let g:coc_user_config['pyls.plugins.pycodestyle.ignore'] = ['E501'] +" let g:coc_user_config['python.autocomplete.showAdvancedMembers'] = v:false let g:coc_user_config['python'] = { -\ 'autocomplete': { 'showAdvancedMembers': v:false }, \ 'formatting': { 'provider': 'black' }, \ 'linting': { \ 'pylintEnabled': v:false, From 9253cb6a08f17bd1a2613bfbbe40975429e94dd6 Mon Sep 17 00:00:00 2001 From: Dmytro Meleshko Date: Mon, 5 Apr 2021 02:06:23 +0300 Subject: [PATCH 41/45] [crosscode] add an icon for the Arch mod --- crosscode/btw-i-use-arch-mod/README.md | 1 + crosscode/btw-i-use-arch-mod/ccmod.json | 3 +++ crosscode/btw-i-use-arch-mod/icon24.png | Bin 0 -> 1024 bytes 3 files changed, 4 insertions(+) create mode 100644 crosscode/btw-i-use-arch-mod/README.md create mode 100644 crosscode/btw-i-use-arch-mod/icon24.png diff --git a/crosscode/btw-i-use-arch-mod/README.md b/crosscode/btw-i-use-arch-mod/README.md new file mode 100644 index 0000000..446e038 --- /dev/null +++ b/crosscode/btw-i-use-arch-mod/README.md @@ -0,0 +1 @@ +The file [`icon24.png`] was cropped from the file [`/usr/share/archlinux/web/arch83x31.gif`](file:///usr/share/archlinux/web/arch83x31.gif) of the AUR package [`archlinux-artwork`](https://aur.archlinux.org/packages/archlinux-artwork/) and is distributed under the CC-BY-NC-SA license. diff --git a/crosscode/btw-i-use-arch-mod/ccmod.json b/crosscode/btw-i-use-arch-mod/ccmod.json index b6c3fd8..10f2db2 100644 --- a/crosscode/btw-i-use-arch-mod/ccmod.json +++ b/crosscode/btw-i-use-arch-mod/ccmod.json @@ -2,6 +2,9 @@ "id": "btw-i-use-arch", "title": "btw I use Arch", "description": "A mod for masochists like myself", + "icons": { + "24": "icon24.png" + }, "prestart": "prestart.js", "poststart": "poststart.js" } diff --git a/crosscode/btw-i-use-arch-mod/icon24.png b/crosscode/btw-i-use-arch-mod/icon24.png new file mode 100644 index 0000000000000000000000000000000000000000..9d83ec3070a946b9b9b09708628808df29400f34 GIT binary patch literal 1024 zcmV+b1poVqP)EX>4Tx04R}tkv&MmKp2MK{)i$K2ZM+>WT;LSL`B3& zt5Adrp;lj3p8qu^L^|% zjT0dB3|#3gf29sgf0ABnY0)E~cN@64ZfVLMaJd5vJQ=bnyHbc&FrNqB&*+=7K;JFU zz2^0;d5+TuAWgkW-T()Oz(|3z*L~jI)!w&%YnuK00eWU~s)lpu^8f$=j8IHeMJ9O* z000072nh=d3l9+!6BHE_78o2H92y=W93UejBO@XwD`5TU$h3Z%tTXP+VnMUSd^Y zYglD(TWND;Wo2t?Y+!GBVsU(XdwT#{oCsf^A6thBV4n?Qp%G=G6=rOAA%%z=Z2iH??+mzS8Bn1Pg{hMK5|ove_T zppBxjnW3tqrKYQ^t+ceXzrVkNuFi(A&xNqiiL=q0vcjLY$dI?xmAciKyw{t)*rB@1 zrM}Rg!P=w4+o{9Vs>a%^$lS2Y-m=Z$w$S6k!otkV%+%D>*x1;>*5}6B=*{2k)8p>l z>GJ32=j`n4;_UP3@%HZY`1AAg^7s1n`1}6;{+^?uGynhq0d!JMQvg8b*k%9#010qN zS#tmY3ljhU3ljkVnw%H_003-BL_t(2&z+D<4uBvGL^+m86B2Yst!ME5r;uW*p-vNZ zHo$vK_@wkAHQ+Nx1r{tg5G*Z7DBr#`L>N~3epFG&?OxujvJ}!3|F}$+f#;Jvg%NM= uwKI{RQB0AzD&RnyxJMD~eE>g7=|>LGW+ldV&yoB90000 Date: Mon, 26 Apr 2021 10:07:31 +0300 Subject: [PATCH 42/45] [nvim] use Yapf with a modified config for formatting --- colorschemes/_theme.py | 3 +-- colorschemes/iterm.itermcolors.py | 13 +++++-------- colorschemes/prismjs-theme.css.py | 4 +--- colorschemes/setvtrgb.txt.py | 9 +-------- colorschemes/variables.css.py | 1 + colorschemes/vim.vim.py | 1 + .../vscode-colorCustomizations.json.py | 8 ++------ colorschemes/xfce4-terminal.theme.py | 1 + colorschemes/zsh.zsh.py | 1 - nvim/coc-languages/python.vim | 18 +++++++++++++++--- python/yapf.ini | 8 ++++++++ script-resources/common_script_utils.py | 9 ++------- script-resources/welcome/colors.py | 1 + script-resources/welcome/main.py | 1 + script-resources/welcome/system_info.py | 18 +++++++----------- 15 files changed, 47 insertions(+), 49 deletions(-) create mode 100644 python/yapf.ini diff --git a/colorschemes/_theme.py b/colorschemes/_theme.py index a467d1e..1695bdc 100644 --- a/colorschemes/_theme.py +++ b/colorschemes/_theme.py @@ -32,8 +32,7 @@ selection_bg = base16_colors[0x2] selection_fg = fg ansi_colors = [ - base16_colors[int(i, 16)] - for i in "0 8 B A D E C 5 3 8 B A D E C 7 9 F 1 2 4 6".split() + base16_colors[int(i, 16)] for i in "0 8 B A D E C 5 3 8 B A D E C 7 9 F 1 2 4 6".split() ] link_color = ansi_colors[0xC] diff --git a/colorschemes/iterm.itermcolors.py b/colorschemes/iterm.itermcolors.py index 5594ff5..622d3ec 100755 --- a/colorschemes/iterm.itermcolors.py +++ b/colorschemes/iterm.itermcolors.py @@ -2,6 +2,7 @@ import _theme as theme + print( """\ @@ -13,7 +14,7 @@ print( def print_color(key_name, color): - r, g, b = [float(int(color[2 * i + 1 : 2 * i + 3], 16)) / 255 for i in range(3)] + r, g, b = [float(int(color[2 * i + 1:2 * i + 3], 16)) / 255 for i in range(3)] print( """\ {} Color @@ -27,9 +28,7 @@ def print_color(key_name, color): Blue Component {} \ -""".format( - key_name, r, g, b - ) +""".format(key_name, r, g, b) ) @@ -44,9 +43,7 @@ for index, color in enumerate(theme.ansi_colors[:16]): print_color("Ansi " + str(index), color) print_color("Link", theme.link_color) -print( - """\ +print("""\ \ -""" -) +""") diff --git a/colorschemes/prismjs-theme.css.py b/colorschemes/prismjs-theme.css.py index 42b62b8..ba5cdf5 100755 --- a/colorschemes/prismjs-theme.css.py +++ b/colorschemes/prismjs-theme.css.py @@ -7,8 +7,6 @@ with open(os.path.join(os.path.dirname(__file__), "prismjs-theme-src.css")) as f css_src = f.read() for var_name, color in theme.css_variables.items(): - css_src = css_src.replace( - "var(--{}{})".format(theme.css_variables_prefix, var_name), color - ) + css_src = css_src.replace("var(--{}{})".format(theme.css_variables_prefix, var_name), color) print(css_src) diff --git a/colorschemes/setvtrgb.txt.py b/colorschemes/setvtrgb.txt.py index 8a8f117..99432e3 100755 --- a/colorschemes/setvtrgb.txt.py +++ b/colorschemes/setvtrgb.txt.py @@ -8,11 +8,4 @@ import _theme as theme # 0,0,0,0,170,170,170,170,85,85,85,85,255,255,255,255 for i in range(3): - print( - ",".join( - [ - str(int(color[2 * i + 1 : 2 * i + 3], 16)) - for color in theme.ansi_colors[:16] - ] - ) - ) + print(",".join([str(int(color[2 * i + 1:2 * i + 3], 16)) for color in theme.ansi_colors[:16]])) diff --git a/colorschemes/variables.css.py b/colorschemes/variables.css.py index 64c4609..4ed4c1c 100755 --- a/colorschemes/variables.css.py +++ b/colorschemes/variables.css.py @@ -2,6 +2,7 @@ import _theme as theme + print(":root {") for var_name, color in theme.css_variables.items(): print(" --{}{}: {};".format(theme.css_variables_prefix, var_name, color)) diff --git a/colorschemes/vim.vim.py b/colorschemes/vim.vim.py index bba2493..0f138d4 100755 --- a/colorschemes/vim.vim.py +++ b/colorschemes/vim.vim.py @@ -2,6 +2,7 @@ import _theme as theme + print("let dotfiles_colorscheme_name = '{}'".format(theme.name)) print("let dotfiles_colorscheme_base16_name = '{}'".format(theme.base16_name)) print("let dotfiles_colorscheme_base16_colors = [") diff --git a/colorschemes/vscode-colorCustomizations.json.py b/colorschemes/vscode-colorCustomizations.json.py index d139834..8832f92 100755 --- a/colorschemes/vscode-colorCustomizations.json.py +++ b/colorschemes/vscode-colorCustomizations.json.py @@ -25,11 +25,7 @@ colors = { for color_brightness in [False, True]: for color_index, color_name in enumerate(ANSI_COLOR_NAMES): - color = theme.ansi_colors[ - color_index + int(color_brightness) * len(ANSI_COLOR_NAMES) - ] - colors[ - "terminal.ansi" + ("Bright" if color_brightness else "") + color_name - ] = color + color = theme.ansi_colors[color_index + int(color_brightness) * len(ANSI_COLOR_NAMES)] + colors["terminal.ansi" + ("Bright" if color_brightness else "") + color_name] = color print(json.dumps(colors, ensure_ascii=False, indent=2)) diff --git a/colorschemes/xfce4-terminal.theme.py b/colorschemes/xfce4-terminal.theme.py index 5775160..3b5f71e 100755 --- a/colorschemes/xfce4-terminal.theme.py +++ b/colorschemes/xfce4-terminal.theme.py @@ -2,6 +2,7 @@ import _theme as theme + print("[Scheme]") print("Name=dmitmel's dotfiles colorscheme") print("ColorForeground={}".format(theme.fg)) diff --git a/colorschemes/zsh.zsh.py b/colorschemes/zsh.zsh.py index 96c73af..bc5c031 100755 --- a/colorschemes/zsh.zsh.py +++ b/colorschemes/zsh.zsh.py @@ -2,7 +2,6 @@ import _theme as theme - for attr in [ "bg", "fg", diff --git a/nvim/coc-languages/python.vim b/nvim/coc-languages/python.vim index ff6cd12..a23c440 100644 --- a/nvim/coc-languages/python.vim +++ b/nvim/coc-languages/python.vim @@ -1,12 +1,24 @@ let g:coc_global_extensions += ['coc-pyright'] let g:coc_filetypes += ['python'] -" let g:coc_user_config['pyls.plugins.pycodestyle.ignore'] = ['E501'] + +let s:ignored_errors = [] +" Indent is not a multiple of 4 +let s:ignored_errors += ['E111'] +" Indent is not a multiple of 4 for comments +let s:ignored_errors += ['E114'] +" Line too long +let s:ignored_errors += ['E501'] + +" let g:coc_user_config['pyls.plugins.pycodestyle.ignore'] = s:ignored_errors " let g:coc_user_config['python.autocomplete.showAdvancedMembers'] = v:false let g:coc_user_config['python'] = { -\ 'formatting': { 'provider': 'black' }, +\ 'formatting': { +\ 'provider': 'yapf', +\ 'yapfArgs': ['--style=' . simplify(g:nvim_dotfiles_dir.'/../python/yapf.ini')] +\ }, \ 'linting': { \ 'pylintEnabled': v:false, \ 'flake8Enabled': v:true, -\ 'flake8Args': ['--ignore', 'E501'], +\ 'flake8Args': ['--ignore=' . join(s:ignored_errors, ',')], \ }, \ } diff --git a/python/yapf.ini b/python/yapf.ini new file mode 100644 index 0000000..fca5143 --- /dev/null +++ b/python/yapf.ini @@ -0,0 +1,8 @@ +[style] +based_on_style = google +column_limit = 99 +indent_width = 4 +blank_lines_between_top_level_imports_and_variables = 2 +dedent_closing_brackets = true +coalesce_brackets = true +spaces_around_power_operator = true diff --git a/script-resources/common_script_utils.py b/script-resources/common_script_utils.py index fa23b02..981a488 100644 --- a/script-resources/common_script_utils.py +++ b/script-resources/common_script_utils.py @@ -4,7 +4,6 @@ import subprocess from pathlib import Path from typing import Iterable, NoReturn - if os.name == "posix": DOTFILES_CONFIG_DIR: Path = Path.home() / ".config" / "dotfiles" DOTFILES_CACHE_DIR: Path = Path.home() / ".cache" / "dotfiles" @@ -14,9 +13,7 @@ def platform_not_supported_error() -> NoReturn: raise Exception("platform '{}' is not supported!".format(sys.platform)) -def run_chooser( - choices: Iterable[str], prompt: str = None, async_read: bool = False -) -> int: +def run_chooser(choices: Iterable[str], prompt: str = None, async_read: bool = False) -> int: supports_result_index = True if os.isatty(sys.stderr.fileno()): process_args = [ @@ -38,9 +35,7 @@ def run_chooser( else: platform_not_supported_error() - chooser_process = subprocess.Popen( - process_args, stdin=subprocess.PIPE, stdout=subprocess.PIPE - ) + chooser_process = subprocess.Popen(process_args, stdin=subprocess.PIPE, stdout=subprocess.PIPE) with chooser_process.stdin as pipe: for index, choice in enumerate(choices): diff --git a/script-resources/welcome/colors.py b/script-resources/welcome/colors.py index b32d782..cb05872 100644 --- a/script-resources/welcome/colors.py +++ b/script-resources/welcome/colors.py @@ -1,5 +1,6 @@ from colorama import Fore, Style, ansi + COLORS = [ansi.code_to_chars(30 + color_index) for color_index in range(0, 8)] diff --git a/script-resources/welcome/main.py b/script-resources/welcome/main.py index 40e9c42..7f0c9ee 100755 --- a/script-resources/welcome/main.py +++ b/script-resources/welcome/main.py @@ -5,6 +5,7 @@ import re from colors import COLORS, Style from system_info import get_system_info + print("") logo_lines, info_lines = get_system_info() diff --git a/script-resources/welcome/system_info.py b/script-resources/welcome/system_info.py index d840055..df4b81c 100644 --- a/script-resources/welcome/system_info.py +++ b/script-resources/welcome/system_info.py @@ -94,9 +94,7 @@ def _get_users(): terminals = users[name] colored_name = bright_colored(name, Fore.BLUE) - colored_terminals = [ - colored(str(term), Style.DIM, Fore.WHITE) for term in terminals - ] + colored_terminals = [colored(str(term), Style.DIM, Fore.WHITE) for term in terminals] terminals_str = ", ".join(colored_terminals) if len(colored_terminals) > 1: @@ -140,14 +138,12 @@ def _get_disks(): continue usage = psutil.disk_usage(disk.mountpoint) - result.append( - ( - disk.mountpoint, - humanize_bytes(usage.used), - humanize_bytes(usage.total), - colorize_percent(usage.percent, warning=70, critical=85), - ) - ) + result.append(( + disk.mountpoint, + humanize_bytes(usage.used), + humanize_bytes(usage.total), + colorize_percent(usage.percent, warning=70, critical=85), + )) return result From dbd76019c896cc8efd52f87d353ea1f5e7bb3273 Mon Sep 17 00:00:00 2001 From: Dmytro Meleshko Date: Mon, 26 Apr 2021 10:11:02 +0300 Subject: [PATCH 43/45] at long last, reformat all Python code with 2 space indents --- colorschemes/_theme.py | 48 ++-- colorschemes/iterm.itermcolors.py | 12 +- colorschemes/kitty.conf.py | 4 +- colorschemes/prismjs-theme.css.py | 4 +- colorschemes/setvtrgb.txt.py | 2 +- colorschemes/termux.properties.py | 4 +- colorschemes/variables.css.py | 2 +- colorschemes/vim.vim.py | 6 +- .../vscode-colorCustomizations.json.py | 32 +-- colorschemes/zsh.zsh.py | 20 +- nvim/coc-languages/python.vim | 2 + python/yapf.ini | 3 +- script-resources/common_script_utils.py | 136 ++++----- script-resources/factorio/property_tree.py | 74 ++--- script-resources/pycalc_startup.py | 38 +-- script-resources/welcome/colors.py | 14 +- script-resources/welcome/humanize.py | 48 ++-- script-resources/welcome/main.py | 26 +- script-resources/welcome/system_info.py | 258 +++++++++--------- 19 files changed, 367 insertions(+), 366 deletions(-) diff --git a/colorschemes/_theme.py b/colorschemes/_theme.py index 1695bdc..644f440 100644 --- a/colorschemes/_theme.py +++ b/colorschemes/_theme.py @@ -4,22 +4,22 @@ base16_name = "eighties" name = "base16-" + base16_name base16_colors = [ - "#2d2d2d", # 0 - "#393939", # 1 - "#515151", # 2 - "#747369", # 3 - "#a09f93", # 4 - "#d3d0c8", # 5 - "#e8e6df", # 6 - "#f2f0ec", # 7 - "#f2777a", # 8 - "#f99157", # 9 - "#ffcc66", # a - "#99cc99", # b - "#66cccc", # c - "#6699cc", # d - "#cc99cc", # e - "#d27b53", # f + "#2d2d2d", # 0 + "#393939", # 1 + "#515151", # 2 + "#747369", # 3 + "#a09f93", # 4 + "#d3d0c8", # 5 + "#e8e6df", # 6 + "#f2f0ec", # 7 + "#f2777a", # 8 + "#f99157", # 9 + "#ffcc66", # a + "#99cc99", # b + "#66cccc", # c + "#6699cc", # d + "#cc99cc", # e + "#d27b53", # f ] bg = base16_colors[0x0] @@ -32,18 +32,18 @@ selection_bg = base16_colors[0x2] selection_fg = fg ansi_colors = [ - base16_colors[int(i, 16)] for i in "0 8 B A D E C 5 3 8 B A D E C 7 9 F 1 2 4 6".split() + base16_colors[int(i, 16)] for i in "0 8 B A D E C 5 3 8 B A D E C 7 9 F 1 2 4 6".split() ] link_color = ansi_colors[0xC] css_variables_prefix = "dotfiles-colorscheme-" css_variables = { - "bg": bg, - "fg": fg, - "selection-bg": selection_bg, - "selection-fg": selection_fg, - "cursor-bg": cursor_bg, - "cursor-fg": cursor_fg, - **{"base-{:02X}".format(index): color for index, color in enumerate(base16_colors)}, + "bg": bg, + "fg": fg, + "selection-bg": selection_bg, + "selection-fg": selection_fg, + "cursor-bg": cursor_bg, + "cursor-fg": cursor_fg, + **{"base-{:02X}".format(index): color for index, color in enumerate(base16_colors)}, } diff --git a/colorschemes/iterm.itermcolors.py b/colorschemes/iterm.itermcolors.py index 622d3ec..8cd59e5 100755 --- a/colorschemes/iterm.itermcolors.py +++ b/colorschemes/iterm.itermcolors.py @@ -4,7 +4,7 @@ import _theme as theme print( - """\ + """\ @@ -14,9 +14,9 @@ print( def print_color(key_name, color): - r, g, b = [float(int(color[2 * i + 1:2 * i + 3], 16)) / 255 for i in range(3)] - print( - """\ + r, g, b = [float(int(color[2 * i + 1:2 * i + 3], 16)) / 255 for i in range(3)] + print( + """\ {} Color Color Space @@ -29,7 +29,7 @@ def print_color(key_name, color): {} \ """.format(key_name, r, g, b) - ) + ) print_color("Background", theme.bg) @@ -40,7 +40,7 @@ print_color("Cursor Text", theme.cursor_fg) print_color("Selection Color", theme.selection_bg) print_color("Selected Text Color", theme.selection_fg) for index, color in enumerate(theme.ansi_colors[:16]): - print_color("Ansi " + str(index), color) + print_color("Ansi " + str(index), color) print_color("Link", theme.link_color) print("""\ diff --git a/colorschemes/kitty.conf.py b/colorschemes/kitty.conf.py index a82df90..81544aa 100755 --- a/colorschemes/kitty.conf.py +++ b/colorschemes/kitty.conf.py @@ -4,7 +4,7 @@ import _theme as theme def print_color(key_name, color): - print("{} {}".format(key_name, color)) + print("{} {}".format(key_name, color)) print_color("background", theme.bg) @@ -14,7 +14,7 @@ print_color("cursor_text_color", theme.cursor_fg) print_color("selection_background", theme.selection_bg) print_color("selection_foreground", theme.selection_fg) for index, color in enumerate(theme.ansi_colors[:16]): - print_color("color" + str(index), color) + print_color("color" + str(index), color) print_color("url_color", theme.link_color) print_color("active_border_color", theme.ansi_colors[2]) diff --git a/colorschemes/prismjs-theme.css.py b/colorschemes/prismjs-theme.css.py index ba5cdf5..924f81d 100755 --- a/colorschemes/prismjs-theme.css.py +++ b/colorschemes/prismjs-theme.css.py @@ -4,9 +4,9 @@ import _theme as theme import os with open(os.path.join(os.path.dirname(__file__), "prismjs-theme-src.css")) as f: - css_src = f.read() + css_src = f.read() for var_name, color in theme.css_variables.items(): - css_src = css_src.replace("var(--{}{})".format(theme.css_variables_prefix, var_name), color) + css_src = css_src.replace("var(--{}{})".format(theme.css_variables_prefix, var_name), color) print(css_src) diff --git a/colorschemes/setvtrgb.txt.py b/colorschemes/setvtrgb.txt.py index 99432e3..9dfb27f 100755 --- a/colorschemes/setvtrgb.txt.py +++ b/colorschemes/setvtrgb.txt.py @@ -8,4 +8,4 @@ import _theme as theme # 0,0,0,0,170,170,170,170,85,85,85,85,255,255,255,255 for i in range(3): - print(",".join([str(int(color[2 * i + 1:2 * i + 3], 16)) for color in theme.ansi_colors[:16]])) + print(",".join([str(int(color[2 * i + 1:2 * i + 3], 16)) for color in theme.ansi_colors[:16]])) diff --git a/colorschemes/termux.properties.py b/colorschemes/termux.properties.py index 164df7a..e6843ff 100755 --- a/colorschemes/termux.properties.py +++ b/colorschemes/termux.properties.py @@ -4,11 +4,11 @@ import _theme as theme def print_color(key_name, color): - print("{}={}".format(key_name, color)) + print("{}={}".format(key_name, color)) print_color("background", theme.bg) print_color("foreground", theme.fg) print_color("cursor", theme.cursor_bg) for index, color in enumerate(theme.ansi_colors[:16]): - print_color("color" + str(index), color) + print_color("color" + str(index), color) diff --git a/colorschemes/variables.css.py b/colorschemes/variables.css.py index 4ed4c1c..2338a6f 100755 --- a/colorschemes/variables.css.py +++ b/colorschemes/variables.css.py @@ -5,5 +5,5 @@ import _theme as theme print(":root {") for var_name, color in theme.css_variables.items(): - print(" --{}{}: {};".format(theme.css_variables_prefix, var_name, color)) + print(" --{}{}: {};".format(theme.css_variables_prefix, var_name, color)) print("}") diff --git a/colorschemes/vim.vim.py b/colorschemes/vim.vim.py index 0f138d4..38dfed0 100755 --- a/colorschemes/vim.vim.py +++ b/colorschemes/vim.vim.py @@ -8,15 +8,15 @@ print("let dotfiles_colorscheme_base16_name = '{}'".format(theme.base16_name)) print("let dotfiles_colorscheme_base16_colors = [") gui_to_cterm_mapping = [0, 18, 19, 8, 20, 7, 21, 15, 1, 16, 3, 2, 6, 4, 5, 17] for colors_pair in zip(theme.base16_colors[:16], gui_to_cterm_mapping): - print("\\ {{'gui': '{}', 'cterm': '{:>02}'}},".format(*colors_pair)) + print("\\ {{'gui': '{}', 'cterm': '{:>02}'}},".format(*colors_pair)) print("\\ ]") def print_terminal_color(key_name, color): - print("let terminal_color_{} = '{}'".format(key_name, color)) + print("let terminal_color_{} = '{}'".format(key_name, color)) print_terminal_color("background", theme.bg) print_terminal_color("foreground", theme.fg) for index, color in enumerate(theme.ansi_colors[:16]): - print_terminal_color(str(index), color) + print_terminal_color(str(index), color) diff --git a/colorschemes/vscode-colorCustomizations.json.py b/colorschemes/vscode-colorCustomizations.json.py index 8832f92..ed1b1dc 100755 --- a/colorschemes/vscode-colorCustomizations.json.py +++ b/colorschemes/vscode-colorCustomizations.json.py @@ -5,27 +5,27 @@ import json ANSI_COLOR_NAMES = [ - "Black", - "Red", - "Green", - "Yellow", - "Blue", - "Magenta", - "Cyan", - "White", + "Black", + "Red", + "Green", + "Yellow", + "Blue", + "Magenta", + "Cyan", + "White", ] colors = { - "terminal.background": theme.bg, - "terminal.foreground": theme.fg, - "terminal.selectionBackground": theme.selection_bg, - "terminalCursor.background": theme.cursor_fg, - "terminalCursor.foreground": theme.cursor_bg, + "terminal.background": theme.bg, + "terminal.foreground": theme.fg, + "terminal.selectionBackground": theme.selection_bg, + "terminalCursor.background": theme.cursor_fg, + "terminalCursor.foreground": theme.cursor_bg, } for color_brightness in [False, True]: - for color_index, color_name in enumerate(ANSI_COLOR_NAMES): - color = theme.ansi_colors[color_index + int(color_brightness) * len(ANSI_COLOR_NAMES)] - colors["terminal.ansi" + ("Bright" if color_brightness else "") + color_name] = color + for color_index, color_name in enumerate(ANSI_COLOR_NAMES): + color = theme.ansi_colors[color_index + int(color_brightness) * len(ANSI_COLOR_NAMES)] + colors["terminal.ansi" + ("Bright" if color_brightness else "") + color_name] = color print(json.dumps(colors, ensure_ascii=False, indent=2)) diff --git a/colorschemes/zsh.zsh.py b/colorschemes/zsh.zsh.py index bc5c031..5a32295 100755 --- a/colorschemes/zsh.zsh.py +++ b/colorschemes/zsh.zsh.py @@ -3,17 +3,17 @@ import _theme as theme for attr in [ - "bg", - "fg", - "cursor_bg", - "cursor_fg", - "selection_bg", - "selection_fg", - "link_color", + "bg", + "fg", + "cursor_bg", + "cursor_fg", + "selection_bg", + "selection_fg", + "link_color", ]: - color = getattr(theme, attr) - print("colorscheme_{}={}".format(attr, color[1:])) + color = getattr(theme, attr) + print("colorscheme_{}={}".format(attr, color[1:])) print("colorscheme_ansi_colors=(") for color in theme.ansi_colors: - print(" {}".format(color[1:])) + print(" {}".format(color[1:])) print(")") diff --git a/nvim/coc-languages/python.vim b/nvim/coc-languages/python.vim index a23c440..1f0037d 100644 --- a/nvim/coc-languages/python.vim +++ b/nvim/coc-languages/python.vim @@ -6,6 +6,8 @@ let s:ignored_errors = [] let s:ignored_errors += ['E111'] " Indent is not a multiple of 4 for comments let s:ignored_errors += ['E114'] +" Indent for continuation lines is smaller than expected +let s:ignored_errors += ['E121'] " Line too long let s:ignored_errors += ['E501'] diff --git a/python/yapf.ini b/python/yapf.ini index fca5143..e4ceea7 100644 --- a/python/yapf.ini +++ b/python/yapf.ini @@ -1,7 +1,8 @@ [style] based_on_style = google column_limit = 99 -indent_width = 4 +indent_width = 2 +continuation_indent_width = 2 blank_lines_between_top_level_imports_and_variables = 2 dedent_closing_brackets = true coalesce_brackets = true diff --git a/script-resources/common_script_utils.py b/script-resources/common_script_utils.py index 981a488..239eb11 100644 --- a/script-resources/common_script_utils.py +++ b/script-resources/common_script_utils.py @@ -5,89 +5,89 @@ from pathlib import Path from typing import Iterable, NoReturn if os.name == "posix": - DOTFILES_CONFIG_DIR: Path = Path.home() / ".config" / "dotfiles" - DOTFILES_CACHE_DIR: Path = Path.home() / ".cache" / "dotfiles" + DOTFILES_CONFIG_DIR: Path = Path.home() / ".config" / "dotfiles" + DOTFILES_CACHE_DIR: Path = Path.home() / ".cache" / "dotfiles" def platform_not_supported_error() -> NoReturn: - raise Exception("platform '{}' is not supported!".format(sys.platform)) + raise Exception("platform '{}' is not supported!".format(sys.platform)) def run_chooser(choices: Iterable[str], prompt: str = None, async_read: bool = False) -> int: - supports_result_index = True - if os.isatty(sys.stderr.fileno()): - process_args = [ - "fzf", - "--with-nth=2..", - "--height=50%", - "--reverse", - "--tiebreak=index", - ] - supports_result_index = False - elif sys.platform == "darwin": - process_args = ["choose", "-i"] - elif os.name == "posix": - process_args = ["rofi", "-dmenu", "-i", "-format", "i"] - if prompt is not None: - process_args += ["-p", prompt] - if async_read: - process_args += ["-async-pre-read", "0"] - else: - platform_not_supported_error() + supports_result_index = True + if os.isatty(sys.stderr.fileno()): + process_args = [ + "fzf", + "--with-nth=2..", + "--height=50%", + "--reverse", + "--tiebreak=index", + ] + supports_result_index = False + elif sys.platform == "darwin": + process_args = ["choose", "-i"] + elif os.name == "posix": + process_args = ["rofi", "-dmenu", "-i", "-format", "i"] + if prompt is not None: + process_args += ["-p", prompt] + if async_read: + process_args += ["-async-pre-read", "0"] + else: + platform_not_supported_error() - chooser_process = subprocess.Popen(process_args, stdin=subprocess.PIPE, stdout=subprocess.PIPE) + chooser_process = subprocess.Popen(process_args, stdin=subprocess.PIPE, stdout=subprocess.PIPE) - with chooser_process.stdin as pipe: - for index, choice in enumerate(choices): - assert "\n" not in choice - if not supports_result_index: - pipe.write(str(index).encode()) - pipe.write(b" ") - pipe.write(choice.encode()) - pipe.write(b"\n") + with chooser_process.stdin as pipe: + for index, choice in enumerate(choices): + assert "\n" not in choice + if not supports_result_index: + pipe.write(str(index).encode()) + pipe.write(b" ") + pipe.write(choice.encode()) + pipe.write(b"\n") - exit_code: int = chooser_process.wait() - if exit_code != 0: - raise Exception("chooser process failed with exit code {}".format(exit_code)) + exit_code: int = chooser_process.wait() + if exit_code != 0: + raise Exception("chooser process failed with exit code {}".format(exit_code)) - chosen_index = int(chooser_process.stdout.read().strip().split()[0]) - return chosen_index + chosen_index = int(chooser_process.stdout.read().strip().split()[0]) + return chosen_index def send_notification(title: str, message: str, url: str = None) -> None: - if sys.platform == "darwin": - process_args = [ - "terminal-notifier", - "-title", - title, - "-message", - message, - "-open", - ] - if url is not None: - process_args += [url] - elif os.name == "posix": - process_args = [ - "notify-send", - "--icon=utilities-terminal", - "--expire-time=3000", - title, - message, - ] - else: - platform_not_supported_error() + if sys.platform == "darwin": + process_args = [ + "terminal-notifier", + "-title", + title, + "-message", + message, + "-open", + ] + if url is not None: + process_args += [url] + elif os.name == "posix": + process_args = [ + "notify-send", + "--icon=utilities-terminal", + "--expire-time=3000", + title, + message, + ] + else: + platform_not_supported_error() - subprocess.run(process_args, check=True) + subprocess.run(process_args, check=True) def set_clipboard(text: str) -> None: - # TODO: somehow merge program selection with the logic in `zsh/functions.zsh` - if sys.platform == "darwin": - process_args = ["pbcopy"] - elif os.name == "posix": - process_args = ["xsel", "--clipboard", "--input"] - # process_args = ["xclip", "-in", "-selection", "clipboard"] - else: - platform_not_supported_error() + # TODO: somehow merge program selection with the logic in `zsh/functions.zsh` + if sys.platform == "darwin": + process_args = ["pbcopy"] + elif os.name == "posix": + process_args = ["xsel", "--clipboard", "--input"] + # process_args = ["xclip", "-in", "-selection", "clipboard"] + else: + platform_not_supported_error() - subprocess.run(process_args, input=text.encode(), check=True) + subprocess.run(process_args, input=text.encode(), check=True) diff --git a/script-resources/factorio/property_tree.py b/script-resources/factorio/property_tree.py index 9275ff4..24f921c 100644 --- a/script-resources/factorio/property_tree.py +++ b/script-resources/factorio/property_tree.py @@ -9,58 +9,58 @@ from typing import Any, IO def read_bool(buf: IO[bytes]) -> bool: - return buf.read(1)[0] == 1 + return buf.read(1)[0] == 1 def read_number(buf: IO[bytes]) -> float: - return struct.unpack(" int: - return struct.unpack(" str: - is_empty = read_bool(buf) - if is_empty: - return "" - len_ = buf.read(1)[0] - if len_ == 0xFF: - len_ = _read_length(buf) - return buf.read(len_).decode("utf8") + is_empty = read_bool(buf) + if is_empty: + return "" + len_ = buf.read(1)[0] + if len_ == 0xFF: + len_ = _read_length(buf) + return buf.read(len_).decode("utf8") def read_dictionary(buf: IO[bytes]) -> dict[str, Any]: - len_ = _read_length(buf) - value: dict[str, Any] = {} - for _ in range(len_): - key = read_string(buf) - value[key] = read(buf) - return value + len_ = _read_length(buf) + value: dict[str, Any] = {} + for _ in range(len_): + key = read_string(buf) + value[key] = read(buf) + return value def read_list(buf: IO[bytes]) -> list[Any]: - len_ = _read_length(buf) - value: list[Any] = [] - for _ in range(len_): - read_string(buf) - value.append(read(buf)) - return value + len_ = _read_length(buf) + value: list[Any] = [] + for _ in range(len_): + read_string(buf) + value.append(read(buf)) + return value def read(buf: IO[bytes]) -> Any: - type_, _any_type_flag = buf.read(2) - if type_ == 0: - return None - elif type_ == 1: - return read_bool(buf) - elif type_ == 2: - return read_number(buf) - elif type_ == 3: - return read_string(buf) - elif type_ == 4: - return read_list(buf) - elif type_ == 5: - return read_dictionary(buf) - else: - raise Exception("unknown property tree type 0x{:02x}".format(type_)) + type_, _any_type_flag = buf.read(2) + if type_ == 0: + return None + elif type_ == 1: + return read_bool(buf) + elif type_ == 2: + return read_number(buf) + elif type_ == 3: + return read_string(buf) + elif type_ == 4: + return read_list(buf) + elif type_ == 5: + return read_dictionary(buf) + else: + raise Exception("unknown property tree type 0x{:02x}".format(type_)) diff --git a/script-resources/pycalc_startup.py b/script-resources/pycalc_startup.py index 6aab338..1ffb1b2 100644 --- a/script-resources/pycalc_startup.py +++ b/script-resources/pycalc_startup.py @@ -3,29 +3,29 @@ from fractions import Fraction def factors(n): - result = set() - for i in range(1, int(sqrt(n)) + 1): - if n % i == 0: - result.add(i) - result.add(n // i) - return result + result = set() + for i in range(1, int(sqrt(n)) + 1): + if n % i == 0: + result.add(i) + result.add(n // i) + return result def solve_quadratic(a, b, c): - if a == 0: - raise Exception("not a quadratic equation") + if a == 0: + raise Exception("not a quadratic equation") + else: + d = b ** 2 - 4 * a * c + print("D = " + str(d)) + if d < 0: + print("no solutions") + elif d > 0: + sd = sqrt(d) + print("sqrt(D) = " + str(sd)) + print("x1 = " + str((-b + sd) / (2 * a))) + print("x2 = " + str((-b - sd) / (2 * a))) else: - d = b ** 2 - 4 * a * c - print("D = " + str(d)) - if d < 0: - print("no solutions") - elif d > 0: - sd = sqrt(d) - print("sqrt(D) = " + str(sd)) - print("x1 = " + str((-b + sd) / (2 * a))) - print("x2 = " + str((-b - sd) / (2 * a))) - else: - print("x = " + str(-b / (2 * a))) + print("x = " + str(-b / (2 * a))) print("loaded Python calculator") diff --git a/script-resources/welcome/colors.py b/script-resources/welcome/colors.py index cb05872..a835612 100644 --- a/script-resources/welcome/colors.py +++ b/script-resources/welcome/colors.py @@ -5,18 +5,18 @@ COLORS = [ansi.code_to_chars(30 + color_index) for color_index in range(0, 8)] def colored(string, *colors): - return "".join(colors + (string, Style.RESET_ALL)) + return "".join(colors + (string, Style.RESET_ALL)) def bright_colored(string, *colors): - return "".join(colors + (Style.BRIGHT, string, Style.RESET_ALL)) + return "".join(colors + (Style.BRIGHT, string, Style.RESET_ALL)) def colorize_percent(percent, warning, critical, inverse=False): - COLORS = [Fore.GREEN, Fore.YELLOW, Fore.RED] + COLORS = [Fore.GREEN, Fore.YELLOW, Fore.RED] - color_index = 0 if percent < warning else 1 if percent < critical else 2 - if inverse: - color_index = 2 - color_index + color_index = 0 if percent < warning else 1 if percent < critical else 2 + if inverse: + color_index = 2 - color_index - return colored("%.2f%%" % percent, COLORS[color_index]) + return colored("%.2f%%" % percent, COLORS[color_index]) diff --git a/script-resources/welcome/humanize.py b/script-resources/welcome/humanize.py index ac7c7fb..9631a9c 100644 --- a/script-resources/welcome/humanize.py +++ b/script-resources/welcome/humanize.py @@ -1,34 +1,34 @@ def humanize_timedelta(timedelta): - result = [] + result = [] - days = timedelta.days - mm, ss = divmod(timedelta.seconds, 60) - hh, mm = divmod(mm, 60) + days = timedelta.days + mm, ss = divmod(timedelta.seconds, 60) + hh, mm = divmod(mm, 60) - def plural(n): - return n, "s" if abs(n) != 1 else "" + def plural(n): + return n, "s" if abs(n) != 1 else "" - if days > 0: - result.append("%d day%s" % plural(days)) - if hh > 0 or result: - result.append("%d hour%s" % plural(hh)) - if mm > 0 or result: - result.append("%d min%s" % plural(mm)) - if len(result) <= 1: - result.append("%d sec%s" % plural(ss)) + if days > 0: + result.append("%d day%s" % plural(days)) + if hh > 0 or result: + result.append("%d hour%s" % plural(hh)) + if mm > 0 or result: + result.append("%d min%s" % plural(mm)) + if len(result) <= 1: + result.append("%d sec%s" % plural(ss)) - return ", ".join(result) + return ", ".join(result) def humanize_bytes(bytes): - units = ["B", "kB", "MB", "GB"] + units = ["B", "kB", "MB", "GB"] - factor = 1 - unit = "" - for unit in units: - next_factor = factor << 10 - if bytes < next_factor: - break - factor = next_factor + factor = 1 + unit = "" + for unit in units: + next_factor = factor << 10 + if bytes < next_factor: + break + factor = next_factor - return "%.2f %s" % (float(bytes) / factor, unit) + return "%.2f %s" % (float(bytes) / factor, unit) diff --git a/script-resources/welcome/main.py b/script-resources/welcome/main.py index 7f0c9ee..6eb37f7 100755 --- a/script-resources/welcome/main.py +++ b/script-resources/welcome/main.py @@ -13,24 +13,24 @@ logo_line_widths = [len(re.sub(r"{\d}", "", line)) for line in logo_lines] logo_width = max(logo_line_widths) for line_index in range(0, max(len(logo_lines), len(info_lines))): - line = "" + line = "" - logo_line_width = 0 + logo_line_width = 0 - if line_index < len(logo_lines): - logo_line = logo_lines[line_index] - logo_line_width = logo_line_widths[line_index] + if line_index < len(logo_lines): + logo_line = logo_lines[line_index] + logo_line_width = logo_line_widths[line_index] - line += Style.BRIGHT - line += logo_line.format(*COLORS) - line += Style.RESET_ALL + line += Style.BRIGHT + line += logo_line.format(*COLORS) + line += Style.RESET_ALL - line += " " * (logo_width - logo_line_width + 3) + line += " " * (logo_width - logo_line_width + 3) - if line_index < len(info_lines): - info_line = info_lines[line_index] - line += info_line + if line_index < len(info_lines): + info_line = info_lines[line_index] + line += info_line - print(line) + print(line) print("") diff --git a/script-resources/welcome/system_info.py b/script-resources/welcome/system_info.py index df4b81c..9d72ded 100644 --- a/script-resources/welcome/system_info.py +++ b/script-resources/welcome/system_info.py @@ -11,202 +11,200 @@ from humanize import humanize_bytes, humanize_timedelta def get_system_info(): - info_lines = [] + info_lines = [] - def info(name, value, *format_args): - line = bright_colored(name + ":", Fore.YELLOW) + " " + value - if format_args: - line = line % format_args - info_lines.append(line) + def info(name, value, *format_args): + line = bright_colored(name + ":", Fore.YELLOW) + " " + value + if format_args: + line = line % format_args + info_lines.append(line) - username = getuser() - hostname = _get_hostname() + username = getuser() + hostname = _get_hostname() - info_lines.append( - bright_colored(username, Fore.BLUE) + "@" + bright_colored(hostname, Fore.RED) - ) - info_lines.append("") + info_lines.append(bright_colored(username, Fore.BLUE) + "@" + bright_colored(hostname, Fore.RED)) + info_lines.append("") - distro_id, distro_name, distro_version, distro_codename = _get_distro_info() - info("OS", " ".join([distro_name, distro_version, distro_codename])) + distro_id, distro_name, distro_version, distro_codename = _get_distro_info() + info("OS", " ".join([distro_name, distro_version, distro_codename])) - logo_path = os.path.join(os.path.dirname(__file__), "logos", distro_id) - with open(logo_path) as logo_file: - logo_lines = logo_file.read().splitlines() + logo_path = os.path.join(os.path.dirname(__file__), "logos", distro_id) + with open(logo_path) as logo_file: + logo_lines = logo_file.read().splitlines() - info("Kernel", "%s %s", platform.system(), platform.release()) + info("Kernel", "%s %s", platform.system(), platform.release()) - info("Uptime", humanize_timedelta(_get_uptime())) + info("Uptime", humanize_timedelta(_get_uptime())) - users_info = _get_users() - if users_info: - info("Users", users_info) + users_info = _get_users() + if users_info: + info("Users", users_info) - shell = _get_shell() - if shell is not None: - info("Shell", shell) + shell = _get_shell() + if shell is not None: + info("Shell", shell) - info_lines.append("") + info_lines.append("") - cpu_usage_info = _get_cpu_usage() - if cpu_usage_info is not None: - info("CPU Usage", "%s", cpu_usage_info) - info("Memory", "%s / %s (%s)", *_get_memory()) + cpu_usage_info = _get_cpu_usage() + if cpu_usage_info is not None: + info("CPU Usage", "%s", cpu_usage_info) + info("Memory", "%s / %s (%s)", *_get_memory()) - for disk_info in _get_disks(): - info("Disk (%s)", "%s / %s (%s)", *disk_info) + for disk_info in _get_disks(): + info("Disk (%s)", "%s / %s (%s)", *disk_info) - battery_info = _get_battery() - if battery_info is not None: - info("Battery", "%s (%s)", *battery_info) + battery_info = _get_battery() + if battery_info is not None: + info("Battery", "%s (%s)", *battery_info) - info_lines.append("") + info_lines.append("") - for local_ip_address in _get_local_ipv4_addresses(): - info("Local IPv4 Address (%s)", "%s", *local_ip_address) + for local_ip_address in _get_local_ipv4_addresses(): + info("Local IPv4 Address (%s)", "%s", *local_ip_address) - return logo_lines, info_lines + return logo_lines, info_lines def _get_hostname(): - hostname = socket.gethostname() - return hostname + hostname = socket.gethostname() + return hostname def _get_uptime(): - return datetime.now() - datetime.fromtimestamp(psutil.boot_time()) + return datetime.now() - datetime.fromtimestamp(psutil.boot_time()) def _get_users(): - users = {} + users = {} - for user in psutil.users(): - name = user.name - terminal = user.terminal - if name in users: - users[name].append(terminal) - else: - users[name] = [terminal] + for user in psutil.users(): + name = user.name + terminal = user.terminal + if name in users: + users[name].append(terminal) + else: + users[name] = [terminal] - result = [] + result = [] - for name in users: - terminals = users[name] + for name in users: + terminals = users[name] - colored_name = bright_colored(name, Fore.BLUE) - colored_terminals = [colored(str(term), Style.DIM, Fore.WHITE) for term in terminals] + colored_name = bright_colored(name, Fore.BLUE) + colored_terminals = [colored(str(term), Style.DIM, Fore.WHITE) for term in terminals] - terminals_str = ", ".join(colored_terminals) - if len(colored_terminals) > 1: - terminals_str = "(%s)" % terminals_str - result.append(colored_name + "@" + terminals_str) + terminals_str = ", ".join(colored_terminals) + if len(colored_terminals) > 1: + terminals_str = "(%s)" % terminals_str + result.append(colored_name + "@" + terminals_str) - return ", ".join(result) + return ", ".join(result) def _get_shell(): - return os.environ.get("SHELL") + return os.environ.get("SHELL") def _get_cpu_usage(): - try: - percent = psutil.cpu_percent() - except Exception as e: - print("Error in _get_cpu_usage:", e) - return None + try: + percent = psutil.cpu_percent() + except Exception as e: + print("Error in _get_cpu_usage:", e) + return None - return colorize_percent(percent, warning=60, critical=80) + return colorize_percent(percent, warning=60, critical=80) def _get_memory(): - memory = psutil.virtual_memory() - return ( - humanize_bytes(memory.used), - humanize_bytes(memory.total), - colorize_percent(memory.percent, warning=60, critical=80), - ) + memory = psutil.virtual_memory() + return ( + humanize_bytes(memory.used), + humanize_bytes(memory.total), + colorize_percent(memory.percent, warning=60, critical=80), + ) def _get_disks(): - result = [] + result = [] - for disk in psutil.disk_partitions(all=False): - if psutil.WINDOWS and ("cdrom" in disk.opts or disk.fstype == ""): - # skip cd-rom drives with no disk in it on Windows; they may raise - # ENOENT, pop-up a Windows GUI error for a non-ready partition or - # just hang - continue + for disk in psutil.disk_partitions(all=False): + if psutil.WINDOWS and ("cdrom" in disk.opts or disk.fstype == ""): + # skip cd-rom drives with no disk in it on Windows; they may raise + # ENOENT, pop-up a Windows GUI error for a non-ready partition or + # just hang + continue - usage = psutil.disk_usage(disk.mountpoint) - result.append(( - disk.mountpoint, - humanize_bytes(usage.used), - humanize_bytes(usage.total), - colorize_percent(usage.percent, warning=70, critical=85), - )) + usage = psutil.disk_usage(disk.mountpoint) + result.append(( + disk.mountpoint, + humanize_bytes(usage.used), + humanize_bytes(usage.total), + colorize_percent(usage.percent, warning=70, critical=85), + )) - return result + return result def _get_battery(): - if not hasattr(psutil, "sensors_battery"): - return None + if not hasattr(psutil, "sensors_battery"): + return None - try: - battery = psutil.sensors_battery() - except Exception as e: - print("Error in _get_battery:", e) - return None + try: + battery = psutil.sensors_battery() + except Exception as e: + print("Error in _get_battery:", e) + return None - if battery is None: - return None + if battery is None: + return None - percent = battery.percent - if battery.power_plugged: - status = "charging" if percent < 100 else "fully charged" - else: - status = "%s left" % humanize_timedelta(timedelta(seconds=battery.secsleft)) - return colorize_percent(percent, critical=10, warning=20, inverse=True), status + percent = battery.percent + if battery.power_plugged: + status = "charging" if percent < 100 else "fully charged" + else: + status = "%s left" % humanize_timedelta(timedelta(seconds=battery.secsleft)) + return colorize_percent(percent, critical=10, warning=20, inverse=True), status def _get_local_ipv4_addresses(): - result = [] + result = [] - for interface, addresses in psutil.net_if_addrs().items(): - for address in addresses: - if address.family != socket.AF_INET: - # allow only IPv4 addresses (skip IPv6 and MAC, for example) - continue - if interface.startswith("lo"): - # skip loopback interfaces - continue + for interface, addresses in psutil.net_if_addrs().items(): + for address in addresses: + if address.family != socket.AF_INET: + # allow only IPv4 addresses (skip IPv6 and MAC, for example) + continue + if interface.startswith("lo"): + # skip loopback interfaces + continue - result.append((interface, address.address)) + result.append((interface, address.address)) - return result + return result def _get_distro_info(): - if psutil.WINDOWS: - return "windows", platform.system(), platform.release(), "" - elif psutil.OSX: - import plistlib + if psutil.WINDOWS: + return "windows", platform.system(), platform.release(), "" + elif psutil.OSX: + import plistlib - with open("/System/Library/CoreServices/SystemVersion.plist", "rb") as f: - sw_vers = plistlib.load(f) - return "mac", sw_vers["ProductName"], sw_vers["ProductVersion"], "" - elif _is_android(): - from subprocess import check_output + with open("/System/Library/CoreServices/SystemVersion.plist", "rb") as f: + sw_vers = plistlib.load(f) + return "mac", sw_vers["ProductName"], sw_vers["ProductVersion"], "" + elif _is_android(): + from subprocess import check_output - android_version = check_output(["getprop", "ro.build.version.release"]) - return "android", "Android", android_version.decode().strip(), "" - elif psutil.LINUX: - import distro + android_version = check_output(["getprop", "ro.build.version.release"]) + return "android", "Android", android_version.decode().strip(), "" + elif psutil.LINUX: + import distro - return distro.id(), distro.name(), distro.version(), distro.codename() + return distro.id(), distro.name(), distro.version(), distro.codename() - raise NotImplementedError("unsupported OS") + raise NotImplementedError("unsupported OS") def _is_android(): - return os.path.isdir("/system/app") and os.path.isdir("/system/priv-app") + return os.path.isdir("/system/app") and os.path.isdir("/system/priv-app") From f8c01686eef09dbcaa2098f4d2e991f4c3cbdd60 Mon Sep 17 00:00:00 2001 From: Dmytro Meleshko Date: Mon, 26 Apr 2021 10:20:57 +0300 Subject: [PATCH 44/45] reformat all remaining Python scripts --- nvim/coc-languages/python.vim | 2 + scripts/copy-crosscode-emoji-url | 92 +++---- scripts/discord-snowflake | 19 +- scripts/discord-stream-desktop-audio | 28 +- scripts/discord-whois | 129 +++++---- scripts/factorio-dump-mod-settings | 38 ++- scripts/leveldb-dump | 49 ++-- scripts/mark-as-recently-used | 8 +- scripts/mediawiki-preview | 266 +++++++++--------- scripts/onscreen-message | 20 +- scripts/playerctl-simple-menu | 395 +++++++++++++-------------- scripts/query-bookmarks | 134 +++++---- scripts/random-local-ipv4 | 4 +- 13 files changed, 572 insertions(+), 612 deletions(-) diff --git a/nvim/coc-languages/python.vim b/nvim/coc-languages/python.vim index 1f0037d..336cf65 100644 --- a/nvim/coc-languages/python.vim +++ b/nvim/coc-languages/python.vim @@ -8,6 +8,8 @@ let s:ignored_errors += ['E111'] let s:ignored_errors += ['E114'] " Indent for continuation lines is smaller than expected let s:ignored_errors += ['E121'] +" Import not at the top of the file +let s:ignored_errors += ['E402'] " Line too long let s:ignored_errors += ['E501'] diff --git a/scripts/copy-crosscode-emoji-url b/scripts/copy-crosscode-emoji-url index 2192be2..e5ad71b 100755 --- a/scripts/copy-crosscode-emoji-url +++ b/scripts/copy-crosscode-emoji-url @@ -9,86 +9,76 @@ from typing import Any, Generator, Optional, Union import urllib.parse import urllib.request + sys.path.insert(1, os.path.join(os.path.dirname(__file__), "..", "script-resources")) import common_script_utils DEFAULT_REGISTRY_DUMP_URL = "https://stronghold.crosscode.ru/~ccbot/emote-registry.json" - if os.name == "posix": - config_path: Path = ( - common_script_utils.DOTFILES_CONFIG_DIR / "copy-crosscode-emoji-url.ini" - ) - default_registry_dump_file: Path = ( - common_script_utils.DOTFILES_CACHE_DIR / "dotfiles" - ) + config_path: Path = (common_script_utils.DOTFILES_CONFIG_DIR / "copy-crosscode-emoji-url.ini") + default_registry_dump_file: Path = (common_script_utils.DOTFILES_CACHE_DIR / "dotfiles") else: - common_script_utils.platform_not_supported_error() + common_script_utils.platform_not_supported_error() config = ConfigParser(interpolation=None) config.read(config_path) - emotes: list[dict[str, Any]] = [] def emote_downloader_and_iterator() -> Generator[str, None, None]: - global emotes + global emotes - registry_dump_file: Optional[Union[str, Path]] = config.get( - "default", "ccbot_emote_registry_dump_file", fallback=None - ) - if registry_dump_file is not None: - registry_dump_file = os.path.expanduser(registry_dump_file) - else: - registry_dump_file = default_registry_dump_file + registry_dump_file: Optional[Union[ + str, Path]] = config.get("default", "ccbot_emote_registry_dump_file", fallback=None) + if registry_dump_file is not None: + registry_dump_file = os.path.expanduser(registry_dump_file) + else: + registry_dump_file = default_registry_dump_file - registry_dump_url = config.get( - "default", "ccbot_emote_registry_dump_url", fallback=DEFAULT_REGISTRY_DUMP_URL - ) + registry_dump_url = config.get( + "default", "ccbot_emote_registry_dump_url", fallback=DEFAULT_REGISTRY_DUMP_URL + ) - emote_registry_data: dict[str, Any] - try: - with open(registry_dump_file, "r") as f: - emote_registry_data = json.load(f) - except FileNotFoundError: - with urllib.request.urlopen(registry_dump_url, timeout=10) as response: - emote_registry_data = json.load(response) + emote_registry_data: dict[str, Any] + try: + with open(registry_dump_file, "r") as f: + emote_registry_data = json.load(f) + except FileNotFoundError: + with urllib.request.urlopen(registry_dump_url, timeout=10) as response: + emote_registry_data = json.load(response) - assert emote_registry_data["version"] == 1 + assert emote_registry_data["version"] == 1 - emotes = [emote for emote in emote_registry_data["list"] if emote["safe"]] + emotes = [emote for emote in emote_registry_data["list"] if emote["safe"]] - for emote in emotes: - yield "{emote[ref]} [{emote[guild_name]}]".format(emote=emote) + for emote in emotes: + yield "{emote[ref]} [{emote[guild_name]}]".format(emote=emote) chosen_index = common_script_utils.run_chooser( - emote_downloader_and_iterator(), prompt="emote", async_read=True + emote_downloader_and_iterator(), prompt="emote", async_read=True ) if chosen_index >= 0: - chosen_emote = emotes[chosen_index] + chosen_emote = emotes[chosen_index] - emote_url: urllib.parse.ParseResult = urllib.parse.urlparse(chosen_emote["url"]) - emote_url_query: dict[str, list[str]] = urllib.parse.parse_qs(emote_url.query) + emote_url: urllib.parse.ParseResult = urllib.parse.urlparse(chosen_emote["url"]) + emote_url_query: dict[str, list[str]] = urllib.parse.parse_qs(emote_url.query) - if config.getboolean("default", "add_emote_name_to_url", fallback=False): - emote_url_query["name"] = [chosen_emote["name"]] + if config.getboolean("default", "add_emote_name_to_url", fallback=False): + emote_url_query["name"] = [chosen_emote["name"]] - default_emote_image_size = config.getint( - "default", "default_emote_image_size", fallback=None - ) - if default_emote_image_size is not None: - emote_url_query["size"] = [str(default_emote_image_size)] + default_emote_image_size = config.getint("default", "default_emote_image_size", fallback=None) + if default_emote_image_size is not None: + emote_url_query["size"] = [str(default_emote_image_size)] - emote_url_query_str = urllib.parse.urlencode(emote_url_query, doseq=True) - emote_url_str = urllib.parse.urlunparse( - emote_url._replace(query=emote_url_query_str) - ) + emote_url_query_str = urllib.parse.urlencode(emote_url_query, doseq=True) + emote_url_str = urllib.parse.urlunparse(emote_url._replace(query=emote_url_query_str)) - common_script_utils.set_clipboard(emote_url_str) + common_script_utils.set_clipboard(emote_url_str) - common_script_utils.send_notification( - os.path.basename(__file__), - "copied URL of {} to clipboard!".format(chosen_emote["ref"]), - ) + common_script_utils.send_notification( + os.path.basename(__file__), + "copied URL of {} to clipboard!".format(chosen_emote["ref"]), + ) diff --git a/scripts/discord-snowflake b/scripts/discord-snowflake index 25380b9..85343ba 100755 --- a/scripts/discord-snowflake +++ b/scripts/discord-snowflake @@ -6,17 +6,16 @@ import sys import colorama import time + DISCORD_EPOCH = 1420070400000 # milliseconds user_snowflake = int(sys.argv[1]) def print_field(name, value): - print( - "{}{}:{} {}".format( - colorama.Style.BRIGHT, name.rjust(21), colorama.Style.RESET_ALL, value - ) - ) + print( + "{}{}:{} {}".format(colorama.Style.BRIGHT, name.rjust(21), colorama.Style.RESET_ALL, value) + ) creation_time = (user_snowflake >> 22) + DISCORD_EPOCH @@ -25,11 +24,11 @@ internal_process_id = (user_snowflake >> 12) & 0x1F increment = user_snowflake & 0xFFF print_field( - "Created at", - "{}.{}".format( - time.strftime("%Y-%m-%d %H:%M:%S", time.gmtime(creation_time // 1000)), - creation_time % 1000, - ), + "Created at", + "{}.{}".format( + time.strftime("%Y-%m-%d %H:%M:%S", time.gmtime(creation_time // 1000)), + creation_time % 1000, + ), ) print_field("Internal worker ID", internal_worker_id) print_field("Internal process ID", internal_process_id) diff --git a/scripts/discord-stream-desktop-audio b/scripts/discord-stream-desktop-audio index e80d176..da925b4 100755 --- a/scripts/discord-stream-desktop-audio +++ b/scripts/discord-stream-desktop-audio @@ -4,35 +4,33 @@ import discord import sys import os + guild_id = int(sys.argv[1]) voice_channel_id = int(sys.argv[2]) pulseaudio_device = sys.argv[3] with open(os.path.expanduser("~/.config/dotfiles/discord-tools-bot-token.txt")) as f: - bot_token = f.read().strip() - + bot_token = f.read().strip() bot = discord.Client() @bot.event async def on_ready(): - print("logged in as {0} ({0.id})".format(bot.user)) + print("logged in as {0} ({0.id})".format(bot.user)) - guild: discord.Guild = bot.get_guild(guild_id) - if guild is None: - raise Exception("guild not found") - voice_channel: discord.VoiceChannel = guild.get_channel(voice_channel_id) - if voice_channel is None: - raise Exception("channel not found") + guild: discord.Guild = bot.get_guild(guild_id) + if guild is None: + raise Exception("guild not found") + voice_channel: discord.VoiceChannel = guild.get_channel(voice_channel_id) + if voice_channel is None: + raise Exception("channel not found") - voice_client = await voice_channel.connect() - print("connected to {0} ({0.id}) in {1} ({1.id})".format(voice_channel, guild)) + voice_client = await voice_channel.connect() + print("connected to {0} ({0.id}) in {1} ({1.id})".format(voice_channel, guild)) - source = discord.FFmpegPCMAudio(pulseaudio_device, before_options="-f pulse") - voice_client.play( - source, after=lambda e: print("Player error: %s" % e) if e else None - ) + source = discord.FFmpegPCMAudio(pulseaudio_device, before_options="-f pulse") + voice_client.play(source, after=lambda e: print("Player error: %s" % e) if e else None) bot.run(bot_token) diff --git a/scripts/discord-whois b/scripts/discord-whois index 91fd346..0598fed 100755 --- a/scripts/discord-whois +++ b/scripts/discord-whois @@ -18,22 +18,21 @@ import typing DISCORD_EPOCH = 1420070400000 # milliseconds # https://discord.com/developers/docs/resources/user#user-object-user-flags DISCORD_FLAGS = { - "Discord Employee": 1 << 0, - "Discord Partner": 1 << 1, - "HypeSquad Events": 1 << 2, - "Bug Hunter Level 1": 1 << 3, - "House of Bravery": 1 << 6, - "House of Brilliance": 1 << 7, - "House of Balance": 1 << 8, - "Early Supporter": 1 << 9, - "Team User": 1 << 10, - "System": 1 << 12, - "Bug Hunter Level 2": 1 << 14, - "Verified Bot": 1 << 16, - "Verified Bot Developer": 1 << 17, + "Discord Employee": 1 << 0, + "Discord Partner": 1 << 1, + "HypeSquad Events": 1 << 2, + "Bug Hunter Level 1": 1 << 3, + "House of Bravery": 1 << 6, + "House of Brilliance": 1 << 7, + "House of Balance": 1 << 8, + "Early Supporter": 1 << 9, + "Team User": 1 << 10, + "System": 1 << 12, + "Bug Hunter Level 2": 1 << 14, + "Verified Bot": 1 << 16, + "Verified Bot Developer": 1 << 17, } - parser = argparse.ArgumentParser() parser.add_argument("user_snowflake", type=int) parser.add_argument("--bot-token", type=str) @@ -45,32 +44,29 @@ user_snowflake = cli_args.user_snowflake bot_token = cli_args.bot_token if bot_token is None: - with open( - os.path.expanduser("~/.config/dotfiles/discord-tools-bot-token.txt") - ) as f: - bot_token = f.read().strip() + with open(os.path.expanduser("~/.config/dotfiles/discord-tools-bot-token.txt")) as f: + bot_token = f.read().strip() image_size = cli_args.image_size if not (image_size is None or (image_size > 0 and image_size & (image_size - 1)) == 0): - parser.error("image_size must be greater than zero and a power of two") - + parser.error("image_size must be greater than zero and a power of two") try: - opener = urllib.request.build_opener() - # Don't send the User-Agent header, Discord blocks the default one - opener.addheaders = [] - with opener.open( - urllib.request.Request( - "http://discord.com/api/users/{}".format(user_snowflake), - headers={"Authorization": "Bot {}".format(bot_token)}, - ), - timeout=10, - ) as response: - raw_data = json.load(response) + opener = urllib.request.build_opener() + # Don't send the User-Agent header, Discord blocks the default one + opener.addheaders = [] + with opener.open( + urllib.request.Request( + "http://discord.com/api/users/{}".format(user_snowflake), + headers={"Authorization": "Bot {}".format(bot_token)}, + ), + timeout=10, + ) as response: + raw_data = json.load(response) except urllib.error.HTTPError as err: - print(err, file=sys.stderr) - print(err.read(), file=sys.stderr) - raise err + print(err, file=sys.stderr) + print(err.read(), file=sys.stderr) + raise err data = {} @@ -78,19 +74,17 @@ data["ID"] = raw_data["id"] data["Name"] = "{}#{}".format(raw_data["username"], raw_data["discriminator"]) default_avatar_url = "https://cdn.discordapp.com/embed/avatars/{}.png".format( - int(raw_data["discriminator"], 10) % 5 + int(raw_data["discriminator"], 10) % 5 ) avatar_url = ( - "https://cdn.discordapp.com/avatars/{}/{}.{}".format( - raw_data["id"], - raw_data["avatar"], - "gif" if raw_data["avatar"].startswith("a_") else "png", - ) - if raw_data["avatar"] is not None - else default_avatar_url + "https://cdn.discordapp.com/avatars/{}/{}.{}".format( + raw_data["id"], + raw_data["avatar"], + "gif" if raw_data["avatar"].startswith("a_") else "png", + ) if raw_data["avatar"] is not None else default_avatar_url ) if image_size is not None: - avatar_url += "?size={}".format(image_size) + avatar_url += "?size={}".format(image_size) data["Avatar"] = avatar_url data["Default avatar"] = default_avatar_url @@ -101,38 +95,37 @@ data["System user"] = raw_data.get("system", False) # https://discord.com/developers/docs/reference#convert-snowflake-to-datetime snowflake_creation_time = (user_snowflake >> 22) + DISCORD_EPOCH data["Created at"] = "{}.{} UTC".format( - time.strftime("%Y-%m-%d %H:%M:%S", time.gmtime(snowflake_creation_time // 1000)), - snowflake_creation_time % 1000, + time.strftime("%Y-%m-%d %H:%M:%S", time.gmtime(snowflake_creation_time // 1000)), + snowflake_creation_time % 1000, ) user_flags = raw_data["public_flags"] if user_flags == 0: - data["Flags"] = "" + data["Flags"] = "" else: - user_flag_names = [] - for flag_name, bitmask in DISCORD_FLAGS.items(): - if user_flags & bitmask: - user_flag_names.append(flag_name) - data["Flags"] = ", ".join(user_flag_names) - + user_flag_names = [] + for flag_name, bitmask in DISCORD_FLAGS.items(): + if user_flags & bitmask: + user_flag_names.append(flag_name) + data["Flags"] = ", ".join(user_flag_names) if cli_args.get_prop is None: - max_name_length = max(map(len, data.keys())) - for name, value in data.items(): + max_name_length = max(map(len, data.keys())) + for name, value in data.items(): - if value is True: - value = "yes" - elif value is False: - value = "no" + if value is True: + value = "yes" + elif value is False: + value = "no" - print( - "{}{:>{}}:{} {}".format( - colorama.Style.BRIGHT, - name, - max_name_length + 1, - colorama.Style.RESET_ALL, - value, - ) - ) + print( + "{}{:>{}}:{} {}".format( + colorama.Style.BRIGHT, + name, + max_name_length + 1, + colorama.Style.RESET_ALL, + value, + ) + ) else: - print(data[cli_args.get_prop]) + print(data[cli_args.get_prop]) diff --git a/scripts/factorio-dump-mod-settings b/scripts/factorio-dump-mod-settings index 5f04b2e..8530465 100755 --- a/scripts/factorio-dump-mod-settings +++ b/scripts/factorio-dump-mod-settings @@ -10,31 +10,29 @@ from pathlib import Path import struct import json + sys.path.insert(1, os.path.join(os.path.dirname(__file__), "..", "script-resources")) import factorio.property_tree - with open(Path.home() / ".factorio" / "mods" / "mod-settings.dat", "rb") as f: - version_main: int - version_major: int - version_minor: int - version_developer: int - version_main, version_major, version_minor, version_developer = struct.unpack( - " Union[str, list[int]]: - if encoding == "utf8": - try: - return b.decode("utf8") - except UnicodeDecodeError: - return list(b) - elif encoding == "base16": - return base64.b16encode(b).decode("ascii") - elif encoding == "base32": - return base64.b32encode(b).decode("ascii") - elif encoding == "base64": - return base64.b64encode(b).decode("ascii") - elif encoding == "base85": - return base64.b85encode(b).decode("ascii") - else: - assert False + if encoding == "utf8": + try: + return b.decode("utf8") + except UnicodeDecodeError: + return list(b) + elif encoding == "base16": + return base64.b16encode(b).decode("ascii") + elif encoding == "base32": + return base64.b32encode(b).decode("ascii") + elif encoding == "base64": + return base64.b64encode(b).decode("ascii") + elif encoding == "base85": + return base64.b85encode(b).decode("ascii") + else: + assert False key_encoding: str = cli_args.key_encoding or cli_args.encoding value_encoding: str = cli_args.value_encoding or cli_args.encoding db = plyvel.DB(str(cli_args.db_path), create_if_missing=False) with db.iterator() as iterator: - for key, value in iterator: - json.dump( - { - "key": bytes_to_json(key, key_encoding), - "value": bytes_to_json(value, value_encoding), - }, - stdout, - ) - stdout.write("\n") + for key, value in iterator: + json.dump( + { + "key": bytes_to_json(key, key_encoding), + "value": bytes_to_json(value, value_encoding), + }, + stdout, + ) + stdout.write("\n") diff --git a/scripts/mark-as-recently-used b/scripts/mark-as-recently-used index 63475cd..c35e763 100755 --- a/scripts/mark-as-recently-used +++ b/scripts/mark-as-recently-used @@ -1,14 +1,16 @@ -#!/usr/bin/python3 +#!/usr/bin/env python3 # Taken from import gi import sys + gi.require_version("Gtk", "3.0") -from gi.repository import Gtk, Gio, GLib # noqa E402 +from gi.repository import Gtk, Gio, GLib + rec_mgr = Gtk.RecentManager.get_default() for arg in sys.argv[1:]: - rec_mgr.add_item(Gio.File.new_for_path(arg).get_uri()) + rec_mgr.add_item(Gio.File.new_for_path(arg).get_uri()) GLib.idle_add(Gtk.main_quit) Gtk.main() diff --git a/scripts/mediawiki-preview b/scripts/mediawiki-preview index c1cfc68..b2d978b 100755 --- a/scripts/mediawiki-preview +++ b/scripts/mediawiki-preview @@ -38,7 +38,6 @@ # - The module `skins.citizen.scripts` references search inputs which aren't # created by this script. - import argparse import mwclient import json @@ -51,85 +50,85 @@ LANG = "en" LANG_TEXT_DIRECTION = "ltr" MODULES_POST_LOAD = { - "vector": [ - "site", - "mediawiki.page.startup", - "mediawiki.page.ready", - "mediawiki.toc", - # "mediawiki.searchSuggest", - # "mediawiki.page.watch.ajax", - "skins.vector.js", - ], - "citizen": [ - # "site", - # "mediawiki.page.startup", - # "mediawiki.page.ready", - # "mediawiki.toc", - # "skins.citizen.scripts.toc", - # "skins.citizen.scripts.search", - # "skins.citizen.styles.search", - # "skins.citizen.icons.search", - # "skins.citizen.scripts", - ], + "vector": [ + "site", + "mediawiki.page.startup", + "mediawiki.page.ready", + "mediawiki.toc", + # "mediawiki.searchSuggest", + # "mediawiki.page.watch.ajax", + "skins.vector.js", + ], + "citizen": [ + # "site", + # "mediawiki.page.startup", + # "mediawiki.page.ready", + # "mediawiki.toc", + # "skins.citizen.scripts.toc", + # "skins.citizen.scripts.search", + # "skins.citizen.styles.search", + # "skins.citizen.icons.search", + # "skins.citizen.scripts", + ], } MODULES_POST_LOAD_BLOCKED = { - "citizen": [ - "skins.citizen.scripts.toc", - "skins.citizen.scripts.search", - "skins.citizen.styles.search", - "skins.citizen.icons.search", - ], + "citizen": [ + "skins.citizen.scripts.toc", + "skins.citizen.scripts.search", + "skins.citizen.styles.search", + "skins.citizen.icons.search", + ], } MODULES_PRELOAD_STYLES = { - "vector": [ - "mediawiki.legacy.commonPrint", - "mediawiki.legacy.shared", - "mediawiki.skinning.interface", - "mediawiki.toc.styles", - "skins.vector.styles", - "site.styles", - ], - "citizen": [ - # "mediawiki.legacy.commonPrint", - # "mediawiki.legacy.shared", - "mediawiki.skinning.content.externallinks", - # "mediawiki.toc.styles", - "skins.citizen.icons", - "skins.citizen.styles", - "skins.citizen.icons.ca", - "skins.citizen.icons.es", - "skins.citizen.icons.footer", - "skins.citizen.icons.n", - "skins.citizen.icons.pt", - "skins.citizen.icons.t", - "skins.citizen.styles.fonts", - "skins.citizen.styles.toc", - "site.styles", - ], + "vector": [ + "mediawiki.legacy.commonPrint", + "mediawiki.legacy.shared", + "mediawiki.skinning.interface", + "mediawiki.toc.styles", + "skins.vector.styles", + "site.styles", + ], + "citizen": [ + # "mediawiki.legacy.commonPrint", + # "mediawiki.legacy.shared", + "mediawiki.skinning.content.externallinks", + # "mediawiki.toc.styles", + "skins.citizen.icons", + "skins.citizen.styles", + "skins.citizen.icons.ca", + "skins.citizen.icons.es", + "skins.citizen.icons.footer", + "skins.citizen.icons.n", + "skins.citizen.icons.pt", + "skins.citizen.icons.t", + "skins.citizen.styles.fonts", + "skins.citizen.styles.toc", + "site.styles", + ], } MODULES_PRELOAD_SCRIPTS = { - "vector": ["startup"], - "citizen": ["startup"], + "vector": ["startup"], + "citizen": ["startup"], } # ported from def escape_css_class(class_str): - class_str = re.sub( - r"""(^[0-9\-])|[\x00-\x20!"#$%&'()*+,.\/:;<=>?@[\]^`{|}~]|\xA0""", - "_", - class_str, - ) - class_str = re.sub(r"_+", "_", class_str) - class_str = class_str.rstrip("_") - return class_str + class_str = re.sub( + r"""(^[0-9\-])|[\x00-\x20!"#$%&'()*+,.\/:;<=>?@[\]^`{|}~]|\xA0""", + "_", + class_str, + ) + class_str = re.sub(r"_+", "_", class_str) + class_str = class_str.rstrip("_") + return class_str def json_dumps_compact(data): - return json.dumps(data, indent=None, separators=(",", ":")) + return json.dumps(data, indent=None, separators=(",", ":")) parser = argparse.ArgumentParser() @@ -137,50 +136,55 @@ parser.add_argument("--site", type=str, required=True) parser.add_argument("--scheme", type=str, default="https") parser.add_argument("--skin", type=str, default="vector") parser.add_argument( - "--input", type=str, required=True, + "--input", + type=str, + required=True, ) parser.add_argument("--title", type=str) parser.add_argument("--output", type=str, required=True) cli_args = parser.parse_args() - site = mwclient.Site(cli_args.site, scheme=cli_args.scheme) def get_load_script_url(**args): - return "{path}load{ext}?{args}".format( - path=site.path, - ext=site.ext, - args=urlencode({"lang": LANG, "skin": cli_args.skin, **args}), - ) + return "{path}load{ext}?{args}".format( + path=site.path, + ext=site.ext, + args=urlencode({ + "lang": LANG, + "skin": cli_args.skin, + **args + }), + ) with open(cli_args.input, "r") as f: - wikitext_str = f.read() + wikitext_str = f.read() result = site.post( - "parse", - title=cli_args.title, - text=wikitext_str, - contentmodel="wikitext", - prop="text|indicators|displaytitle|modules|jsconfigvars|categorieshtml", - preview=True, - pst=True, # pre-save transforms - sectionpreview=False, - disableeditsection=True, # disables "[edit]" links next to headers - useskin=cli_args.skin, - uselang=LANG, + "parse", + title=cli_args.title, + text=wikitext_str, + contentmodel="wikitext", + prop="text|indicators|displaytitle|modules|jsconfigvars|categorieshtml", + preview=True, + pst=True, # pre-save transforms + sectionpreview=False, + disableeditsection=True, # disables "[edit]" links next to headers + useskin=cli_args.skin, + uselang=LANG, )["parse"] def get_modules(page_modules, added_modules_dict, blocked_modules_dict={}): - modules = page_modules + added_modules_dict[cli_args.skin] - for blocked_module in blocked_modules_dict.get(cli_args.skin, []): - try: - modules.remove(blocked_module) - except ValueError: - pass - return modules + modules = page_modules + added_modules_dict[cli_args.skin] + for blocked_module in blocked_modules_dict.get(cli_args.skin, []): + try: + modules.remove(blocked_module) + except ValueError: + pass + return modules rendered_html = """\ @@ -240,53 +244,43 @@ rendered_html = """\ """.format( - lang=html.escape(LANG), - text_dir=html.escape(LANG_TEXT_DIRECTION), - base_url=html.escape("{}://{}".format(site.scheme, site.host)), - page_modules_state_json=json_dumps_compact( - { - "noscript": "ready", - "user.options": "ready", - "user.tokens": "loading", - **{name: "ready" for name in MODULES_PRELOAD_STYLES[cli_args.skin]}, - } - ), - page_config_json=json_dumps_compact(result["jsconfigvars"]), - page_modules_json=json_dumps_compact( - get_modules(result["modules"], MODULES_POST_LOAD, MODULES_POST_LOAD_BLOCKED) - ), - style_url=html.escape( - get_load_script_url( - only="styles", - modules="|".join( - get_modules(result["modulestyles"], MODULES_PRELOAD_STYLES) - ), - ) - ), - script_url=html.escape( - get_load_script_url( - only="scripts", - modules="|".join( - get_modules(result["modulescripts"], MODULES_PRELOAD_SCRIPTS) - ), - raw="1", - ) - ), - skin=html.escape(cli_args.skin), - page_class=html.escape(escape_css_class(result["displaytitle"])), - title=html.escape(result["displaytitle"]), - indicators_html="\n".join( - [ - '
{}
'.format( - indicator["name"], indicator["*"] - ) - for indicator in result["indicators"] - ] - ), - content_html=result["text"]["*"], - categories_html=result["categorieshtml"]["*"], + lang=html.escape(LANG), + text_dir=html.escape(LANG_TEXT_DIRECTION), + base_url=html.escape("{}://{}".format(site.scheme, site.host)), + page_modules_state_json=json_dumps_compact({ + "noscript": "ready", + "user.options": "ready", + "user.tokens": "loading", + **{name: "ready" for name in MODULES_PRELOAD_STYLES[cli_args.skin]}, + }), + page_config_json=json_dumps_compact(result["jsconfigvars"]), + page_modules_json=json_dumps_compact( + get_modules(result["modules"], MODULES_POST_LOAD, MODULES_POST_LOAD_BLOCKED) + ), + style_url=html.escape( + get_load_script_url( + only="styles", + modules="|".join(get_modules(result["modulestyles"], MODULES_PRELOAD_STYLES)), + ) + ), + script_url=html.escape( + get_load_script_url( + only="scripts", + modules="|".join(get_modules(result["modulescripts"], MODULES_PRELOAD_SCRIPTS)), + raw="1", + ) + ), + skin=html.escape(cli_args.skin), + page_class=html.escape(escape_css_class(result["displaytitle"])), + title=html.escape(result["displaytitle"]), + indicators_html="\n".join([ + '
{}
'.format( + indicator["name"], indicator["*"] + ) for indicator in result["indicators"] + ]), + content_html=result["text"]["*"], + categories_html=result["categorieshtml"]["*"], ) - with open(cli_args.output, "w") as f: - f.write(rendered_html) + f.write(rendered_html) diff --git a/scripts/onscreen-message b/scripts/onscreen-message index 3ca6694..32c3b5a 100755 --- a/scripts/onscreen-message +++ b/scripts/onscreen-message @@ -2,8 +2,9 @@ import gi import argparse + gi.require_version("Gtk", "3.0") -from gi.repository import Gtk, Gdk, Pango # noqa: E402 +from gi.repository import Gtk, Gdk, Pango parser = argparse.ArgumentParser() @@ -12,7 +13,6 @@ args = parser.parse_args() message = " ".join(args.message) - window = Gtk.ApplicationWindow() window.set_keep_above(True) window.set_decorated(False) @@ -25,17 +25,17 @@ window.add(scrolled_window) def on_key_release(target, event): - key = event.keyval - if key in [Gdk.KEY_Escape, Gdk.KEY_q, Gdk.KEY_Q]: - window.close() + key = event.keyval + if key in [Gdk.KEY_Escape, Gdk.KEY_q, Gdk.KEY_Q]: + window.close() def on_configure(target, event): - if target != window or event.type != Gdk.EventType.CONFIGURE: - return - font_desc = Pango.FontDescription() - font_desc.set_size(Pango.SCALE * event.height * 2 / 3) - label.override_font(font_desc) + if target != window or event.type != Gdk.EventType.CONFIGURE: + return + font_desc = Pango.FontDescription() + font_desc.set_size(Pango.SCALE * event.height * 2 / 3) + label.override_font(font_desc) window.connect("configure-event", on_configure) diff --git a/scripts/playerctl-simple-menu b/scripts/playerctl-simple-menu index 3072017..f351bb4 100755 --- a/scripts/playerctl-simple-menu +++ b/scripts/playerctl-simple-menu @@ -9,162 +9,162 @@ import math import gi + gi.require_version("Playerctl", "2.0") gi.require_version("Gtk", "3.0") gi.require_version("Gdk", "3.0") gi.require_version("Pango", "1.0") -from gi.repository import Playerctl, Gtk, Gdk, GLib, Pango # noqa: E402 - +from gi.repository import Playerctl, Gtk, Gdk, GLib, Pango # Larger priority values will make the player with this name appear higher in # the menu. The default priority is 0. PLAYER_NAME_PRIORITIES = { - "audacious": 2, - "mpv": 1, - "vlc": 1, - "firefox": -1, - "chrome": -2, - "chromium": -2, + "audacious": 2, + "mpv": 1, + "vlc": 1, + "firefox": -1, + "chrome": -2, + "chromium": -2, } PLAYER_ICON_NAME_FIXES = { - "chrome": "google-chrome", + "chrome": "google-chrome", } PLAYER_PLAYBACK_STATUS_EMOJIS = { - Playerctl.PlaybackStatus.PLAYING: "\u25B6", - Playerctl.PlaybackStatus.PAUSED: "\u23F8", - Playerctl.PlaybackStatus.STOPPED: "\u23F9", + Playerctl.PlaybackStatus.PLAYING: "\u25B6", + Playerctl.PlaybackStatus.PAUSED: "\u23F8", + Playerctl.PlaybackStatus.STOPPED: "\u23F9", } def humanize_duration(duration): - minutes, seconds = divmod(math.floor(duration), 60) - hours, minutes = divmod(minutes, 60) - text = "{:02}:{:02}".format(minutes, seconds) - if hours > 0: - text = "{}:{}".format(hours, text) - return text + minutes, seconds = divmod(math.floor(duration), 60) + hours, minutes = divmod(minutes, 60) + text = "{:02}:{:02}".format(minutes, seconds) + if hours > 0: + text = "{}:{}".format(hours, text) + return text def iter_metadata_entries_for_player(player): - metadata = player.props.metadata + metadata = player.props.metadata - title = metadata.lookup_value("xesam:title") - if title: - yield title.get_string() + title = metadata.lookup_value("xesam:title") + if title: + yield title.get_string() - album = metadata.lookup_value("xesam:album") - if album: - yield album.get_string() + album = metadata.lookup_value("xesam:album") + if album: + yield album.get_string() - if player.props.can_seek: - position_secs = player.props.position / 1e6 - duration = metadata.lookup_value("mpris:length") - if duration is not None and duration.is_of_type(GLib.VariantType.new("x")): - duration_secs = duration.get_int64() / 1e6 - yield "Time: {} / {}".format( - humanize_duration(position_secs), humanize_duration(duration_secs) - ) + if player.props.can_seek: + position_secs = player.props.position / 1e6 + duration = metadata.lookup_value("mpris:length") + if duration is not None and duration.is_of_type(GLib.VariantType.new("x")): + duration_secs = duration.get_int64() / 1e6 + yield "Time: {} / {}".format( + humanize_duration(position_secs), humanize_duration(duration_secs) + ) def iter_actions_for_player(player): - if not player.props.can_control: - yield ("This player can't be controlled!", None, False, None) - return + if not player.props.can_control: + yield ("This player can't be controlled!", None, False, None) + return - playback_status = player.props.playback_status - if playback_status == Playerctl.PlaybackStatus.PLAYING: - yield ( - "_Pause", - "media-playback-pause", - player.props.can_pause, - player.pause, - ) - elif playback_status == Playerctl.PlaybackStatus.PAUSED: - yield ( - "Resume (_P)", - "media-playback-start", - player.props.can_play, - player.play, - ) - elif playback_status == Playerctl.PlaybackStatus.STOPPED: - yield ( - "_Play", - "media-playback-start", - player.props.can_play, - player.play, - ) - - # See + playback_status = player.props.playback_status + if playback_status == Playerctl.PlaybackStatus.PLAYING: yield ( - "_Stop", - "media-playback-stop", - player.props.can_play and playback_status != Playerctl.PlaybackStatus.STOPPED, - player.stop, + "_Pause", + "media-playback-pause", + player.props.can_pause, + player.pause, + ) + elif playback_status == Playerctl.PlaybackStatus.PAUSED: + yield ( + "Resume (_P)", + "media-playback-start", + player.props.can_play, + player.play, + ) + elif playback_status == Playerctl.PlaybackStatus.STOPPED: + yield ( + "_Play", + "media-playback-start", + player.props.can_play, + player.play, ) + # See + yield ( + "_Stop", + "media-playback-stop", + player.props.can_play and playback_status != Playerctl.PlaybackStatus.STOPPED, + player.stop, + ) + + yield ( + "_Mute" if player.props.volume != 0.0 else "Nor_mal volume", + "audio-volume-muted" if player.props.volume != 0.0 else "audio-volume-high", + True, + lambda volume: player.set_volume(volume), + 0.0 if player.props.volume != 0.0 else 1.0, + ) + yield ( + "Volume +10%", + "audio-volume-medium", + True, + lambda: player.set_volume(min(player.props.volume + 0.1, 1.0)), + ) + yield ( + "Volume -10%", + "audio-volume-low", + True, + lambda: player.set_volume(max(player.props.volume - 0.1, 0.0)), + ) + + yield ( + "_Next", + "media-skip-forward", + player.props.can_go_next, + player.next, + ) + yield ( + "Previous (_B)", + "media-skip-backward", + player.props.can_go_previous, + player.previous, + ) + + shuffle = player.props.shuffle + yield ( + "Don't shuffle (_R)" if shuffle else "Shuffle (_R)", + "media-playlist-shuffle", + True, + lambda: player.set_shuffle(not shuffle), + ) + + loop_status = player.props.loop_status + for loop_action_name, loop_action_status in [ + ("Don't _loop", Playerctl.LoopStatus.NONE), + ("Loop _one", Playerctl.LoopStatus.TRACK), + ("Loop _all", Playerctl.LoopStatus.PLAYLIST), + ]: yield ( - "_Mute" if player.props.volume != 0.0 else "Nor_mal volume", - "audio-volume-muted" if player.props.volume != 0.0 else "audio-volume-high", - True, - lambda volume: player.set_volume(volume), - 0.0 if player.props.volume != 0.0 else 1.0, - ) - yield ( - "Volume +10%", - "audio-volume-medium", - True, - lambda: player.set_volume(min(player.props.volume + 0.1, 1.0)), - ) - yield ( - "Volume -10%", - "audio-volume-low", - True, - lambda: player.set_volume(max(player.props.volume - 0.1, 0.0)), + loop_action_name, + "media-playlist-repeat", + loop_action_status != loop_status, + lambda loop_action_status: player.set_loop_status(loop_action_status), + loop_action_status, ) - yield ( - "_Next", - "media-skip-forward", - player.props.can_go_next, - player.next, - ) - yield ( - "Previous (_B)", - "media-skip-backward", - player.props.can_go_previous, - player.previous, - ) - - shuffle = player.props.shuffle - yield ( - "Don't shuffle (_R)" if shuffle else "Shuffle (_R)", - "media-playlist-shuffle", - True, - lambda: player.set_shuffle(not shuffle), - ) - - loop_status = player.props.loop_status - for loop_action_name, loop_action_status in [ - ("Don't _loop", Playerctl.LoopStatus.NONE), - ("Loop _one", Playerctl.LoopStatus.TRACK), - ("Loop _all", Playerctl.LoopStatus.PLAYLIST), - ]: - yield ( - loop_action_name, - "media-playlist-repeat", - loop_action_status != loop_status, - lambda loop_action_status: player.set_loop_status(loop_action_status), - loop_action_status, - ) - - yield ( - "Play a_gain", - "go-first", - player.props.can_seek, - lambda: player.set_position(0), - ) + yield ( + "Play a_gain", + "go-first", + player.props.can_seek, + lambda: player.set_position(0), + ) root_menu = Gtk.Menu() @@ -172,93 +172,84 @@ root_menu = Gtk.Menu() player_names = Playerctl.list_players() if len(player_names) > 0: - players = [] - for player_name in player_names: - player = Playerctl.Player.new_from_name(player_name) - players.append( - { - "player": player, - "player_name": player_name, - "sorting_key": ( - player.props.playback_status != Playerctl.PlaybackStatus.PLAYING, - -PLAYER_NAME_PRIORITIES.get(player_name.name, 0), - player_name.instance, - ), - } - ) - players = sorted( - players, key=lambda player_and_meta: player_and_meta["sorting_key"] + players = [] + for player_name in player_names: + player = Playerctl.Player.new_from_name(player_name) + players.append({ + "player": + player, + "player_name": + player_name, + "sorting_key": ( + player.props.playback_status != Playerctl.PlaybackStatus.PLAYING, + -PLAYER_NAME_PRIORITIES.get(player_name.name, 0), + player_name.instance, + ), + }) + players = sorted(players, key=lambda player_and_meta: player_and_meta["sorting_key"]) + + for player_and_meta in players: + player_name = player_and_meta["player_name"] + player = player_and_meta["player"] + + player_menu_item = Gtk.ImageMenuItem.new_with_label( + "{} [{}]".format( + player_name.instance, + PLAYER_PLAYBACK_STATUS_EMOJIS[player.props.playback_status], + ) ) - for player_and_meta in players: - player_name = player_and_meta["player_name"] - player = player_and_meta["player"] + player_icon_name = PLAYER_ICON_NAME_FIXES.get(player_name.name, player_name.name) + player_icon = Gtk.Image.new_from_icon_name(player_icon_name, Gtk.IconSize.MENU) + player_menu_item.set_image(player_icon) - player_menu_item = Gtk.ImageMenuItem.new_with_label( - "{} [{}]".format( - player_name.instance, - PLAYER_PLAYBACK_STATUS_EMOJIS[player.props.playback_status], - ) + actions_menu = Gtk.Menu() + + track_metadata = player.props.metadata + any_metadata_was_added = False + for meta_entry_text in iter_metadata_entries_for_player(player): + meta_menu_item = Gtk.MenuItem.new_with_label(meta_entry_text) + meta_menu_item.set_sensitive(False) + meta_menu_item_label = meta_menu_item.get_child() + meta_menu_item_label.set_ellipsize(Pango.EllipsizeMode.END) + meta_menu_item_label.set_max_width_chars(20) + + actions_menu.append(meta_menu_item) + any_metadata_was_added = True + + if any_metadata_was_added: + actions_menu.append(Gtk.SeparatorMenuItem.new()) + + for ( + action_name, + action_icon_name, + action_enabled, + action_fn, + *action_fn_args, + ) in iter_actions_for_player(player): + action_menu_item = Gtk.ImageMenuItem.new_with_mnemonic(action_name) + + if action_icon_name is not None: + action_icon = Gtk.Image.new_from_icon_name(action_icon_name, Gtk.IconSize.MENU) + action_menu_item.set_image(action_icon) + + action_menu_item.set_sensitive(action_enabled) + if action_fn is not None: + action_menu_item.connect( + "activate", + lambda _menu_item, action_fn, action_fn_args: action_fn(*action_fn_args), + action_fn, + action_fn_args, ) - player_icon_name = PLAYER_ICON_NAME_FIXES.get( - player_name.name, player_name.name - ) - player_icon = Gtk.Image.new_from_icon_name(player_icon_name, Gtk.IconSize.MENU) - player_menu_item.set_image(player_icon) + actions_menu.append(action_menu_item) - actions_menu = Gtk.Menu() - - track_metadata = player.props.metadata - any_metadata_was_added = False - for meta_entry_text in iter_metadata_entries_for_player(player): - meta_menu_item = Gtk.MenuItem.new_with_label(meta_entry_text) - meta_menu_item.set_sensitive(False) - meta_menu_item_label = meta_menu_item.get_child() - meta_menu_item_label.set_ellipsize(Pango.EllipsizeMode.END) - meta_menu_item_label.set_max_width_chars(20) - - actions_menu.append(meta_menu_item) - any_metadata_was_added = True - - if any_metadata_was_added: - actions_menu.append(Gtk.SeparatorMenuItem.new()) - - for ( - action_name, - action_icon_name, - action_enabled, - action_fn, - *action_fn_args, - ) in iter_actions_for_player(player): - action_menu_item = Gtk.ImageMenuItem.new_with_mnemonic(action_name) - - if action_icon_name is not None: - action_icon = Gtk.Image.new_from_icon_name( - action_icon_name, Gtk.IconSize.MENU - ) - action_menu_item.set_image(action_icon) - - action_menu_item.set_sensitive(action_enabled) - if action_fn is not None: - action_menu_item.connect( - "activate", - lambda _menu_item, action_fn, action_fn_args: action_fn( - *action_fn_args - ), - action_fn, - action_fn_args, - ) - - actions_menu.append(action_menu_item) - - player_menu_item.set_submenu(actions_menu) - root_menu.append(player_menu_item) + player_menu_item.set_submenu(actions_menu) + root_menu.append(player_menu_item) else: - menu_item = Gtk.MenuItem.new_with_label("No players were detected!") - menu_item.set_sensitive(False) - root_menu.append(menu_item) - + menu_item = Gtk.MenuItem.new_with_label("No players were detected!") + menu_item.set_sensitive(False) + root_menu.append(menu_item) root_menu.connect("selection-done", Gtk.main_quit) root_menu.connect("deactivate", Gtk.main_quit) diff --git a/scripts/query-bookmarks b/scripts/query-bookmarks index 1e8db42..fa3867f 100755 --- a/scripts/query-bookmarks +++ b/scripts/query-bookmarks @@ -16,35 +16,31 @@ import shutil import sqlite3 from typing import Optional, Tuple, Generator + sys.path.insert(1, os.path.join(os.path.dirname(__file__), "..", "script-resources")) import common_script_utils - if sys.platform == "darwin": - firefox_home: Path = Path.home() / "Library" / "Application Support" / "Firefox" + firefox_home: Path = Path.home() / "Library" / "Application Support" / "Firefox" elif os.name == "posix": - firefox_home: Path = Path.home() / ".mozilla" / "firefox" + firefox_home: Path = Path.home() / ".mozilla" / "firefox" else: - common_script_utils.platform_not_supported_error() - + common_script_utils.platform_not_supported_error() profiles_config = ConfigParser(interpolation=None) profiles_config.read(firefox_home / "profiles.ini") -installs_sections: list[str] = [ - s for s in profiles_config.sections() if s.startswith("Install") -] +installs_sections: list[str] = [s for s in profiles_config.sections() if s.startswith("Install")] if not installs_sections: - raise Exception("no Firefox installations detected!") + raise Exception("no Firefox installations detected!") if len(installs_sections) > 1: - raise Exception("multiple Firefox installations are not supported!") + raise Exception("multiple Firefox installations are not supported!") profile_dir: Path = firefox_home / profiles_config.get(installs_sections[0], "Default") # should places.sqlite be used instead? db_path: Path = profile_dir / "weave" / "bookmarks.sqlite" if not db_path.is_file(): - raise Exception("'{}' is not a file".format(db_path)) - + raise Exception("'{}' is not a file".format(db_path)) # Firefox holds a lock over the database file, so I can't connect to it even # in the readonly mode: https://stackoverflow.com/a/7857866/12005228 @@ -55,78 +51,74 @@ os.close(db_copy_fd) chooser_entries: list[Tuple[str, str, Optional[str]]] = [] try: - shutil.copyfile(db_path, db_copy_path) - db = sqlite3.connect(db_copy_path) + shutil.copyfile(db_path, db_copy_path) + db = sqlite3.connect(db_copy_path) - urls: dict[int, str] = {} - url_id: int - url: str - for url_id, url in db.execute("SELECT id, url FROM urls"): - urls[url_id] = url + urls: dict[int, str] = {} + url_id: int + url: str + for url_id, url in db.execute("SELECT id, url FROM urls"): + urls[url_id] = url - folders: dict[str, Tuple[Optional[str], str]] = {} - folder_id: str - parent_folder_id: str - folder_title: str - for folder_id, parent_folder_id, folder_title in db.execute( - "SELECT guid, parentGuid, title FROM items WHERE kind = 3 AND validity AND NOT isDeleted" - ): - folders[folder_id] = ( - parent_folder_id if parent_folder_id != folder_id else None, - folder_title, - ) + folders: dict[str, Tuple[Optional[str], str]] = {} + folder_id: str + parent_folder_id: str + folder_title: str + for folder_id, parent_folder_id, folder_title in db.execute( + "SELECT guid, parentGuid, title FROM items WHERE kind = 3 AND validity AND NOT isDeleted" + ): + folders[folder_id] = ( + parent_folder_id if parent_folder_id != folder_id else None, + folder_title, + ) - url_title: str - url_id: int - url_keyword: str - parent_folder_id: str - for url_title, url_id, url_keyword, parent_folder_id in db.execute( - "SELECT title, urlId, keyword, parentGuid FROM items WHERE kind = 1 AND validity AND NOT isDeleted" - ): - url = urls[url_id] + url_title: str + url_id: int + url_keyword: str + parent_folder_id: str + for url_title, url_id, url_keyword, parent_folder_id in db.execute( + "SELECT title, urlId, keyword, parentGuid FROM items WHERE kind = 1 AND validity AND NOT isDeleted" + ): + url = urls[url_id] - folder_path = list[str]() - parent_folder_id_2: Optional[str] = parent_folder_id - while parent_folder_id_2 is not None: - folder = folders.get(parent_folder_id_2, None) - if folder is None: - # broken folder structure? - folder_path.clear() - break - parent_folder_id_2, folder_title = folder - if folder_title is not None: - folder_path.append(folder_title) + folder_path = list[str]() + parent_folder_id_2: Optional[str] = parent_folder_id + while parent_folder_id_2 is not None: + folder = folders.get(parent_folder_id_2, None) + if folder is None: + # broken folder structure? + folder_path.clear() + break + parent_folder_id_2, folder_title = folder + if folder_title is not None: + folder_path.append(folder_title) - folder_path_str = ( - ("/" + "/".join(reversed(folder_path))) if len(folder_path) > 0 else None - ) + folder_path_str = (("/" + "/".join(reversed(folder_path))) if len(folder_path) > 0 else None) - chooser_entries.append((url_title, url, folder_path_str)) - if url_keyword is not None: - chooser_entries.append((url_keyword, url, folder_path_str)) + chooser_entries.append((url_title, url, folder_path_str)) + if url_keyword is not None: + chooser_entries.append((url_keyword, url, folder_path_str)) finally: - os.remove(db_copy_path) + os.remove(db_copy_path) def chooser_entries_iter() -> Generator[str, None, None]: - for title, url, folder_path_str in chooser_entries: - entry_items = [title, url] - if folder_path_str is not None: - entry_items.append(folder_path_str) - entry = " \u2014\u2014 ".join(entry_items) - yield entry + for title, url, folder_path_str in chooser_entries: + entry_items = [title, url] + if folder_path_str is not None: + entry_items.append(folder_path_str) + entry = " \u2014\u2014 ".join(entry_items) + yield entry -chosen_index = common_script_utils.run_chooser( - chooser_entries_iter(), prompt="bookmark" -) +chosen_index = common_script_utils.run_chooser(chooser_entries_iter(), prompt="bookmark") if chosen_index >= 0: - _title, url, _folder_path_str = chooser_entries[chosen_index] - print(url) + _title, url, _folder_path_str = chooser_entries[chosen_index] + print(url) - common_script_utils.set_clipboard(url) - common_script_utils.send_notification( - os.path.basename(__file__), "bookmark URL copied to clipboard!", url - ) + common_script_utils.set_clipboard(url) + common_script_utils.send_notification( + os.path.basename(__file__), "bookmark URL copied to clipboard!", url + ) diff --git a/scripts/random-local-ipv4 b/scripts/random-local-ipv4 index dbf02a4..a72180c 100755 --- a/scripts/random-local-ipv4 +++ b/scripts/random-local-ipv4 @@ -1,10 +1,10 @@ -#!/usr/bin/env python +#!/usr/bin/env python3 import random def randbyte() -> int: - return random.randrange(0, 256) + return random.randrange(0, 256) print("127.{}.{}.{}".format(randbyte(), randbyte(), randbyte())) From c12afbc6ff50e599139edf9e6f9e93bd83cabae6 Mon Sep 17 00:00:00 2001 From: Dmytro Meleshko Date: Mon, 26 Apr 2021 10:25:01 +0300 Subject: [PATCH 45/45] [nvim] move the flake8 config to an external file --- nvim/coc-languages/python.vim | 15 +-------------- python/flake8.ini | 12 ++++++++++++ 2 files changed, 13 insertions(+), 14 deletions(-) create mode 100644 python/flake8.ini diff --git a/nvim/coc-languages/python.vim b/nvim/coc-languages/python.vim index 336cf65..20b80e1 100644 --- a/nvim/coc-languages/python.vim +++ b/nvim/coc-languages/python.vim @@ -1,19 +1,6 @@ let g:coc_global_extensions += ['coc-pyright'] let g:coc_filetypes += ['python'] -let s:ignored_errors = [] -" Indent is not a multiple of 4 -let s:ignored_errors += ['E111'] -" Indent is not a multiple of 4 for comments -let s:ignored_errors += ['E114'] -" Indent for continuation lines is smaller than expected -let s:ignored_errors += ['E121'] -" Import not at the top of the file -let s:ignored_errors += ['E402'] -" Line too long -let s:ignored_errors += ['E501'] - -" let g:coc_user_config['pyls.plugins.pycodestyle.ignore'] = s:ignored_errors " let g:coc_user_config['python.autocomplete.showAdvancedMembers'] = v:false let g:coc_user_config['python'] = { \ 'formatting': { @@ -23,6 +10,6 @@ let g:coc_user_config['python'] = { \ 'linting': { \ 'pylintEnabled': v:false, \ 'flake8Enabled': v:true, -\ 'flake8Args': ['--ignore=' . join(s:ignored_errors, ',')], +\ 'flake8Args': ['--config=' . simplify(g:nvim_dotfiles_dir.'/../python/flake8.ini')], \ }, \ } diff --git a/python/flake8.ini b/python/flake8.ini new file mode 100644 index 0000000..b0c0191 --- /dev/null +++ b/python/flake8.ini @@ -0,0 +1,12 @@ +[flake8] +ignore = + # Indent is not a multiple of 4 + E111 + # Indent is not a multiple of 4 for comments + E114 + # Indent for continuation lines is smaller than expected + E121 + # Import not at the top of the file + E402 + # Line too long + E501