diff options
Diffstat (limited to 'vim/vimrc')
-rw-r--r-- | vim/vimrc | 1267 |
1 files changed, 666 insertions, 601 deletions
@@ -1,24 +1,8 @@ -" Tom Ryder (tejr)'s Literate Vimrc -" ================================= +" ----------------------------------- +" Tom Ryder (tejr)'s Literate Vimrc +" ----------------------------------- " -" <https://sanctum.geek.nz/cgit/dotfiles.git> -" -" This is an attempt at something like a 'literate vimrc', in the tradition of -" Donald Knuth's "literate programming". -" -" <http://www.literateprogramming.com/> -" -" It's a long file, and comments abound. If this bothers you, you can do -" something like this to strip out all the blank lines and lines with only -" comments: -" -" :g/\m^$\|^\s*"/d -" -" This file should be saved as "vimrc" in the user runtime directory. On -" Unix-like operating systems, this is ~/.vim; on Windows, it's ~/vimfiles. -" It requires Vim 7.0 or newer with +eval, with 'nocompatible'. The vimrc -" stub at ~/.vimrc on Unix or ~/_vimrc on Windows should checks that these -" conditions are met before loading this file with `:runtime vimrc`. +" Last updated: Sun, 14 Jan 2024 03:06:40 +0000 " " > And I was lifted up in heart, and thought " > Of all my late-shown prowess in the lists, @@ -27,282 +11,201 @@ " > Had heaven appeared so blue, nor earth so green, " > For all my blood danced in me, and I knew " > That I should light upon the Holy Grail. -" > -" > --Tennyson " - -" This file has characters outside the ASCII character set, which makes the -" Vim script linter vim-vint recommend declaring the file encoding with -" a :scriptencoding command. The :help for this command specifies that it -" should be done after 'encoding' is set, so we'll do that here at the top of -" the file too. -" -" On Unix, I keep LANG defined in my environment, and it's almost always set -" to a multibyte (UTF-8) locale. This informs Vim's choice of internal -" character encoding, but the default for the 'encoding' option in LANG's -" absence is "latin1". Nowadays, this is never what I want, so we'll manually -" choose "utf-8" as an encoding instead if LANG is not defined. -" -if !exists('$LANG') - set encoding=utf-8 -endif -scriptencoding utf-8 - -" With encoding handled, the next thing we'll do is ensure we have an -" environment variable MYVIM set that specifies the path to the directory -" holding user runtime files. We'll only set our own if such a variable does -" not already exist in the environment. -" -" We'll use the path nominated in the MYVIM variable as the root of our -" 'backupdir', 'directory', 'undodir', and 'viminfofile' caches, and anywhere -" else we need a sensible writable location for Vim-related files. Having it -" available as an environment variable makes assignments with :set and -" escaping much more convenient, without requiring awkward :execute wrappers. -" -" I think the absence of a variable like this is a glaring omission from Vim. -" We have VIM, VIMRUNTIME, and MYVIMRC, so why is there not an environment -" variable for the user's Vim runtime directory? It is a mystery. -" -" The default value for MYVIM will be the first path in &runtimepath. This is -" similar to what Vim does internally for situating its spelling database -" files, in the absence of a specific setting for 'spellfile'. -" -" Splitting the values of a comma-separated option like 'runtimepath' -" correctly is surprisingly complicated. The list separator for such options -" is more accurately defined as follows: -" -" > A comma not preceded by a backslash, and possibly followed by an arbitrary -" > number of spaces and commas. -" -" The pattern required for the split breaks down like this: -" -" \\ <- Literal backslash -" \@<! <- Negative lookbehind assertion; means that whatever occurred -" before this pattern, here a backslash, cannot precede what -" follows, but anything that does precede it is not removed from -" the data as part of the split delimiter -" , <- Literal comma -" [, ]* <- Any number of commas and spaces +" ---Tennyson " -" For the edge case of a blank 'runtimepath', MYVIM will be set to the empty -" string, due to the way that split() works by default without its third -" parameter {keepempty} set to false. +" > your vimrc is better than the bible " -" Once we have the path elements, we have to remove the escaping for periods, -" specifically remove up to one backslash before all periods. We do that with -" a map() over substitute(), string-eval style to accommodate older Vim before -" Funcref variables were added. +" ---@polanco@mastodon.sdf.org +" <https://mastodon.sdf.org/@polanco/104069285780040986> " -" We don't, however, have to deal with escaped backslashes, or any other -" character; you can read the source code for the ad-hoc tokenizer in -" copy_option_part() in src/misc2.c in Vim's source code and test it with some -" values of your own if you want to understand why. + +" This file is an attempt at something like a "literate vimrc", in the +" tradition of Donald Knuth's "literate programming": +" <http://www.literateprogramming.com/> " -" I'll factor this out into a global function if I ever need it anywhere else. +" The dotfiles project as part of which it is maintained is here: +" <https://dev.sanctum.geek.nz/cgit/dotfiles.git> " -" Vim, I love you, but you are really weird. +" This is a long file, and comments abound. Should this be bothersome, one +" could execute this command in Vim itself, to strip out comment blocks and +" blank lines: " -let s:runtimepath = map( - \ split(&runtimepath, '\\\@<!,[, ]*'), - \ "substitute(v:val, '\\\\,', '', 'g')" - \ ) -if !exists('$MYVIM') - let $MYVIM = s:runtimepath[0] -endif - -" Having either imported or defined a value for the MYVIM environment -" variable, we now need to ensure it's not going to cause problems for the -" rest of this file. If any of those conditions are met, we'll throw an -" explanatory error and stop reading this file. Most of the file doesn't -" depend on MYVIM, but there's not much point accommodating these edge cases. +" :g/\m^$\|^\s*"/d " - -" Firstly, MYVIM can't be an empty string. We need a real path. +" This file should be saved as `vimrc`---note no leading period---in the user +" runtime directory. On GNU/Linux, Mac OS X, and BSD, that directory is +" `~/.vim`. On Windows, it's `~/vimfiles`. It requires Vim v7.0.0 or newer, +" including the +eval feature, and with the 'compatible' option turned off. +" That's to allow line continuations. The vimrc stub at ~/.vimrc (Unix) or +" ~/_vimrc (Windows) checks that these conditions are met before loading this +" file. " -if $MYVIM ==# '' - echoerr 'Blank user runtime path' - finish -endif - -" Secondly, if MYVIM's value contains a comma, its use in comma-separated -" option values will confuse Vim into thinking more than one directory is -" being specified, splitting our value into parts. This is normal :set -" behavior. It's possible to work around this with some careful escaping or -" :execute abstraction, but it's not really worth the extra complexity for -" such a niche situation. +" The Vim script linter Vint should raise no errors, warnings, or style +" problems with this file. <https://github.com/Kuniwak/vint> " -if $MYVIM =~# ',' - echoerr 'Illegal comma in user runtime path' - finish -endif -" Thirdly, Vim v7 prior to v7.1.055 had a nasty bug with escaping with -" multiple backslash characters on the command line, and so on these older -" versions of Vim, we'll need to forbid that character in the value of MYVIM -" in order to be confident that we're stashing files in the correct path. +" We'll begin by making sure that this file and Vim are speaking the same +" language. Since it's been the future for a few years now, this file +" indulges in characters outside the ASCII character set. The presence of +" such characters prompts Vint to suggest declaring the file encoding with +" a :scriptencoding command: " -" To reproduce this bug on these older versions, try this command: +" > vim/vimrc:1:1: Use scriptencoding when multibyte char exists (see :help +" > :scriptencoding) " -" :file foo\ bar\ baz +" Furthermore, the :help for :scriptencoding specifies that :scriptencoding +" should be set *after* 'encoding'. " -" It should rename the buffer as "foo bar aaz"; note the change in the first -" letter of the last word of the filename. +" Which encoding to use? The answer is the UTF-8 encoding for Unicode, +" wherever possible. On POSIX-fearing operating systems, I define the primary +" locale environment variable $LANG to `en_NZ.UTF-8`. This informs Vim's +" choice of internal character encoding. In the absence of such a setting, +" 'encoding' defaults to `latin1` (ISO-8859-1) in most circumstances. Since +" this is almost never what I want, even if I haven't said so explicitly by +" exporting $LANG, we'll fall back to UTF-8 instead. " -" <https://github.com/vim/vim/releases/tag/v7.1.055> +" However, we need to test that the +multi_byte feature is available before +" doing any of this, because it was a compile-time feature that wasn't even +" enabled by default in Vim v7.0. Its status as an optional feature wasn't +" removed until v8.1.0733. " -if $MYVIM =~# '\\' - \ && (v:version < 701 || v:version == 701 && !has('patch55')) - echoerr 'Illegal backslash in user runtime path on Vim < v7.1.055' - finish -endif - -" Now that we have a bit more confidence in our runtime environment, set up -" all of the filetype detection, plugin, and indent hooks. -" -filetype plugin indent on - -" There are a couple of contexts in which it's useful to reload filetypes for -" the current buffer, quietly doing nothing if filetypes aren't enabled. -" We'll set up a user command named :ReloadFileType to do this, with -" a script-local function backing it. +" <https://github.com/vim/vim/releases/tag/v8.1.0733> " -function! s:ReloadFileType() abort - if exists('g:did_load_filetypes') - doautocmd filetypedetect BufRead +if has('multi_byte') + if &encoding ==# 'latin1' && !exists('$LANG') + set encoding=utf-8 endif -endfunction -command! -bar ReloadFileType - \ call s:ReloadFileType() - -" We'll also define a :ReloadVimrc command. This may seem like overkill, at -" first. Surely just `:source $MYVIMRC` would be good enough? -" -" The problem is there are potential side effects to the current buffer when -" the vimrc is reloaded. The :set commands for options like 'expandtab' and -" 'shiftwidth' may trample over different buffer-local settings that were -" specified by filetype and indent plugins. To ensure these local values are -" reinstated, we'll define the new command wrapper to issue a :ReloadFileType -" command after the vimrc file is sourced. -" -" We can't put the actual :source command into the script-local function we -" define here, because Vim would get upset that we're trying to redefine -" a function as it executes! -" -" Just to be on the safe side, we also suppress any further ##SourceCmd hooks -" from running the :source command with a :noautocmd wrapper. This is -" a defensive measure to avoid infinite recursion. It may not actually be -" necessary. -" -" We emit a faked display of the command, as well, just to make it clear that -" something has happened. The :redraw just before that message seems to be -" necessary for this message to display correctly. I'm not sure why. -" -function! s:ReloadVimrc() abort - ReloadFileType - redraw - echomsg fnamemodify($MYVIMRC, ':p:~').' reloaded' -endfunction -command! -bar ReloadVimrc - \ noautocmd source $MYVIMRC | call s:ReloadVimrc() + scriptencoding utf-8 +endif -" We'll now create or reset a group of automatic command hooks specific to -" matters related to reloading the vimrc itself, or maintaining and managing -" options set within it. +" With encoding handled, we'll turn our attention to the value of the +" 'runtimepath' option, since any scripts loaded from the paths specified +" therein control so much of the behavior of Vim. We build this path up as +" accurately as possible, accounting for Vim's unusual escaping behavior for +" these list options. +" +" One of the first things we'll need to be able to do is split the value of +" 'runtimepath' into its constituent paths. Correctly splitting the values of +" comma-separated Vim options is surprisingly complicated. It's not as simple +" as just splitting on commas, or even unescaped commas; a more accurate +" definition of the delimiter is: +" +" > Any comma not preceded by a backslash, followed by any number of spaces +" > and commas. +" +" The pattern we use for the call to split() therefore breaks down like this: +" +" \\ <- A literal backslash +" \@<! <- A negative lookbehind assertion; this means that whatever +" occurred before this pattern---in this case, a backslash--- +" cannot precede what follows, but anything that *does* precede it +" is considered part of the datum, and not the delimiter. +" , <- A literal comma +" [, ]* <- Any number of commas and spaces " -augroup vimrc - autocmd! -augroup END - -" Reload the stub vimrc, and thereby this main one, each time either of them -" is saved. This often makes errors in the file immediately apparent, and -" saves restarting Vim or running the :source command manually, which -" I almost always want to do after changing my vimrc file anyway. +" We don't, however, have to deal with backslashes before other backslashes, +" nor before any other character. If this seems wrong to you, I encourage you +" to read the source code for the ad-hoc tokenizer in copy_option_part() in +" src/misc2.c in Vim's source code. " -autocmd vimrc BufWritePost $MYVIMRC,$MYVIM/vimrc - \ ReloadVimrc - -" If Vim is new enough (v7.0.187) to support the ##SourceCmd event for -" automatic command hooks, we'll also apply a hook for that event to catch -" invocations of :source of either vimrc file, and translate that into -" reloading the stub vimrc. +" Vim, I do love you, but sometimes you're really weird. " -" <https://github.com/vim/vim/releases/tag/v7.0.187> +" We fold all that mess away into an autoloaded function option#Split(); see +" vim/autoload/option.vim. Provided a 'runtimepath' is actually set, using +" the list returned from that function, we define an environment variable +" MYVIM---to complement MYVIMRC---for ~/.vim or ~/vimfiles, by retrieving the +" first value from the 'runtimepath'. We'll use this later on in the file to +" comprehensively match expected paths for vimrc files. " -if exists('##SourceCmd') - autocmd vimrc SourceCmd $MYVIMRC,$MYVIM/vimrc - \ ReloadVimrc +if &runtimepath ==# '' + throw 'Empty ''runtimepath''' +endif +let $MYVIM = option#Split(&runtimepath)[0] + +" The next components of the runtime directory that we'll set up here will +" make use of the user's configured XDG base directories: +" +" <https://specifications.freedesktop.org/basedir-spec/basedir-spec-latest.html#variables> +" +" Note that this isn't an attempt to shoehorn all of Vim into the XDG mold; +" all of this distribution's files are still expected to be installed into +" $MYVIM, per the above. We're just leaning on XDG's conventions to provide +" separate locations for cache files and other configuration. +" +" We'll start by retrieving the list of valid paths for configuration from +" both the XDG_CONFIG_HOME and XDG_CONFIG_DIRS variables, or from their +" defaults, using autoloaded xdg# functions. +" +let s:xdgconfigdirs + \ = xdg#ConfigDirs() +let s:xdgconfighome + \ = xdg#ConfigHome() +let s:xdgdatadirs + \ = xdg#DataDirs() +let s:xdgdatahome + \ = xdg#DataHome() +let s:xdgstatehome + \ = xdg#StateHome() + +" We put XDG_CONFIG_HOME at the front of the 'runtimepath' list with insert(), +" provided it isn't empty, which is what the function returns when the +" configured path isn't absolute. This is per the standard's dictum: +" +" > All paths set in these environment variables must be absolute. If an +" > implementation encounters a relative path in any of these variables it +" > should consider the path invalid and ignore it. +" +" ---XDG Base Directory Specification v0.7 (24th November 2010), "Basics", +" <https://specifications.freedesktop.org/basedir-spec/0.7/ar01s02.html> +" +" Ours not to reason why... +" +if s:xdgconfighome !=# '' || !empty(s:xdgconfigdirs) + execute 'set runtimepath^='.option#Escape(join(map( + \ extend( + \ s:xdgconfighome !=# '' ? [s:xdgconfighome] : [], + \ s:xdgconfigdirs + \), + \ 'option#item#Escape(v:val)' + \), ',')) + execute 'set runtimepath+='.option#Escape(join(map( + \ reverse(extend( + \ s:xdgconfighome !=# '' ? [s:xdgconfighome] : [], + \ s:xdgconfigdirs + \)), + \ 'option#item#Escape(v:val.''/after'')' + \), ',')) endif -" We're going to be creating a few directories now. The code to do so in -" a compatible way is verbose, mostly because we need to check whether the -" directory already exists, even though we're specifying the special 'p' value -" for its optional {path} argument. This is because until v8.0.1708, mkdir() -" raises an error if the directory to be created already exists, even with -" a {path} of 'p', where the analogous `mkdir` shell command does not do so -" with its -p option included. -" -" <https://github.com/vim/vim/releases/tag/v8.0.1708> -" -" So, let's wrap that logic in a script-local function s:Establish(), and then -" hide it behind a user command :Establish. We'll lock down all the -" directories that we create with restrictive permissions, too. Who knows -" what secrets are in your file buffers? -" -" We set the command's tab completion to provide directory names as -" candidates, and specify that there must be only one argument, which we'll -" provide as a quoted parameter to the function. -" -function! s:Establish(name) abort - let name = expand(a:name) - let path = 'p' - let prot = 0700 - if !isdirectory(name) && exists('*mkdir') - call mkdir(name, path, prot) - endif -endfunction -command! -bar -complete=dir -nargs=1 Establish - \ call s:Establish(<f-args>) - -" Now that we have a clean means to create directories if they don't already -" exist, let's apply it for the first time to the user runtime directory. -" Note that we aren't checking whether this actually succeeded. We do want -" errors raised if there were problems with the creation, but we'll barrel on -" ahead regardless after warning the user about our failure. -" -Establish $MYVIM - -" Our next application of our new :Establish command is to configure the path -" for the viminfo metadata file, putting it in a cache subdirectory of the -" user runtime directory set in MYVIM. -" -" Using this non-default location for viminfo has the nice benefit of +" Using a logical but non-default location for viminfo has the nice benefit of " preventing command and search history from getting clobbered when something " runs Vim without using this vimrc, because such an instance will safely -" write its history to the default viminfo path instead. It also contributes -" to our aim of having everything related to the Vim runtime process in one -" dedicated directory tree. -" -" The normal method of specifying the path to the viminfo file, as applied -" here, is an addendum of the path to the 'viminfo' option with an "n" prefix. -" Vim v8.1.716 introduced a nicer way to set this with an option named -" 'viminfofile', which is too new for us to use just yet. +" write its own history to the default viminfo path instead. " -" <https://github.com/vim/vim/releases/tag/v8.1.0716> +" This is the portable way to specify the path to the viminfo file, as an +" addendum of the path to the 'viminfo' option with an `n` prefix. Vim +" v8.1.716 introduced a way to set this with an option named 'viminfofile', +" but I don't see a reason to use that. " -Establish $MYVIM/cache -set viminfo+=n$MYVIM/cache/viminfo +if s:xdgstatehome !=# '' + if !isdirectory(s:xdgstatehome) + call mkdir(s:xdgstatehome, 'p', 0700) + endif + execute 'set viminfo+='.option#Escape( + \ 'n'.s:xdgstatehome.'/viminfo' + \) +endif " Speaking of recorded data in viminfo files, the default Vim limit of a mere -" 50 entries for command and search history is pretty mean. Because I don't -" think I'm ever likely to be in a situation where remembering several -" thousand Vim commands and search patterns is going to severely tax memory, -" let alone disk space, I'd rather this limit were much higher. It's -" sometimes really handy to dig up commands from many days ago. +" 50 entries for command and search history is pretty stingy. The documented +" maximum value for this option is 10000. I used that for a while, but +" eventually found that on lower-powered machines, keeping this much command +" history slowed Vim startup down a bit much for my liking, so I've scaled +" this back to a more conservative 300. If I end up missing useful commands, +" I might try switching this on available memory instead. " -" The maximum value for the 'history' option is documented in `:help -" 'history'` as 10000, so let's just use that, and see if anything breaks. -" -set history=10000 +set history=300 " We'll now enable automatic backups of most file buffers, since that's off by " default. In practice, I don't need these backups very much, at least if I'm @@ -321,11 +224,13 @@ set history=10000 " this trailing slashes hint for a long time before 'backupdir' caught up to " them. The 'directory' option for swap files has supported it at least as " far back as v5.8.0 (2001), and 'undodir' appears to have supported it since -" its creation in v7.2.438. Even though the :help for 'backupdir' didn't say -" so, people assumed it would work the same way, when in fact Vim simply -" ignored it until v8.1.0251. I don't want to add the slashes to the option -" value in older versions of Vim where they don't do anything, so we'll check -" the version ourselves to see if there's any point in including them. +" its creation in v7.2.438. Even though `:help 'backupdir'` didn't say so, +" people assumed it would work the same way, when in fact Vim simply ignored +" it until v8.1.0251. +" +" I don't want to add the slashes to the option value in older versions of Vim +" where they don't do anything, so we'll check the version ourselves to see if +" there's any point in including them. " " <https://github.com/vim/vim/releases/tag/v8.1.0251> " @@ -333,71 +238,196 @@ set history=10000 " 'backupfullname', 'swapfilefullname' would have been clearer. " set backup -Establish $MYVIM/cache/backup -if has('patch-8.1.251') - set backupdir^=$MYVIM/cache/backup// -else - set backupdir^=$MYVIM/cache/backup +if s:xdgstatehome !=# '' + if !isdirectory(s:xdgstatehome.'/backup') + call mkdir(s:xdgstatehome.'/backup', 'p', 0700) + endif + execute 'set backupdir^='.option#Escape(option#item#Escape( + \ s:xdgstatehome.'/backup'.(patch#('8.1.251') ? '//' : '') + \)) endif " Files in certain directories on Unix-compatible filesystems should not be " backed up, for security reasons. This is particularly important if editing -" temporary files created by sudoedit(8). On Unix-like systems, we here add -" a few paths to the default value of 'backupskip' in order to prevent the -" creation of such undesired backup files. -" -" * /dev/shm: RAM disk, default path for password-store's temporary files -" * /usr/tmp: Hard-coded path for sudoedit(8) [1/2] -" * /var/tmp: Hard-coded path for sudoedit(8) [2/2] -" -" Prior to v8.1.1519, Vim didn't check patterns added to 'backupskip' for -" uniqueness, so adding the same path repeatedly resulted in duplicate strings -" in the value. This was due to the absence of the P_NODUP flag for the -" option's definition in src/option.c in the Vim source code. If we're using -" a version older than v8.1.1519, we'll need to explicitly reset 'backupskip' -" to its default value before adding patterns to it, so that reloading this -" file doesn't stack up multiple copies of any added paths. -" -" <https://github.com/vim/vim/releases/tag/v8.1.1519> +" temporary files created by sudoedit(8). We add a few path patterns to the +" default value of 'backupskip' here, in order to prevent the creation of such +" undesired backup files. " if has('unix') - if !has('patch-8.1.1519') + + " Prior to v8.1.1519, Vim didn't check patterns added to 'backupskip' for + " uniqueness, so adding the same path repeatedly resulted in duplicate + " strings in the value. This was due to the absence of the P_NODUP flag for + " the option's definition in src/option.c in the Vim source code. If we're + " using a version older than v8.1.1519, we'll need to explicitly reset + " 'backupskip' to its default value before adding patterns to it, so that + " reloading this file doesn't stack up multiple copies of any added paths. + " + " <https://github.com/vim/vim/releases/tag/v8.1.1519> + " + if !patch#('8.1.1519') set backupskip& endif - set backupskip^=/dev/shm/*,/usr/tmp/*,/var/tmp/* + + " Typical temporary file locations + "" RAM disk, default path for password-store's temporary files + set backupskip+=/dev/shm/* + "" Hard-coded paths for sudoedit + set backupskip+=/usr/tmp/*,/var/tmp/* + + " Per-repository temporary files for Git + "" Commit and tag messages + set backupskip+=*/*.git/?*_EDITMSG + "" Edited patches + set backupskip+=*/*.git/ADD_EDIT.patch + "" Email messages + set backupskip+=*/*.git/.gitsendemail.msg.* + "" Interactive rebase manifests + set backupskip+=*/*.git/rebase-merge/git-rebase-todo + + " systemd user manager unit files + "" Full unit files + set backupskip+=*/systemd/user/.#?*.?*???????????????? + "" Per-unit overrides + set backupskip+=*/systemd/user/?*.?*.d/.#override.conf???????????????? + endif " Keep swap files for file buffers in a dedicated directory, rather than the " default of writing them to the same directory as the buffer file. Add two " trailing slashes to the path to prompt Vim to use the full escaped path in " its name, in order to avoid filename collisions, since the 'directory' -" option has supported that hint for much longer than 'backupdir' has. We -" apply :Establish to attempt to create the path first, if needed. +" option has supported that hint for much longer than 'backupdir' has. " -Establish $MYVIM/cache/swap -set directory^=$MYVIM/cache/swap// +if s:xdgstatehome !=# '' + if !isdirectory(s:xdgstatehome.'/swap') + call mkdir(s:xdgstatehome.'/swap', 'p', 0700) + endif + execute 'set directory^='.option#Escape(option#item#Escape( + \ s:xdgstatehome.'/swap//' + \)) +endif " Keep tracked undo history for files permanently, in a dedicated cache " directory, so that the u/:undo and CTRL-R/:redo commands will work between " Vim invocations. " " The 'undodir' option has the same structure as 'backupdir' and 'directory'; -" if we have a user runtime directory, create a sub-subdirectory within it -" dedicated to the undo files cache. Note also the trailing double-slash as -" a signal to Vim to use the full path of the original file in its undo file -" cache's name. +" if we have a user cache directory, create a subdirectory within it dedicated +" to the undo files cache. Note also the trailing double-slash as a signal to +" Vim to use the full path of the original file in its undo file cache's name. " " Support for these persistent undo file caches was not released until v7.3.0, " so we need to check for the feature's presence before we enable it. " -if has('persistent_undo') - Establish $MYVIM/cache/undo +if s:xdgstatehome !=# '' && has('persistent_undo') set undofile - set undodir^=$MYVIM/cache/undo// + if !isdirectory(s:xdgstatehome.'/undo') + call mkdir(s:xdgstatehome.'/undo', 'p', 0700) + endif + execute 'set undodir^='.option#Escape(option#item#Escape( + \ s:xdgstatehome.'/undo//' + \)) +endif + +" Set up a directory for files generated by :mkview. To date, I think I have +" used this twice in my life, but may as well be consistent with the other +" directories of this type. This isn't a comma-separated list like the others +" ('backupdir', 'directory', 'spell', 'undodir') +" +if s:xdgstatehome !=# '' && has('mksession') + if !isdirectory(s:xdgstatehome.'/view') + call mkdir(s:xdgstatehome.'/view', 'p', 0700) + endif + execute 'set viewdir='.option#Escape(option#item#Escape( + \ s:xdgstatehome.'/view' + \)) +endif + +" Now that we have a bit more confidence in our runtime environment, set up +" all of the filetype detection, plugin, and indent hooks. +" +filetype plugin indent on + +" There are a couple of contexts in which it's useful to reload filetypes for +" the current buffer, quietly doing nothing if filetypes aren't enabled. +" We'll set up a user command named :ReloadFileType to do this, with +" an autoloaded function backing it. +" +command! -bar ReloadFileType + \ call reload#FileType() + +" We'll also define a :ReloadVimrc command. This may seem like overkill, at +" first. Surely just `:source $MYVIMRC` would be good enough? +" +" The problem is there are potential side effects to the current buffer when +" the vimrc is reloaded. The global :set commands for some options may +" trample over different buffer-local settings that were specified by filetype +" and indent plugins. To ensure these local values are reinstated, we'll +" define the new command wrapper around an autoloaded function that itself +" issues a :ReloadFileType command after the vimrc file is sourced. +" +command! -bar ReloadVimrc + \ call reload#Vimrc() + +" We'll now create or reset a group of automatic command hooks specific to +" matters related to reloading the vimrc itself, or maintaining and managing +" options set within it. +" +augroup vimrc + autocmd! +augroup END + +" Reload the stub vimrc, and thereby this main one, each time either of them +" is written. This often makes errors in the file immediately apparent, and +" saves restarting Vim or running the :source command manually, which I almost +" always want to do after changing my vimrc file anyway. +" +autocmd vimrc BufWritePost $MYVIMRC,$MYVIM/vimrc + \ ReloadVimrc + +" If Vim is new enough (v7.0.187) to support the ##SourceCmd event for +" automatic command hooks, we'll also apply a hook for that event to catch +" invocations of :source of either vimrc file, and translate that into +" reloading the stub vimrc. +" +" <https://github.com/vim/vim/releases/tag/v7.0.187> +" +if exists('##SourceCmd') + autocmd vimrc SourceCmd $MYVIMRC,$MYVIM/vimrc + \ ReloadVimrc +endif + +" For spelling, use New Zealand English by default, but later on we'll +" configure a leader mapping to switch to United States English, since I so +" often have to write for Yankees. +" +set spelllang=en_nz + +" Spell checking includes optional support for catching lower case letters at +" the start of sentences, and defines a pattern in 'spellcapcheck' for the end +" of a sentence. The default is pretty good, but with two-spacing with +" 'cpoptions' including `J` and 'formatoptions' including `p` as set later in +" this file, we can be less ambiguous in this pattern. We require two +" consecutive spaces, a newline, a carriage return, or a tab to mark the end +" of a sentence. This means that we could make abbreviations like "i.e. +" something" without flagging "something" as a spelling error. +" +set spellcapcheck=[.?!]\\%(\ \ \\\|[\\n\\r\\t]\\) + +" When spell-checking snakeCased or CamelCased words, treat every upper-case +" character in a word text object as the beginning of a new word for separate +" spell-checking. At the time of writing, this is still a very new option +" (v8.2.0953, June 2020). +" +" <https://github.com/vim/vim/releases/tag/v8.2.0953> +" +if exists('+spelloptions') + set spelloptions+=camel endif " For word completion in insert mode with CTRL-X CTRL-K, or if 'complete' -" includes the 'k' flag, the 'dictionary' option specifies the path to the +" includes the `k` flag, the 'dictionary' option specifies the path to the " system word list. This makes the dictionary completion work consistently, " even if 'spell' isn't set at the time to coax it into using 'spellfile'. " @@ -408,33 +438,37 @@ endif " At some point, I may end up having to set this option along with 'spellfile' " a bit more intelligently to ensure that spell checking and dictionary " function consistently, and with reference to the same resources. For the -" moment, I've just added another entry referring to a directory in the user -" runtime directory, but I don't have anything distinct to put there yet. -" -" In much the same way, we add an expected path to a thesaurus, for completion -" with CTRL-X CTRL-T in insert mode, or with 't' added to 'completeopt'. The -" thesaurus data isn't installed as part of the default `install-vim` target -" in tejr's dotfiles, but it can be retrieved and installed with -" `install-vim-thesaurus`. -" -" I got the thesaurus itself from the link in the :help for 'thesaurus' in -" v8.1. It's from WordNet and MyThes-1. I maintain a mirror on my own -" website that the Makefile recipe attempts to retrieve. I had to remove the -" first two metadata lines from thesaurus.txt, as Vim appeared to interpret -" them as part of the body data. -" -" Extra checks for appending the 'dictionary' and 'thesaurus' paths in MYVIM -" need to be made, because the P_NDNAME property is assigned to them, which -" enforces a character blacklist in the option value. We check for the same -" set of blacklist characters here, and if the MYVIM path offends, we just -" skip the setting entirely, rather than throwing cryptic errors at the user. -" None of them are particularly wise characters to have in paths, anyway, -" legal though they may be on Unix filesystems. +" moment, I've just added additional entries referring to the user's data +" directory. " set dictionary^=/usr/share/dict/words -if $MYVIM !~# '[*?[|;&<>\r\n]' - set dictionary^=$MYVIM/ref/dictionary.txt - set thesaurus^=$MYVIM/ref/thesaurus.txt +if s:xdgdatahome !=# '' || !empty(s:xdgdatadirs) + execute 'set dictionary^='.option#Escape(join(map( + \ extend( + \ s:xdgdatahome !=# '' ? [s:xdgdatahome] : [], + \ s:xdgdatadirs + \), + \ 'option#item#Escape(v:val.''/dictionary.txt'')' + \), ',')) +endif + +" In much the same way as 'dictionary', we add an expected path to +" a thesaurus, for completion with CTRL-X CTRL-T in insert mode, or with `t` +" added to 'completeopt'. The thesaurus data isn't installed as part of the +" default `install-vim` target in tejr's dotfiles, but a decent one can be +" retrieved from my website at <https://sanctum.geek.nz/ref/thesaurus.txt>. +" I got this from the link in the :help for 'thesaurus' in v8.1. It's from +" WordNet and MyThes-1. I had to remove the first two metadata lines from +" thesaurus.txt, as Vim appeared to interpret them as part of the body data. +" +if s:xdgdatahome !=# '' || !empty(s:xdgdatadirs) + execute 'set thesaurus^='.option#Escape(join(map( + \ extend( + \ s:xdgdatahome !=# '' ? [s:xdgdatahome] : [], + \ s:xdgdatadirs + \), + \ 'option#item#Escape(v:val.''/thesaurus.txt'')' + \), ',')) endif " Next, we'll modernize a little in adjusting some options with old @@ -462,42 +496,13 @@ endif " " The default value for the 'path' option is similar, in that it has an aged " default; this option specifies directories in which project files and -" includes can be unearthed by navigation commands like 'gf'. Specifically, +" includes can be unearthed by navigation commands like `gf`. Specifically, " its default value comprises /usr/include, which is another C default. Let's " get rid of that, too. " set comments= commentstring= define= include= set path-=/usr/include -" Next, we'll adjust the global indentation settings. In general and as -" a default, I prefer spaces to tabs, and I like to use four of them, for -" a more distinct visual structure. Should you happen to disagree with this, -" I cordially invite you to fite me irl. -" -" <https://sanctum.geek.nz/blinkenlights/spaces.webm> -" -" Filetype indent plugins will often refine these settings for individual -" buffers. For example, 'expandtab' is not appropriate for Makefiles, nor for -" the Go programming language. For another, two-space indents are more -" traditional for Vim script. -" -set autoindent " Use indent of previous line on new lines -set expandtab " Insert spaces when tab key is pressed in insert mode -set shiftwidth=4 " Indent command like < and > use four-space indents - -" Apply 'softtabstop' option to make a tab key press in insert mode insert the -" same number of spaces as defined by the indent depth in 'shiftwidth'. If -" Vim is new enough to support it (v7.3.693), apply a negative value to do -" this dynamically if 'shiftwidth' changes. -" -" <https://github.com/vim/vim/releases/tag/v7.3.693> -" -if v:version > 730 || v:version == 730 && has('patch693') - set softtabstop=-1 -else - let &softtabstop = &shiftwidth -endif - " Relax traditional vi's harsh standards over what regions of the buffer can " be removed with backspace in insert mode. While this admittedly allows bad " habits to continue, since insert mode by definition is not really intended @@ -551,6 +556,14 @@ if exists('+breakindent') set breakindent endif +" I use `cd` with no argument to go $HOME in the shell all the time. +" Analogous behavior for Vim with :cd makes sense to me. I can use :pwd (or +" my <Leader>g mapping) if I want to see where I am. +" +if exists('+cdhome') + set cdhome +endif + " Rather than rejecting operations like :write or :saveas when 'readonly' is " set or in other situations in which data might be lost, Vim should give me " a prompt to allow me to confirm that I know what I'm doing. @@ -561,7 +574,7 @@ set confirm " if it's going to be followed by another key code, despite this being how the " function keys and Meta/Alt modifier are implemented for many terminal types. " Otherwise, if I press Escape, there's an annoying delay before 'showmode' -" stops showing '--INSERT--'. +" stops showing `--INSERT--`. " " This breaks the function keys and the Meta/Alt modifier in insert mode in " most or maybe all of the terminals I use, but I don't want those keys in @@ -569,34 +582,21 @@ set confirm " set noesckeys -" By default, I prefer that figuring out where a region of text to fold away -" should be done by the indent level of its lines, since I tend to be careful -" about my indentation even in languages where it has no semantic meaning. +" Always start with 'foldlevel' set high enough to have all folds of any +" practical depth open by default. " -set foldmethod=indent - -" That said, I don't want any of these indent-based folds to start off closed. -" Therefore, we set the depth level at which folds should automatically start -" as closed to a rather high number, per the documentation's recommendations. -" -" I think of a Vim window with a file buffer loaded into it as -" a two-dimensional, planar view of the file, so that moving down one screen -" line means moving down one buffer line, at least when 'wrap' is unset. -" Folds break that mental model, and so I usually enable them explicitly only -" when I'm struggling to grasp some code with very long functions or loops. -" -set foldlevelstart=99 +set foldlevel=256 " Automatic text wrapping options using flags in the 'formatoptions' option -" begin here. I rely on the filetype plugins to set the 't' and 'c' flags for +" begin here. I rely on the filetype plugins to set the `t` and `c` flags for " this option to configure whether text or comments should be wrapped, as " appropriate for the document type or language, and so I don't mess with " either of those flags here. " If a line is already longer than 'textwidth' would otherwise limit when " editing of that line begins in insert mode, don't suddenly automatically -" wrap it; I'll break it apart myself with a command like 'gq'. This doesn't -" seem to stop paragraph reformatting with 'a', if that's set. +" wrap it; I'll break it apart myself with a command like `gq`. This doesn't +" seem to stop paragraph reformatting with `a`, if that's set. " set formatoptions+=l @@ -611,8 +611,8 @@ set formatoptions+=1 " If the filetype plugins have correctly described what the comment syntax for " the buffer's language looks like, it makes sense to use that to figure out " how to join lines within comments without redundant comment syntax cropping -" up. For example, with this set, joining lines in this very comment with 'J' -" would remove the leading '"' characters. +" up. For example, with this set, joining lines in this very comment with `J` +" would remove the leading `"` characters. " " This 'formatoptions' flag wasn't added until v7.3.541. Because we can't " test for the availability of option flags directly, we resort to a version @@ -622,23 +622,23 @@ set formatoptions+=1 " " <https://github.com/vim/vim/releases/tag/v7.3.541> " -if v:version > 730 || v:version == 730 && has('patch541') +if patch#('7.3.541') set formatoptions+=j endif -" A momentary digression here into the doldrums of 'cpoptions'--after +" A momentary digression here into the doldrums of 'cpoptions'---after " staunchly opposing it for years, I have converted to two-spacing. You can " blame Steve Losh: " " <http://stevelosh.com/blog/2012/10/why-i-two-space/> " -" Consequently, we specify that sentence objects for the purposes of the 's' -" text object, the '(' and ')' sentence motions, and formatting with the 'gq' +" Consequently, we specify that sentence objects for the purposes of the `s` +" text object, the `(` and `)` sentence motions, and formatting with the 'gq' " command must be separated by *two* spaces. One space does not suffice. " " My defection to the two-spacers is also the reason I now leave 'joinspaces' " set, per its default, so that two spaces are inserted when consecutive -" sentences separated by a line break are joined onto one line by the 'J' +" sentences separated by a line break are joined onto one line by the `J` " command. " set cpoptions+=J @@ -651,18 +651,18 @@ set cpoptions+=J " If we're using two-period spacing for sentences, Vim can interpret the " different spacing to distinguish between the two types, and can thereby " avoid breaking a line just after an abbreviating period. For example, the -" two words in "Mr. Moolenaar" should never be split apart, preventing -" confusion on the reader's part lest the word "Mr." look too much like the -" end of a sentence, and also preserving the semantics of that same period for -" subsequent reformatting; its single-space won't get lost. +" two words in "Mr. Moolenaar" should never be split apart, lest the +" abbreviation "Mr." look too much like the end of a sentence. This also +" preserves the semantics of that same period for subsequent reformatting; its +" single-space won't get lost. " -" So, getting back to our 'formatoptions' settings, that is what the 'p' flag +" So, getting back to our 'formatoptions' settings, that is what the `p` flag " does. I wrote the patch that added it, after becoming envious of an " analogous feature during an ill-fated foray into GNU Emacs usage. " " <https://github.com/vim/vim/releases/tag/v8.1.1523> " -if has('patch-8.1.728') +if patch#('8.1.728') set formatoptions+=p endif @@ -678,22 +678,22 @@ if has('gui_running') set guioptions+=M endif -" By default, Vim doesn't allow a file buffer to have unsaved changes if it's -" not displayed in a window. Setting this option removes that restriction so -" that buffers can remain in a modified state while not actually displayed -" anywhere. +" By default, Vim doesn't allow a file buffer to have unwritten changes if +" it's not displayed in a window. Setting this option removes that +" restriction so that buffers can remain in a modified state while not +" actually displayed anywhere. " " This option is set in almost every vimrc I read; it's so pervasive that " I sometimes see comments expressing astonishment or annoyance that it isn't " set by default. However, I didn't actually need this option for several " years of Vim usage, because I instinctively close windows onto buffers only -" after the buffers within them were saved anyway. +" after the buffers within them have been written anyway. " " However, the option really is required for batch operations performed with -" commands like :argdo or :bufdo, because Vim won't otherwise tolerate unsaved -" changes to a litany of buffers that are not displayed in any window. After -" I started using such command maps a bit more often, I realized I finally had -" a reason to turn this on permanently. +" commands like :argdo or :bufdo, because Vim won't otherwise tolerate +" unwritten changes to a litany of buffers that are not displayed in any +" window. After I started using such command maps a bit more often, +" I realized I finally had a reason to turn this on permanently. " set hidden @@ -743,7 +743,7 @@ set listchars+=nbsp:+ " Non-breaking spaces " precedes: Signals presence of unwrapped text to screen left " « U+00BB LEFT-POINTING DOUBLE ANGLE QUOTATION MARK " -" Failing that, '<' and '>' will do the trick. +" Failing that, `<` and `>` will do the trick. " if has('multi_byte_encoding') set listchars+=extends:»,precedes:« @@ -788,7 +788,12 @@ set noruler set sessionoptions-=localoptions " No buffer options or mappings set sessionoptions-=options " No global options or mappings -" The 'I' flag for the 'shortmess' option prevents the display of the Vim +" Turn 'showcmd' off if a system vimrc has been rude enough to set it; I don't +" like how it can interfere with the display of longer lines. +" +set noshowcmd + +" The `I` flag for the 'shortmess' option prevents the display of the Vim " startup screen with version information, :help hints, and donation " suggestion. After I registered Vim and donated to Uganda per the screen's " plea, I didn't feel bad about turning this off anymore. Even with this @@ -801,6 +806,15 @@ set sessionoptions-=options " No global options or mappings " set shortmess+=I +" Scrolling by screen line rather than file line makes sense to me. Turn the +" option to do so on, if it's there. This only works with mouse scrolling, +" which I don't use, and with CTRL-E, CTRL-Y, which I should be using more +" anyway. +" +if exists('+smoothscroll') + set smoothscroll +endif + " I find the defaults of new windows opening above or to the left of the " previous window too jarring, because I'm used to both the i3 window manager " and the tmux terminal multiplexer doing it the other way around, in reading @@ -809,22 +823,11 @@ set shortmess+=I " set splitbelow splitright -" Limit the number of characters per line that syntax highlighting will -" attempt to match. This is as much an effort to encourage me to break long -" lines and do hard wrapping correctly as it is for efficiency. -" -set synmaxcol=500 - -" Vim has an internal list of terminal types that support using smoother -" terminal redrawing, and for which 'ttyfast' is normally set, described in -" `:help 'ttyfast'`. That list includes most of the terminals I use, but -" there are a couple more for which the 'ttyfast' option should apply: the -" windows terminal emulator PuTTY, and the terminal multiplexer tmux, both of -" which I use heavily. +" I don't like the titles of my terminal windows being changed, especially +" when changing them back doesn't actually work. Just leave them alone, Vim, +" even if you think you can handle it. " -if &term =~# '^putty\|^tmux' - set ttyfast -endif +set notitle " We really don't want a mouse; while I use it a lot for cut and paste in X, " it just gets in the way if the tool running in the terminal tries to use it @@ -885,7 +888,7 @@ set wildmode=list:longest,full " giving patterns for the top 100 alphanumeric extensions for files from the " running user's home directory: " -" $ (LC_ALL=C find "$HOME" ! -type d -name '*.?*' -exec \ +" $ (LC_ALL=C ; find "$HOME" ! -type d -name '*.?*' -exec \ " sh -c 'for fn ; do " ext=${fn##*.} " case $ext in @@ -898,7 +901,7 @@ set wildmode=list:longest,full " " I turned out to have rather a lot of .html and .vim files. " -" If you're scoffing at that and thinking "I could write a much simpler one", +" If you're scoffing at that and thinking "I could write a much simpler one," " please do so, and send it to me at <tom@sanctum.geek.nz> to have yours put " in here instead, with appropriate credit. Don't forget to handle more than " ARG_MAX files, include filenames with newlines, and that the -z or -0 null @@ -906,11 +909,6 @@ set wildmode=list:longest,full " " <https://mywiki.wooledge.org/UsingFind#Complex_actions> " -" It's tempting to put the list of patterns here into a separate file--or at -" least into a more readily editable intermediate list variable--rather than -" the minor maintenance hassle it presently constitutes in this compact form. -" I'm not sure whether I'll do that just yet. -" set wildignore=*~,#*#,*.7z,.DS_Store,.git,.hg,.svn,*.a,*.adf,*.asc,*.au,*.aup \,*.avi,*.bin,*.bmp,*.bz2,*.class,*.db,*.dbm,*.djvu,*.docx,*.exe \,*.filepart,*.flac,*.gd2,*.gif,*.gifv,*.gmo,*.gpg,*.gz,*.hdf,*.ico @@ -919,18 +917,20 @@ set wildignore=*~,#*#,*.7z,.DS_Store,.git,.hg,.svn,*.a,*.adf,*.asc,*.au,*.aup \,*.s3m,*.sdbm,*.sqlite,*.swf,*.swp,*.tar,*.tga,*.ttf,*.wav,*.webm,*.xbm \,*.xcf,*.xls,*.xlsx,*.xpm,*.xz,*.zip -" Allow me to be lazy and type a path to complete on the Ex command line in -" all-lowercase, and transform the consequent completion to match the -" appropriate case, like the Readline setting completion-ignore-case can be -" used for GNU Bash. +" Allow me to type a path to complete on the Ex command line in all-lowercase, +" and transform the consequent completion to match the appropriate case, like +" the Readline setting `completion-ignore-case` can be used for GNU Bash. +" +" When completing filenames on the command line, choose completions without +" regard to case, allowing me the ease of typing a partial path in +" all-lowercase. This is very similar to the Readline setting +" `completion-ignore-case` used for Bash. " -" As far as I can tell, despite its name, the 'wildignore' case option doesn't -" have anything to do with the 'wildignore' option, and so files that would -" match any of those patterns only with case insensitivity implied will still -" be candidates for completion. +" The 'wildignorecase' option is not related to the similarly-named +" 'wildignore' option, nor to the +wildmenu feature. " -" The option wasn't added until v7.3.72, so we need to check it exists before -" we try to set it. +" We need to check that the 'wildignorecase' option exists before we set it, +" because it wasn't added to Vim until v7.3.72: " " <https://github.com/vim/vim/releases/tag/v7.3.072> " @@ -970,26 +970,33 @@ endif " background. For any other color scheme, turn the option off, because it " almost always stands out too much for my liking. " +" You'd think the pattern here could be used to match the color scheme name, +" and it can be---after patch v7.4.108, when Christian Brabandt fixed it. +" Until that version, it matched against the current buffer name, so we're +" forced to have an explicit test in the command instead. +" +" <https://github.com/vim/vim/releases/tag/v7.4.108> +" autocmd vimrc ColorScheme * - \ set nocursorline -autocmd vimrc ColorScheme sahara - \ set cursorline + \ call colorscheme#UpdateCursorline(g:colors_name, ['sahara']) -" We'll have Vim try to use my 'sahara' fork of the 'desert256' color scheme. -" If we fail to load the color scheme, for whatever reason, suppress the -" error, and ensure a dark background for the default color scheme. +" Use `dark` as my default value for 'background', in the absence of an +" environment variable COLORFGBG or a response in v:termrbgresp that would set +" it specifically. " -" There's also a very simple grayscale color scheme I occasionally use instead -" called 'juvenile', which is included as a Git submodule with this dotfiles -" distribution. +if !exists('$COLORFGBG') && !get(v:, 'termrbgresp') + set background=dark +endif + +" If the background seems to be dark, and I have either the GUI or a 256 color +" terminal, and my custom sahara.vim color scheme looks to be available, load +" it. " -try +if &background ==# 'dark' + \ && (has('gui_running') || str2nr(&t_Co) >= 256) + \ && globpath(&runtimepath, 'colors/sahara.vim') !=# '' colorscheme sahara -catch - if &background !=# 'dark' - set background=dark - endif -endtry +endif " My mapping definitions begin here. I have some general personal rules for " approaches to mappings: @@ -1010,7 +1017,7 @@ endtry " extent possible, and avoid "doing more" in insert mode besides merely " inserting text as it's typed. " -" * Avoid key chords with Ctrl in favor of leader keys. +" * Avoid key chords with CTRL in favor of leader keys. " " * Never use Alt/Meta key chords; the terminal support for them is just too " confusing and flaky. @@ -1026,6 +1033,13 @@ endtry " many of these. " +" I use Mosh (the mobile shell) a lot, which uses CTRL-^ as its escape key. +" That shadows Vim's shortcut to switch to the alternate buffer. Map +" <Backspace> to do that instead. +" +nnoremap <Backspace> + \ <C-^> + " I find the space bar's default behavior in normal mode of moving right one " character to be useless. Instead, I remap it to be a lazy way of paging " through the argument list buffers, scrolling a page until the last line of @@ -1035,48 +1049,8 @@ endtry " nnoremap <expr> <Space> \ line('w$') < line('$') - \ ? "\<PageDown>" - \ : ":\<C-U>next\<CR>" - -" I hate CTRL-C's default insert mode behavior. It ends the insert session -" without firing the InsertLeave event for automatic command hooks. Why would -" anyone want that? It breaks plugins that hinge on mirrored functionality -" between the InsertEnter and InsertLeave events, and doesn't otherwise differ -" from Escape or :stopinsert. Even worse, people think it's a *synonym* for -" Escape, and use it because it's easier to reach than the Escape key or -" CTRL-[. Terrible! -" -" Instead, I apply a custom plugin named insert_cancel.vim to make it cancel -" the current insert operation; that is, if the buffer has changed at all -" since the start of the insert operation, pressing CTRL-C will reverse it, -" while ending insert mode and firing InsertLeave as normal. This makes way -" more sense to me, and I use it all the time now. -" -" <https://sanctum.geek.nz/cgit/vim-insert-cancel.git/about/> -" -" You might think on a first look, as I did, that a plugin is overkill, and -" that a mapping like this would be all that's required: -" -" :inoremap <C-C> <Esc>u -" -" Indeed, it *mostly* works, but there are some subtle problems with it. The -" primary issue is that if you didn't make any changes during the insert mode -" session that you're terminating, it *still* reverses the previous change, -" which will be something else entirely that you probably *didn't* mean to be -" undone. The plugin's way of working around this and the other shortcomings -" of the simple mapping above is not too much more complicated, but it was not -" easy to figure out. -" -" At any rate, we only want to establish the mapping if we can expect the -" plugin to load, so test that 'loadplugins' is set and that the plugin file -" exists with the expected filename. -" -" If the plugin isn't available, I just abandon CTRL-C to continue its -" uselessness. -" -if &loadplugins && globpath(&runtimepath, 'plugin/insert_cancel.vim') !=# '' - imap <C-C> <Plug>(InsertCancel) -endif + \ ? "\<PageDown>" + \ : ":\<C-U>next\<CR>" " I often can't remember (or guess) digraph codes, and want to look up how to " compose a specific character that I can name, at least in part. The table @@ -1100,7 +1074,7 @@ endif " > Í I' LATIN CAPITAL LETTER I WITH ACUTE " > ...etc... " -" <https://sanctum.geek.nz/cgit/vim-digraph-search.git/about/> +" <https://dev.sanctum.geek.nz/cgit/vim-digraph-search.git/about/> " " This leaves you in insert mode, ready to hit CTRL-K one more time and then " type the digraph that you've hopefully found. @@ -1109,7 +1083,8 @@ endif " checking that the plugin's available before we map to it; it'll just quietly " do nothing. " -imap <C-K><C-K> <Plug>(DigraphSearch) +imap <C-K><C-K> + \ <Plug>(DigraphSearch) " I end up hitting CTRL-L to clear or redraw the screen in interactive shells " and tools like Mutt and Vim pretty often. It feels natural to me to stack @@ -1132,33 +1107,36 @@ nnoremap <C-L> " for this, but it didn't work. Maybe i_CTRL-O doesn't respect mappings. " I couldn't find any documentation about it. " -inoremap <C-L> <C-O>:execute "normal \<C-L>"<CR> +inoremap <C-L> + \ <C-O>:execute "normal \<C-L>"<CR> -" We use :vnoremap here rather than :xnoremap and thereby make the mapping -" apply to select mode as well, because CTRL-L doesn't reflect a printable -" character, and so we may as well make it work, even though I don't actually -" use select mode directly. +" We use :vmap here rather than :xmap to have the mapping applied for select +" mode as well as visual mode. This is because CTRL-L doesn't reflect +" a printable character, and so we don't shadow anything by making it work, +" even though I don't actually use select mode directly very much. " -vmap <C-L> <Esc><C-L>gv +vmap <C-L> + \ <Esc><C-L>gv -" By default, the very-useful normal mode command '&' that repeats the +" By default, the very-useful normal mode command `&` that repeats the " previous :substitute command doesn't preserve the flags from that " substitution. I'd prefer it to do so, like the :&& command does, and it's " easily remapped for both normal and visual mode, so let's just do it. " -nnoremap & - \ :&&<CR> -xnoremap & +noremap & \ :&&<CR> +ounmap & +sunmap & -" I really like using the '!' command in normal mode as an operator to filter +" I really like using the `!` command in normal mode as an operator to filter " text through a shell command. It always bugged me a little that there " didn't seem to be an analogue for a motion to filter text through an " internal command like :sort, so I wrote one. " -" <https://sanctum.geek.nz/cgit/vim-colon-operator.git/about/> +" <https://dev.sanctum.geek.nz/cgit/vim-colon-operator.git/about/> " -nmap g: <Plug>(ColonOperator) +nmap g: + \ <Plug>(ColonOperator) " I used Tim Pope's unimpaired.vim plugin for ages, and I liked some of these " bracket pair mappings, so I've carried a few of the simpler ones over. All @@ -1192,10 +1170,12 @@ nnoremap ]l " put_blank_lines.vim. These use operator functions so that they're " repeatable without repeat.vim. They accept count prefixes, too. " -" <https://sanctum.geek.nz/cgit/vim-put-blank-lines.git/about/> +" <https://dev.sanctum.geek.nz/cgit/vim-put-blank-lines.git/about/> " -nmap [<Space> <Plug>(PutBlankLinesAbove) -nmap ]<Space> <Plug>(PutBlankLinesBelow) +nmap [<Space> + \ <Plug>(PutBlankLinesAbove) +nmap ]<Space> + \ <Plug>(PutBlankLinesBelow) " We're on to the leader maps, now. It's difficult to know in what order to " describe and specify these. I used to have them in alphabetical order, but @@ -1211,6 +1191,16 @@ nmap ]<Space> <Plug>(PutBlankLinesBelow) let mapleader = '\' let maplocalleader = ',' +" If the local leader is a comma, map double-tap comma to its original +" function in the relevant modes so that I can still use it quickly without +" relying on mapping 'timeout'. +" +if maplocalleader ==# ',' + noremap ,, + \ , + sunmap ,, +endif + " Let's start with some simple ones; these ones all just toggle a boolean " option, and print its new value. They're dirt simple to specify, and don't " require any plugins. @@ -1221,66 +1211,73 @@ let maplocalleader = ',' " 'cursorline' is always off when in any visual mode, including block mode, " where it actually might have been really handy. +"" Leader,TAB toggles automatic indentation based on the previous line +nnoremap <Leader><Tab> + \ :<C-U>set autoindent! autoindent?<CR> +"" Leader,c toggles highlighted cursor row; doesn't work in visual mode +nnoremap <Leader>c + \ :<C-U>set cursorline! cursorline?<CR> "" Leader,h toggles highlighting search results nnoremap <Leader>h \ :<C-U>set hlsearch! hlsearch?<CR> "" Leader,i toggles showing matches as I enter my pattern nnoremap <Leader>i \ :<C-U>set incsearch! incsearch?<CR> -"" Leader,TAB toggles automatic indentation based on the previous line -nnoremap <Leader><Tab> - \ :<C-U>setlocal autoindent! autoindent?<CR> -"" Leader,c toggles highlighted cursor row; doesn't work in visual mode -nnoremap <Leader>c - \ :<C-U>setlocal cursorline! cursorline?<CR> "" Leader,s toggles spell checking nnoremap <Leader>s - \ :<C-U>setlocal spell! spell?<CR> + \ :<C-U>set spell! spell?<CR> " The next group of option-toggling maps are much the same as the previous " group, except they also include analogous maps for visual mode, defined as " recursive maps into normal mode that conclude with re-selecting the text. -"" Leader,N toggles position display in bottom right -nnoremap <Leader>N - \ :<C-U>set ruler! ruler?<CR> -xmap <Leader>N <Esc><Leader>Ngv "" Leader,C toggles highlighted cursor column; works in visual mode -nnoremap <Leader>C - \ :<C-U>setlocal cursorcolumn! cursorcolumn?<CR> -xmap <Leader>C <Esc><Leader>Cgv +noremap <Leader>C + \ :<C-U>set cursorcolumn! cursorcolumn?<CR> +ounmap <Leader>C +sunmap <Leader>C "" Leader,l toggles showing tab, end-of-line, and trailing white space -nnoremap <Leader>l - \ :<C-U>setlocal list! list?<CR> -xmap <Leader>l <Esc><Leader>lgv +noremap <Leader>l + \ :<C-U>set list! list?<CR> +ounmap <Leader>l +sunmap <Leader>l "" Leader,n toggles line number display -nnoremap <Leader>n - \ :<C-U>setlocal number! number?<CR> -xmap <Leader>n <Esc><Leader>ngv +noremap <Leader>n + \ :<C-U>set number! number?<CR> +ounmap <Leader>n +sunmap <Leader>n +"" Leader,N toggles position display in bottom right +noremap <Leader>N + \ :<C-U>set ruler! ruler?<CR> +ounmap <Leader>N +sunmap <Leader>N "" Leader,w toggles soft wrapping -nnoremap <Leader>w - \ :<C-U>setlocal wrap! wrap?<CR> -xmap <Leader>w <Esc><Leader>wgv - -" This next one just shows option state of the 'formatoptions' affecting how -" text is automatically formatted; it doesn't change its value. - -"" Leader,f shows the current 'formatoptions' at a glance -nnoremap <Leader>f - \ :<C-U>setlocal formatoptions?<CR> +noremap <Leader>w + \ :<C-U>set wrap! wrap?<CR> +ounmap <Leader>w +sunmap <Leader>w " I often have to switch between US English and NZ English. The latter is " almost exactly the same as UK English in most locales, although we use " dollars rather than pounds. This is mostly so I remember things like -" excluding or including the 'u' in words like 'favourite', depending on the +" excluding or including the `u` in words like `favourite`, depending on the " target audience. I generally use US English for international audiences. - -"" Leader,u sets US English spelling language -nnoremap <Leader>u - \ :<C-U>setlocal spelllang=en_us<CR> -"" Leader,z sets NZ English spelling language +" nnoremap <Leader>z - \ :<C-U>setlocal spelllang=en_nz<CR> + \ :<C-U>set spelllang=en_nz<CR> +nnoremap <Leader>u + \ :<C-U>set spelllang=en_us<CR> + +" I've also been trying to learn French lately (2023-04-03), and having +" a spelling check there is handy for doing my homework. +" +" This mapping used to show the state of 'formatoptions', but I haven't been +" using that nearly as often lately. +" +" <https://sanctum.geek.nz/images/ze-cultured-frenchman.png> +" +nnoremap <Leader>f + \ :<C-U>set spelllang=fr<CR> " The next mapping is also for toggling an option, but it's more complicated; " it uses a simple plugin of mine called copy_linebreak.vim to manage several @@ -1295,11 +1292,12 @@ nnoremap <Leader>z " larger blocks of text or for manipulating the text as it leaves the buffer, " it makes more sense to use :! commands. " -" <https://sanctum.geek.nz/cgit/vim-copy-linebreak.git/about/> +" <https://dev.sanctum.geek.nz/cgit/vim-copy-linebreak.git/about/> " "" Leader,b toggles settings friendly to copying and pasting -nmap <Leader>b <Plug>(CopyLinebreakToggle) +nmap <Leader>b + \ <Plug>(CopyLinebreakToggle) " The above mappings show that mappings for toggling boolean options are " simple, but there isn't a way to toggle single flags within option strings @@ -1308,13 +1306,14 @@ nmap <Leader>b <Plug>(CopyLinebreakToggle) " the name of an option, and the second is the flag within it that should be " toggled on or off. -"" Leader,a toggles 'formatoptions' 'a' auto-flowing flag +"" Leader,a toggles 'formatoptions' `a` auto-flowing flag nnoremap <Leader>a \ :<C-U>ToggleFlagLocal formatoptions a<CR> "" Leader,L toggles 'colorcolumn' showing the first column beyond 'textwidth' -nnoremap <Leader>L +noremap <Leader>L \ :<C-U>ToggleFlagLocal colorcolumn +1<CR> -xmap <Leader>L <Esc><Leader>Lgv +ounmap <Leader>L +sunmap <Leader>L " This mapping uses my paste_insert.vim plugin to queue up automatic commands " for the next insert operation. It's still pretty new. It replaces my old @@ -1322,7 +1321,8 @@ xmap <Leader>L <Esc><Leader>Lgv " kept confusing me. I'm hoping this will be better. "" Leader,p prepares the next insert for paste mode -nmap <Leader>p <Plug>PasteInsert +nmap <Leader>p + \ <Plug>PasteInsert " These mappings are for managing filetypes. The first one uses the " :ReloadFileType command that was defined much earlier in this file for @@ -1333,34 +1333,33 @@ nnoremap <Leader>F \ :<C-U>ReloadFileType<CR> "" Leader,t shows current filetype nnoremap <Leader>t - \ :<C-U>setlocal filetype?<CR> + \ :<C-U>set filetype?<CR> "" Leader,T clears filetype nnoremap <Leader>T - \ :<C-U>setlocal filetype=<CR> + \ :<C-U>set filetype=<CR> -" These mappings use my put_date.vim and utc.vim plugins for date insertion -" into the buffer. +" These mappings use my put_date.vim plugin for date insertion into the +" buffer. "" Leader,d inserts the local date (RFC 2822) nnoremap <Leader>d \ :PutDate<CR> "" Leader,D inserts the UTC date (RFC 2822) nnoremap <Leader>D - \ :<Home>UTC<End> PutDate<CR> + \ :PutDate!<CR> " This group contains mappings that are to do with file and path management -" relative to the current buffer. The Leader,P mapping that creates -" directory hierarchies uses the :Establish command created earlier. +" relative to the current buffer. "" Leader,g shows the current file's fully expanded path nnoremap <Leader>g \ :<C-U>echo expand('%:p')<CR> "" Leader,G changes directory to the current file's location nnoremap <Leader>G - \ :<C-U>cd %:h<Bar>pwd<CR> + \ :<C-U>cd %:h <Bar> pwd<CR> "" Leader,P creates the path to the current file if it doesn't exist nnoremap <Leader>P - \ :<C-U>Establish %:h<CR> + \ :<C-U>call mkdir(expand('%:h'), 'p')<CR> " This group contains mappings that show information about Vim's internals: " marks, registers, variables, and the like. @@ -1410,35 +1409,45 @@ nnoremap <Leader><Insert> \ :<C-U>enew<CR> "" Leader,e forces a buffer to be editable, even a :help one nnoremap <Leader>e - \ :<C-U>setlocal modifiable noreadonly<CR> + \ :<C-U>set modifiable noreadonly<CR> "" Leader,E locks a buffer, reversible with <Leader>e nnoremap <Leader>E - \ :<C-U>setlocal nomodifiable readonly<CR> -"" Leader,j jumps to buffers ("jetpack") + \ :<C-U>set nomodifiable readonly<CR> +"" Leader,j jumps to buffers---the "jetpack" nnoremap <Leader>j \ :<C-U>buffers<CR>:buffer<Space> -" This ground defines mappings for filtering and batch operations to clean up +" Leader,o hacks up the list of old files from viminfo just long enough to +" ensure that :browse :oldfiles fits in a screen, avoiding an Enter or `q` +" keystroke before entering the number. This one is handy followed by +" <Leader>,\ to jump back to the last remembered position in that file, since +" by definition viminfo remembers that mark, too. +" +nmap <Leader>o + \ <Plug>(SelectOldFiles) + +" This group defines mappings for filtering and batch operations to clean up " buffer text. All of these mappings use commands from my custom plugins: " " :KeepPosition -" <https://sanctum.geek.nz/cgit/vim-keep-position.git/about/> +" <https://dev.sanctum.geek.nz/cgit/vim-keep-position.git/about/> " :SqueezeRepeatBlanks -" <https://sanctum.geek.nz/cgit/vim-squeeze-repeat-blanks.git/about/> +" <https://dev.sanctum.geek.nz/cgit/vim-squeeze-repeat-blanks.git/about/> " :StripTrailingWhitespace -" <https://sanctum.geek.nz/cgit/vim-strip-trailing-whitespace.git/about/> +" <https://dev.sanctum.geek.nz/cgit/vim-strip-trailing-whitespace.git/about/> " "" Leader,x strips trailing whitespace -nnoremap <Leader>x - \ :StripTrailingWhitespace<CR> -xnoremap <Leader>x +noremap <Leader>x \ :StripTrailingWhitespace<CR> +ounmap <Leader>x +sunmap <Leader>x + "" Leader,X squeezes repeated blank lines -nnoremap <Leader>X - \ :SqueezeRepeatBlanks<CR> -xnoremap <Leader>X +noremap <Leader>X \ :SqueezeRepeatBlanks<CR> +ounmap <Leader>X +sunmap <Leader>X "" Leader,= runs the whole buffer through =, preserving position nnoremap <Leader>= \ :<C-U>KeepPosition execute 'normal! 1G=G'<CR> @@ -1453,23 +1462,28 @@ nnoremap <Leader>+ "" Leader,_ uses last changed or yanked text as an object onoremap <Leader>_ \ :<C-U>execute 'normal! `[v`]'<CR> -"" Leader,% uses entire buffer as an object +"" Leader,% or Leader,5 uses entire buffer as an object onoremap <Leader>% \ :<C-U>execute 'normal! 1GVG'<CR> +omap <Leader>5 + \ <Leader>% " This group defines some useful motions, including navigating by indent " block using a custom plugin: " -" <https://sanctum.geek.nz/cgit/vim-vertical-region.git/about/> +" <https://dev.sanctum.geek.nz/cgit/vim-vertical-region.git/about/> " "" Leader,{ and Leader,} move to top and bottom of indent region -map <Leader>{ <Plug>(VerticalRegionUp) +map <Leader>{ + \ <Plug>(VerticalRegionUp) sunmap <Leader>{ -map <Leader>} <Plug>(VerticalRegionDown) +map <Leader>} + \ <Plug>(VerticalRegionDown) sunmap <Leader>} -"" Leader,\ jumps to the last edit position mark: think "Now, where was I?" -noremap <Leader>\ `" +"" Leader,\ jumps to the last edit position mark; think "Now, where was I?" +noremap <Leader>\ + \ `" sunmap <Leader>\ " This group does both: useful motions on defined text objects. @@ -1493,29 +1507,68 @@ nnoremap <Leader>? " other place. The plugin mappings probably require their own documentation " comment block, but my hands are getting tired from all this typing. " -" * <https://sanctum.geek.nz/cgit/vim-replace-operator.git/about/> -" * <https://sanctum.geek.nz/cgit/vim-regex-escape.git/about/> +" * <https://dev.sanctum.geek.nz/cgit/vim-alternate-filetype.git/about/> +" * <https://dev.sanctum.geek.nz/cgit/vim-regex-escape.git/about/> +" * <https://dev.sanctum.geek.nz/cgit/vim-replace-operator.git/about/> +" * <https://dev.sanctum.geek.nz/cgit/vim-scratch-buffer.git/about/> " "" Leader,. runs the configured make program into the location list nnoremap <Leader>. \ :<C-U>lmake!<CR> "" Leader,q formats the current paragraph -nnoremap <Leader>q gqap +nnoremap <Leader>q + \ gqap "" Leader,r acts as a replacement operator -nmap <Leader>r <Plug>(ReplaceOperator) -xmap <Leader>r <Plug>(ReplaceOperator) -"" Leader,* escapes regex metacharacters -nmap <Leader>* <Plug>(RegexEscape) -xmap <Leader>* <Plug>(RegexEscape) +map <Leader>r + \ <Plug>(ReplaceOperator) +ounmap <Leader>r +sunmap <Leader>r +"" Leader,!/1 repeats the last command, adding a bang +nnoremap <Leader>! + \ :<Up><Home><S-Right>!<CR> +nmap <Leader>1 + \ <Leader>! +"" Leader,#/3 switches the current buffer to the next alternate filetype +nmap <Leader># + \ <Plug>(AlternateFileType) +nmap <Leader>3 + \ <Leader># +"" Leader,&/7 escapes regex metacharacters +map <Leader>& + \ <Plug>(RegexEscape) +ounmap <Leader>& +sunmap <Leader>& +map <Leader>7 + \ <Leader>& +ounmap <Leader>7 +sunmap <Leader>7 +"" Leader,*/8 is "sticky star": +"" - Set search string to word under cursor +"" - Show search highlighting if it's enabled +"" - Don't move the cursor +nnoremap <Leader>* + \ :<C-U>let @/ = expand('<cword>') <Bar> let &hlsearch = &hlsearch<CR> +nmap <Leader>8 + \ <Leader>* +"" Leader,` opens a scratch buffer, horizontally split +nnoremap <Leader>` + \ :<C-U>ScratchBuffer<CR> +"" Leader,~ opens a scratch buffer, vertically split +nnoremap <Leader>~ + \ :<C-U>vertical ScratchBuffer<CR> + +" There's no digraph for ZERO WIDTH SPACE (U+200B), which I often need to work +" around word boundary problems in tagging people on the Fediverse. +" +digraphs zs 8203 " And last, but definitely not least, I'm required by Vim fanatic law to " include a mapping that reloads my whole configuration. This uses the " command wrapper defined much earlier in the file, so that filetypes also get " reloaded afterwards, meaning I don't need to follow <Leader>R with " a <Leader>F to fix up broken global settings. - -"" Leader,R reloads ~/.vimrc +" nnoremap <Leader>R \ :<C-U>ReloadVimrc<CR> @@ -1524,17 +1577,28 @@ nnoremap <Leader>R " pretty useful. First, some 'deliberate' abbreviations for stuff I type " a lot: " -inoreabbrev tr@ tom@sanctum.geek.nz -inoreabbrev tr/ <https://sanctum.geek.nz/> +inoreabbrev tr@ + \ tom@sanctum.geek.nz +inoreabbrev tr/ + \ <https://sanctum.geek.nz/> " And then, just automatically fix some things I almsot always spell or type " wrnog. " -inoreabbrev almsot almost -inoreabbrev wrnog wrong -inoreabbrev Fielding Feilding -inoreabbrev THe The -inoreabbrev THere There +inoreabbrev almsot + \ almost +inoreabbrev wrnog + \ wrong +inoreabbrev Fielding + \ Feilding +inoreabbrev Newsbeuter + \ Newsboat +inoreabbrev newsbeuter + \ newsboat +inoreabbrev THe + \ The +inoreabbrev THere + \ There " Here endeth the literate vimrc. Let us praise God. " @@ -1543,4 +1607,5 @@ inoreabbrev THere There " > authors...as soon as this is perceived the book should be thrown away, " > for time is precious. " > -" > -- Schopenhauer +" > ---Schopenhauer +" |