Posts tagged vim

gnu global

posted on 2017-04-26 20:56

Get the current version from here. Alternatively, use the use the anonymous access to CVS, but no Idea wether the patches would work there.

The steps to version 6.5.6 running on a current gentoo install were, including the patches follow. I hope I don't forget something, this write was done a week later.

needed packages

emerge -atv these:

  • dev-python/pygments
  • dev-util/ctags
  • sys-devel/automake
  • sys-devel/m4

getting and compiling

mkdir asdf
cd asdf
curl -O http://tamacom.com/global/global-6.5.6.tar.gz
tar xzvf global-6.5.6.tar.gz
cd global-6.5.6

applying these two patches:

diff --git a/configure.ac b/configure.ac
index cda52e4..d7d1a73 100644
--- a/configure.ac
+++ b/configure.ac
@@ -24,6 +24,7 @@ dnl
 AC_INIT([GNU GLOBAL],[6.5.6])
 AC_DEFINE(COPYRIGHT_YEAR,["1996-2016"],[Copyright Year])
 AC_CONFIG_SRCDIR(global/global.c)
+AC_CONFIG_MACRO_DIRS([m4])
 AC_CONFIG_HEADERS([config.h:config-h.in])
 AC_PREREQ(2.59)
 AM_INIT_AUTOMAKE([1.9.3 gnu subdir-objects])


diff --git a/Makefile.am b/Makefile.am
index 43585a6..f6ab5c5 100644
--- a/Makefile.am
+++ b/Makefile.am
@@ -29,6 +29,8 @@ gtags_DATA = AUTHORS COPYING COPYING.LIB ChangeLog FAQ INSTALL LICENSE NEWS READ

 EXTRA_DIST = ${gtags_DATA} reconf.sh convert.pl mainpage.dox head.in

+ACLOCAL_AMFLAGS = -I m4
+
 doxygen:
    GTAGSCONF=':htags_options=--insert-header=head.in --suggest:' doxygen

Then back to the shell:

autoreconf -fvi
./configure --with-universal-ctags=`which ctags`
make
make check
sudo make install

setup and test

sudo updatedb
sudo locate gtags.conf
cp -va /usr/local/share/gtags/gtags.conf ~/.globalrc
gtags --version
global --version
cd ../..
rm -rf asdf

usage

Now onto actual usage:

CLI:

gtags -v        # generate tag database (initially, rerun with -i everytime code is changed!)

global FUNC     # finds file where FUNC is defined, regexp's work, too
global -r FUNC      # find files where FUNC is used in
global -x FUNC      # == ctags -x, name+line+path+line_content

Of course you only want to look at source, not generated code. If git is used, doing this from the project root will do the trick:

git ls-files > gtags.files

There's more to it, but it should be sufficiant for now. Usually global should be integrated into your dev environment of choice.

Out of the box, less should work. vim and emacs need plugins to work, they won't be covered at this time here.

less:

export LESSGLOBALTAGS=global  ## this is needed so less knows it can work with global
less -t FUNC        # opens file where FUNC is defined

notes on using vimdiff

posted on 2016-12-29 11:55

Bare minimum to do some work with it:

do - Get changes from other window into the current window.
dp - Put the changes from current window into the other window.

]c - Jump to the next change.
[c - Jump to the previous change.

Ctrl W + Ctrl W - Switch to the other split window.

If you load up two files in splits (:vs or :sp), you can do :diffthis on each window and achieve a diff of files that were already loaded in buffers. :diffoff can be used to turn off the diff mode.

Also helpful: :help copy-diffs, and this link here.

vim align by character

posted on 2016-10-10 13:03

Use case is, align this:

[transfer]
    valid users = transfer
    force user = transfer
    force group = transfer
    browseable = yes
    path = /var/samba/transfer/

to that:

[transfer]
        valid users             = transfer
        force user              = transfer
        force group             = transfer
        path                    = /var/samba/transfer/

Usually all answers point to Tabular.vim or Align.vim plugins.

This can as well be achieved by creating a macro and applying it to all lines in your whole file (or just a subset, how you prefer).

Steps to record are as follows:

  • start macro recording - q q
  • jump to beginning of line - 0
  • jump to character - f
  • 1 char backwards - h
  • insert 100 spaces - 100 i ESC
  • jump to column where to align to, i.e. 45 - 45 |
  • delete all following spaces / to beginning next word - d w
  • end macro - q

Then either use visual mode to mark all lines you want it applied to, press : to get into command mode:

:'<,'>norm! @q

or on all lines:

:%norm! @q

or on all lines matching a PATTERN:

:g/PATTERN/norm! @q

spacemacs: essentials

posted on 2016-01-16 12:20

foreword

Spacemacs is a truly awesome piece of software. It is literally the best of both worlds from vim and emacs.

In the last years I have heavily used (and customized) vim (my .vimrc is about 900 lines). But as soon as you want to do more complex stuff, which involves a lot of plugins, things get ugly and slow. Often you also happen to need a custom compiled vim (so it has python bindings enabled) and bad hackery (vimscript is an absolute traffic accident).

After quite some stints with emacs in the last years (interest in lisp plus the customization which is possible with it, compared to vimscript) and a lot of pulling hair out due to debugging problems (When is a major/minor-mode actually loaded? Packages broken when using the different package universes like melpa/elpa/marmalade together? Evil-mode not working in all buffers even though it was set globally?) I stumbled upon Spacemacs.

common solutions for common problems

helm keybind popup too slow

See ~/.spacemacs:

dotspacemacs-which-key-delay 0.01

syntax highlighting for special files lacking

Put this into ~/.spacemacs in the user-config() section:

(autoload 'markdown-mode "markdown-mode"
  "Major mode for editing Markdown files" t)
(add-to-list 'auto-mode-alist '("\\.post\\'" . markdown-mode))
(add-to-list 'auto-mode-alist '("\\.md\\'" . markdown-mode))

font too large

See ~/.spacemacs, same section:

(defun dotspacemacs/user-config ()
       (set-face-attribute 'default nil :height 80)
)

Here 10 ~= 1pt, so 80 is like 8pt from what I read.

start maximized

See ~/.spacemacs:

dotspacemacs-maximized-at-startup t

custom bindings

Canonical example here shall be using 'jk' simultanously to exit from INSERT mode. For that the key-chord package is needed, plus a little configuration.

See ~/.spacemacs:

(defun dotspacemacs/user-config ()
       (key-chord-define-global "jk" 'evil-normal-state)
       (key-chord-mode t)
       ...
)
(defun dotspacemacs/user-config ()

is the place to go. If you for example need additional packages without grouping them into a layer, put them under dotspacemacs-additional-packages, also in .spacemacs.

dotspacemacs/user-init vs. dotspacemacs/user-config

user-config gets loaded at the end of the parsing of the config file contents, whereas user-init right at the beginning. Usually you want to place code into user-config.

keybinds essentials list (beside original vim stuff)

ESC             abort current menu
C-g             abort current menu
C-h u           go back to previous helm menu

SPC f f         open file
SPC f s         save file

C-x C-c         close spacemacs

# window management
SPC w /         create vertical window split
SPC w -         create horizontal window split
SPC w c         window close

SPC TAB         switch to last buffer
SPC b b         buffer list
SPC b n         next buffer
SPC b p         previous buffer
SPC f d         kill/delete buffer

SPC <number>    jump to window <number>
SPC w arrow     move to window up/left/righ/down
C-w hjkl        move to window up/left/righ/down
SPC w S-arrow   move window up/left/righ/down
SPC w c         close window

# open and reload dotfile
SPC f e d       open
SPC f e R       reload dotfile

# using the help for looking up things, the shortcut is:
SPC h d f       help describe function
SPC h d k       help describe key
SPC h d p       help describe package
SPC h d m       help describe mode
SPC h d v       help describe variable
C-h a           emacs 'apropos'

keybinds additionals list (non-geeks safely forget everything past here...)

HUD

SPC t f         toggle show indicator at 80 chars and disable soft-wrapping
SPC t h h       toggle show cursorline
SPC t i         toggle show indent guide
SPC t h a       toggle automatic symbol highlighting
SPC f t         toggle neo-tree (folder browser)

editing

SPC n r         narrow region (just show current selection)
SPC n f         narrow function (just show current function)
SPC n w         widen again

syntax checking

SPC t s         enable flycheck

vim: search/replace just within block selection

posted on 2015-06-21 21:40:24

A completely arbitrary and pretty non-worldly example:

, , , , , , , , , , , , , , , , , ,
, , , , , , , , , , , , , , , , , ,
, , , , , , , , , , , , , , , , , ,
, , , , , , , , , X , X , , , , , ,
, , , , , , , , , X , X , , , , , ,
, , , , , , , , , X , X , , , , , ,
, , , , , , , , , X , X , , , , , ,
, , , , , , , , , X , X , , , , , ,
, , , , , , , , , , , , , , , , , ,
, , , , , , , , , , , , , , , , , ,
, , , , , , , , , , , , , , , , , ,
, , , , , , , , , , , , , , , , , ,

Shall look like this:

, , , , , , , , , , , , , , , , , ,
, , , , , , , , , , , , , , , , , ,
, , , , , , , , C C C C C , , , , ,
, , , , , , , , C X C X C , , , , ,
, , , , , , , , C X C X C , , , , ,
, , , , , , , , C X C X C , , , , ,
, , , , , , , , C X C X C , , , , ,
, , , , , , , , C X C X C , , , , ,
, , , , , , , , C C C C C , , , , ,
, , , , , , , , , , , , , , , , , ,
, , , , , , , , , , , , , , , , , ,
, , , , , , , , , , , , , , , , , ,

Which basically means, how can the text selection be made, and just change the words/characters/regexes with the selection and not the complete line?

The answer is, using :'<,'>s/\%V,/C/g after having block-selected the area in question.

So simply prepend \%V to the search term.

Lots of other things can be done, like just matching before/after a line number, search only within specific columns, ... See here for more info.

vim: remote editing of files

posted on 2015-04-21 10:24:10

In general, this will do:

vim scp://remoteuser@server.tld//path/to/document

E.g.

vim scp://my_user:my_pass@sjas.de//var/www/domain/somefile.txt

The important part is the double slash after the domain, in case you specify absolute paths.

To not having to fiddle with passwords, create a .netrc file in your home folder containing entries like this one:

machine yourftp.somewhere.org login yourlogin password "yoursecret"

Some more tricks can be found here, where this is initially from.

If vim tells something about 'buftype' and that it cannot save, issue this command prior to saving from within vim:

:se buftype=

OS schema

posted on 2015-01-17 04:55:48

While toying around with the vim DrawIt plugin (which simplyfies the task of creating ascii art diagrams immensely), I needed something to test it with.

After having come across an operating system layout and which of linux tools' are to be used at which spot, I 'redrew' this:

      +---------------------------------------------+
      |              APPLICATIONS                   |
      |          db's, all server types, ...        |
      |                   +-------------------------+
      |                   |       system libs       |
      +=============================================+
      |              system call interface          |
      +=============================================+
 l    |  VFS           ||  sockets   ||             |     cpu     +-------+
 i    +----------------++------------++  scheduler  |-------------| CPU 1 |
 n  k |  FS            ||  TCP/UDP   ||             |  intercon.  +-------+
 u  e +----------------++------------++-------------+                 |
 x  r |  volume        ||  IP        ||             |                 |
    n |  managers      ||            ||  virtual    |                 |
    e +----------------++------------++  memory     |                 |
    l |  block dev if  ||  ethernet  ||             |             +------+
      +=============================================+             | DRAM |
      |              device drivers                 |             +------+
      +=============================================+
                             |
                             |  I/O bus
                             |
                       +------------+
                       | I/O bridge |
       expander        +------------+
       interconnect     /           \
                       /             \
       +----------------+          +--------------------+
       | I/O controller |          | network controller |
       +----------------+          +--------------------+
               /\                            /\
              /  \     if transports        /  \
             /    \                        /    \
       +------+    +------+         +------+   +------+
       | disk |    | swap |         | port |   | port |
       +------+    +------+         +------+   +------+

Minimal dotfiles

posted on 2014-11-06 05:40:21

Without further ado, this is put here for documentary reasons. I paste this into the current configs and am glad.

.bashrc

#######################################################################################################################
### aliases
#######################################################################################################################
alias l='ls -lahF --color'
alias ..='cd ..'
alias lsblk='lsblk -o name,label,mountpoint,fstype,model,size,type,state,uuid'
alias v='vim'
alias grep='grep -i -n --color'
alias ev='vim ~/.vimrc'
alias eb='vim ~/.bashrc'
alias eg='vim ~/.gitconfig'
alias ggfc='git add .; git commit -m "fastcommit"; git pull origin master; git push origin master'


#######################################################################################################################
### env
#######################################################################################################################
export EDITOR=vim
export VISUAL=vim
export PS1='\[\e[31;1m\][\[\e[37;1m\]\u\[\e[33;1m\]@\[\e[37;1m\]\H \[\e[32;1m\]\w\[\e[31;1m\]]\[\e[36;1m\]\$ \[\e[0m\]'
export PATH=/home/sjas/bin:$PATH
export LESS_TERMCAP_mb=$'\E[1;31m'
# COMMAND AND FLAG COLOR
export LESS_TERMCAP_md=$'\E[1;32m'
# PARAMETER COLOR
export LESS_TERMCAP_us=$'\E[1;33m'
export LESS_TERMCAP_me=$'\E[0m'
export LESS_TERMCAP_se=$'\E[0m'
export LESS_TERMCAP_so=$'\E[38m'
export LESS_TERMCAP_ue=$'\E[0m'

#######################################################################################################################
# blogging
#######################################################################################################################
function createpost() {
    if [ $# -ne 1 ]
    then 
        echo "Usage :: post filename as parameter without .post extension"
        exit 1
    fi

    cat << EOHD > ~/blog/$1.post
;;;;;
title: 
tags: 
date: 
format: md
;;;;;
content
EOHD
}

.vimrc

let mapleader=' '
let maplocalleader=' '
syn on
se hls
se is
se ic
se gd
se ai
se et
se sts=4
se ts=4
se sw=4
se backspace=indent,eol,start
se sm
se wildmenu
se wildmode=list:longest,full


nnoremap s/ :s/
nnoremap ss/ :%s/
vnoremap s/ :s/
nnoremap <leader><backspace> /qwerqwerasdfasdf<cr><esc>
nnoremap <leader>ul yypVr=0<cr>
nnoremap <leader>fs :.!date --rfc-3339=seconds<cr><esc>$xxxxxx
nnoremap <leader><leader>fs Sdate:<esc>o<esc>:.!date --rfc-3339=seconds<cr><esc>kJ$xxxxxx
nnoremap <leader><leader>i :%s/^\s*<cr>/qwerqwer<cr><esc>
vnoremap <leader><leader>i :s/^\s*<cr>/qwerqwer<cr><esc>
nnoremap <leader><leader>s :%s/\s*$<cr>/qwerqwer<cr><esc>
vnoremap <leader><leader>s :s/\s*$<cr>/qwerqwer<cr><esc>
vnoremap <leader>ln !nl -ba<cr>
nnoremap <leader>n :next<cr>
nnoremap <leader>b :prev<cr>
nnoremap <leader><c-d> :sh<cr>

nnoremap <Leader>wq :wq<CR>
nnoremap <Leader>fw :se bt=<cr>:w<CR>
nnoremap <Leader>fa :wa<CR>
nnoremap <Leader>fq :q<CR>
nnoremap <Leader>rq :q!<CR>

cmap w!! w !sudo tee % > /dev/null

vim fast execution bind

posted on 2014-09-07 12:32:37

To test quick throwaway scripts in vim try this: (linux-only, for windows this will work only via cygwin)

nnoremap <Leader>fr :w<CR>:!clear && ./%<CR>

Upon pressing the <leader>fr key combination (vim's leaderkey is \ by default), this happens:

  • the file you are currently editing will be saved
  • vim drops to a shell and clears the screen
  • the script gets executed

This works as long as the script has a shebang line and is executable (don't forget to chmod), since \% is the wildcard for the currently opened file

The best things in life are for free. :)

Fix git mergeconflicts (with vim)

posted on 2014-09-06 13:11:07

If, during a pull (or rebase), git fails to finish its currently run command, this one-liner might be helpful:

vim `git diff --diff-filter=U --name-only`

It will open all files, that git could not merge, in vim.

Fix the first one, save, :n (next window), fix the next one, and so forth.

Once you are done, git add . them all, git commit, and start again where git left off. (The rebase or push or whatever.)

vim backreferences

posted on 2014-08-08 15:30:52

Backreferences in vim are used in search-and-replace commands in vim.

Parts grouped in the search part, can be referenced in the replace part.

Usually for grouping escaped parentheses are needed, depending on how magic your vim is, or if you use \v. If you don't believe me, you most certainly never used :h magic in vim, which tells this:

 3. Magic                                                        */magic*

Some characters in the pattern are taken literally.  They match with the same
character in the text.  When preceded with a backslash however, these
characters get a special meaning.

Other characters have a special meaning without a backslash.  They need to be
preceded with a backslash to match literally.

If a character is taken literally or not depends on the 'magic' option and the
items mentioned next.
                                                        */\m* */\M*
Use of "\m" makes the pattern after it be interpreted as if 'magic' is set,
ignoring the actual value of the 'magic' option.
Use of "\M" makes the pattern after it be interpreted as if 'nomagic' is used.
                                                        */\v* */\V*
Use of "\v" means that in the pattern after it all ASCII characters except
'0'-'9', 'a'-'z', 'A'-'Z' and '_' have a special meaning.  "very magic"

Use of "\V" means that in the pattern after it only the backslash has a
special meaning.  "very nomagic"

Examples:
after:    \v       \m       \M       \V         matches ~
                'magic' 'nomagic'
          $        $        $        \$         matches end-of-line
          .        .        \.       \.         matches any character
          *        *        \*       \*         any number of the previous atom
          ()       \(\)     \(\)     \(\)       grouping into an atom
          |        \|       \|       \|         separating alternatives
          \a       \a       \a       \a         alphabetic character
          \\       \\       \\       \\         literal backslash
          \.       \.       .        .          literal dot
          \{       {        {        {          literal '{'
          a        a        a        a          literal 'a'

{only Vim supports \m, \M, \v and \V}

It is recommended to always keep the 'magic' option at the default setting,
which is 'magic'.  This avoids portability problems.  To make a pattern immune
to the 'magic' option being set or not, put "\m" or "\M" at the start of the
pattern.

TL;DR

Use \( \) to group, and \1, \2, and so forth to reference.

Example:

echo 1
echo 2

will become

echo "1"
echo "2"

through this:

:%s/\(^echo \)\(\d\+\)$/\1"\2"/g

or alternatively this: (I hope I have no typo in there ;o))

:%s/\v(^echo )(\d\+)$/\1"\2"/g

It matches echo at the beginning of the line (^) as first part, one ore more digits (\d\+) afterwards as second part. These are referenced through \1 and \2, and the second backreference is put in between quotation marks "".

vim: jump to column

posted on 2014-06-22 21:52:47

To jump to a special column, i.e. the 71st, do this:

71 Ctrl-|

Compile vim on Debian 7

posted on 2014-05-14 17:13:39

bare vim

First install mercurial if you do not have it already. Use hg --version to check.

$ apt-get install mercurial

Then get the vim sources and compile:

$ hg clone https://vim.googlecode.com/hg/ vim
$ cd vim/src
$ make

If it fails with an error like this one:

checking for tgetent in -ltinfo... no
checking for tgetent in -lncurses... no
checking for tgetent in -ltermlib... no
checking for tgetent in -ltermcap... no
checking for tgetent in -lcurses... no
no terminal library found
checking for tgetent()... configure: error: NOT FOUND!
      You need to install a terminal library; for example ncurses.
            Or specify the name of the library with
--with-tlib.
            make: *** [auto/config.mk] Error 1

Try installing an ncurses library:

$ apt-get install libncurses5

Afterwards all should be fine.

vim with python 3 support enabled

If however you desire specific functions (like using the powerline statusbar), you might need python support compiled into vim. Along with this there are some other things I need, too, which are shown below.

Enable it by preparing via ./configure:

./configure \
    --enable-python3interp \
    --with-python-config-dir=/usr/lib/python3.2/config-3.2mu \
    --with-x=yes \
    --with-features=normal \
    --disable-gui \
    --prefix=$HOME/dev/vim

This enables python 3 (for python 2, the command is the same, just lacking the '3'), the config dir is important, too.

X support is baked in for clipboard stuff, IIRC.
The featureset is normal. (See :h +feature for what is included.)
GUI is disabled since I never use gvim.
At last, the install directory is in $HOME/dev, because I prefer the vim install being there along with other dev tools.

python support install problems in detail

missing python dev packages

The tricky stuff for enabling python is to not forget the python dev packages, in my case via apt-get install python3-dev.
If python does not want to work, vim needs python's config dir location, and there has to be the config.c file located. Else installation will work, but you will not notice why it did now work as expected.

Try appending grep python -C3 via a pipe, i.e.

$ ./configure \
    --enable-python3interp \
    --with-python-config-dir=/usr/lib/python3.2/config-3.2mu \
    --with-x=yes \
    --with-features=normal \
    --disable-gui \
    --prefix=$HOME/dev/vim | grep python -C3`

That way you will be able to notice if the ./configure step is borked.

./configure's caching

Also, ./configure caches the steps it has made. This is the case when the ./configure ... output has (cached) appended. In this case just delete the config.cache file within the vim/src/auto folder.

Editing remote files in local vim

posted on 2014-05-14 14:39:09

If you have a highly configured vim that you hold dearly and love to bits, and you have to edit a lot of remote files, try vim-over-ssh. scp is used to transfer files, and there is a slight delay, but it does work awesome.

Syntax:

vim scp://<user>@<host>//<path/to/file>

Note the double slashes // after the hostname. These are used so the absolute path to your file can be specified.

vim open file with cursor positioned

posted on 2014-05-13 15:54:34

To open a file in vim, with the cursor positioned on the first search match, use:

$ vim +/<searchterm> <filename>

To just open vim with the cursor being placed on a specific line, do:

$ vim +<linenumber> <filename>

Editing shell commands in vim

posted on 2014-04-26 18:41:02

Having a long shell command, wishing for an easier way to edit it? Not wanting to have the vim bindings (set -o vi IIRC) enabled in bash, since they, lets face it, could use alot of improvement? (Or a proper zsh prompt, so you see which mode you are currently in, maybe?)

$ Ctrl+X, Ctrl+E

Press this while being in the bash console. Once you save and exit vim, you have your output changes in the shell again, and off you go.

Find files via grep and open in editor

posted on 2014-01-18 23:33:31

Often you have to find a function definition or use or just a unique string or setting, but do not know in which file it is located. Grepping will return the results, but you have to type in the filename again when opening the file in question in an editor. This here is intended to streamline the process.

USAGE:
grepe static void main or
grepv static void main.

No "" needed.

INSTALL:
Put this into your .bashrc.

#emacs:
grepe(){
    emacs $(\grep -irl "$*" .)
}
#vim:
grepv(){
    vim $(\grep -irl "$*" .)
}

I wonder why I did not look for this earlier. :o)

grep is used instead of ack so all files are searched, as ack will only search files it 'knows'.

Vim colorcolumn fix

posted on 2013-12-13 23:08:23

Vim's got the possibility to show a colored vertical line in your editor a certain character spot.

cc=81

Put this command in your .vimrc to enable this. cc is shorthand for colorcolumn. This basically is just a graphical reminder at column 81 for you to break your lines, and is shown across all lines.

If instead you just want to have markers shown when you actually have to long lines, use this:

call machadd('ColorColumn', '\%81v', 100)

Now the highlighting is only present in lines actually being too long.

Line numbers in vim

posted on 2013-10-27 14:27:18

Line numbers in vim are turned off by default, and there exist two variations of them. (Since vim version 7.3 IIRC.)

When viewing a file with a dozen lines, numbers can be shown absolute (1,2,3,4,5..12) or relative to the line you are in. If your cursor is located in line 3, numbering would change if you move to line 4. (2,1,[3],1,2,3,4..9) changes to (3,2,1,[4],1,2,3..8).

Relative numbering would look plain useless on first sight, but when was the last time you wondered which line numbering argument to use relative to the current line? I.e. delete the next x lines, where x is not just 4,5,6 lines, where you can still easily tell the count?
Less obvious at first, think less complex, do you use j and k for in-file-navigation? Sure, { and } will jump paragraph-wise. But is this really the best means to an end?

When using absolute numbers :10<CR> will jump to line 10 in the file. But 5j will jump five lines down, 5- goes five down from the current line, and relative numbering will show exactly how many lines you will have to enter. For example, what is when the file you are editing in like 4000 lines long, and you move around lines 3500? Jumping to absolute lines gets old fast, if you are in the four-digits, line-wise.

To enable line numbers shown:

# turn on absolute numbering
:se nu
# turn on relative numbering
:se rnu

To disable: (Comes in handy for c&p things, especially when using vim in the console.)

# turn off absolute numbering
:se nonu
# turn off relative numbering
:se nornu

Of course, you cannot use both modes at once. But I disgress. The incentive for this post was a different use case.

How to number the lines of the current code snippet for documentation purposes in-file after pasting?

There are a lot of possible solutions with vimscript usage (which is very likely not the easiest way). Or just use linux'/cygwin' nl command:

:%!nl -ba

The % indicated this is applied to the whole file.

:'<,'>!nl -ba

Wheres this is just applied to the lines currently marked in visual mode. Select lines, :!nl -ba, vim will insert the rest. Use man nl for the different options the nl command provides.

Just put this in your .vimrc:

vnoremap <leader>ln !nl -ba<cr>

This lets you annotate an area you selected in visual mode via Leaderkey-l-n.

To easily remove the line numbers in case they would not be needed anymore, C-v enables vim's block-wise editing mode. At least under linux, for windows this was C-Q or C-q or something, I just remember it differed.
Anyway, this enables you to easily select a rectangle of text anywhere within your current file. The selection can be changed, deleted, whatever. Changes my only appear after exiting block-selection-mode, do not wonder when only one line is affected during your changing.

vim leaderkey rebinding to space

posted on 2013-10-17 16:03:58

Rebinding the leader key in vim is quite nice, since the original \ bind is kind of suboptimal. Once you start binding your own stuff, the key assigned to it is in heavy use. Using some meta key like CTRL or ALT is not useful since these will not work on their own. Most users take , or something alike.

Why not just use SPACE?

Only problem is, a literal ' ' used with the rebind command will not work, vim will not recognize it. It has to be inserted via pressing CTRL+V followed by hitting SPACE. That way the space will be inserted properly, and the following line will work in your .vimrc:

let mapleader = ' '

If you just copy-paste the line above without explicit CTRL-V-inserting the space in your vim while editing the .vimrc, most likely your binding will not work.

Insert date and time via vim

posted on 2013-10-16 00:30:54

Out of the box vim does not have any possibility to insert date/time information into text files you are editing. (At least that vim were sporting such functionality would be news to me.) But unix comes to help. Vim is programmable and makes it easy to bind anything to any key.

First how to obtain the proper date information. Test this on your command prompt:

date --rfc-3339=seconds

which produces something like

2013-10-16 00:03:26+02:00

To bind commands to keys in vim, the .vimrc file needs some editing. It lies in your homefolder. (This file could also be called _vimrc, if you are under windows. Depending on how you installed vim.) In case it does not exist, create a new one and insert the following line:

nnoremap <Leader>fs :.!date --rfc-3339=seconds<cr><esc>

If the timezone information is too much, just use instead:

nnoremap <Leader>fs :.!date --rfc-3339=seconds<cr><esc>$xxxxxx

and you have

2013-10-16 00:03:26

The binding can be used in normal mode in vim via \fs (press these three keys one after another), except if you have rebound your leader key. When used, the entire line will be replaced with the date entry.

Leaderkey rebinding can be done like here.

This blog covers .csv, .htaccess, .pfx, .vmx, /etc/crypttab, /etc/network/interfaces, /etc/sudoers, /proc, 10.04, 14.04, AS, ASA, ControlPanel, DS1054Z, GPT, HWR, Hyper-V, IPSEC, KVM, LSI, LVM, LXC, MBR, MTU, MegaCli, PHP, PKI, R, RAID, S.M.A.R.T., SNMP, SSD, SSL, TLS, TRIM, VEEAM, VMware, VServer, VirtualBox, Virtuozzo, XenServer, acpi, adaptec, algorithm, ansible, apache, apache2.4, apachebench, apple, applet, arcconf, arch, architecture, areca, arping, asa, asdm, autoconf, awk, backup, bandit, bar, bash, benchmarking, binding, bitrate, blackarmor, blockdev, blowfish, bochs, bond, bonding, booknotes, bootable, bsd, btrfs, buffer, c-states, cache, caching, ccl, centos, certificate, certtool, cgdisk, cheatsheet, chrome, chroot, cisco, clamav, cli, clp, clush, cluster, coleslaw, colorscheme, common lisp, configuration management, console, container, containers, controller, cron, cryptsetup, csync2, cu, cups, cygwin, d-states, database, date, db2, dcfldd, dcim, dd, debian, debug, debugger, debugging, decimal, desktop, df, dhclient, dhcp, diff, dig, display manager, dm-crypt, dmesg, dmidecode, dns, docker, dos, drivers, dtrace, dtrace4linux, du, dynamictracing, e2fsck, eBPF, ebook, efi, egrep, emacs, encoding, env, error, ess, esx, esxcli, esxi, ethtool, evil, expect, exportfs, factory reset, factory_reset, factoryreset, fail2ban, fbsd, fdisk, fedora, file, filesystem, find, fio, firewall, firmware, fish, flashrom, forensics, free, freebsd, freedos, fritzbox, fsck, fstrim, ftp, ftps, g-states, gentoo, ghostscript, git, git-filter-branch, github, gitolite, global, gnutls, gradle, grep, grml, grub, grub2, guacamole, hardware, haskell, hdd, hdparm, hellowor, hex, hexdump, history, howto, htop, htpasswd, http, httpd, https, i3, icmp, ifenslave, iftop, iis, imagemagick, imap, imaps, init, innoDB, innodb, inodes, intel, ioncube, ios, iostat, ip, iperf, iphone, ipmi, ipmitool, iproute2, ipsec, iptables, ipv6, irc, irssi, iw, iwconfig, iwlist, iwlwifi, jailbreak, jails, java, javascript, javaws, js, juniper, junit, kali, kde, kemp, kernel, keyremap, kill, kpartx, krypton, lacp, lamp, languages, ldap, ldapsearch, less, leviathan, liero, lightning, links, linux, linuxin3months, lisp, list, livedisk, lmctfy, loadbalancing, locale, log, logrotate, looback, loopback, losetup, lsblk, lsi, lsof, lsusb, lsyncd, luks, lvextend, lvm, lvm2, lvreduce, lxc, lxde, macbook, macro, magento, mailclient, mailing, mailq, manpages, markdown, mbr, mdadm, megacli, micro sd, microsoft, minicom, mkfs, mktemp, mod_pagespeed, mod_proxy, modbus, modprobe, mount, mouse, movement, mpstat, multitasking, myISAM, mysql, mysql 5.7, mysql workbench, mysqlcheck, mysqldump, nagios, nas, nat, nc, netfilter, networking, nfs, nginx, nmap, nocaps, nodejs, numberingsystem, numbers, od, onyx, opcode-cache, openVZ, openlierox, openssl, openvpn, openvswitch, openwrt, oracle linux, org-mode, os, oscilloscope, overview, parallel, parameter expansion, parted, partitioning, passwd, patch, pct, pdf, performance, pfsense, php, php7, phpmyadmin, pi, pidgin, pidstat, pins, pkill, plasma, plesk, plugin, posix, postfix, postfixadmin, postgres, postgresql, poudriere, powershell, preview, profiling, prompt, proxmox, ps, puppet, pv, pveam, pvecm, pvesm, pvresize, python, qemu, qemu-img, qm, qmrestore, quicklisp, quickshare, r, racktables, raid, raspberry pi, raspberrypi, raspbian, rbpi, rdp, redhat, redirect, registry, requirements, resize2fs, rewrite, rewrites, rhel, rigol, roccat, routing, rs0485, rs232, rsync, s-states, s_client, samba, sar, sata, sbcl, scite, scp, screen, scripting, seafile, seagate, security, sed, serial, serial port, setup, sftp, sg300, shell, shopware, shortcuts, showmount, signals, slattach, slip, slow-query-log, smbclient, snmpget, snmpwalk, software RAID, software raid, softwareraid, sophos, spacemacs, spam, specification, speedport, spi, sqlite, squid, ssd, ssh, ssh-add, sshd, ssl, stats, storage, strace, stronswan, su, submodules, subzone, sudo, sudoers, sup, swaks, swap, switch, switching, synaptics, synergy, sysfs, systemd, systemtap, tar, tcpdump, tcsh, tee, telnet, terminal, terminator, testdisk, testing, throughput, tmux, todo, tomcat, top, tput, trafficshaping, ttl, tuning, tunnel, tunneling, typo3, uboot, ubuntu, ubuntu 16.04, udev, uefi, ulimit, uname, unetbootin, unit testing, upstart, uptime, usb, usbstick, utf8, utm, utm 220, ux305, vcs, vgchange, vim, vimdiff, virtualbox, virtualization, visual studio code, vlan, vmstat, vmware, vnc, vncviewer, voltage, vpn, vsphere, vzdump, w, w701, wakeonlan, wargames, web, webdav, weechat, wget, whois, wicd, wifi, windowmanager, windows, wine, wireshark, wpa, wpa_passphrase, wpa_supplicant, x11vnc, x2x, xfce, xfreerdp, xmodem, xterm, xxd, yum, zones, zsh


Unless otherwise credited all material Creative Commons License by sjas