Kakoune
=======

Introduction:
-------------

Kakoune is a code editor heavily inspired by vim, as such most of it's
commands are similar to vi's ones.

Kakoune can operate in two modes, normal and insertion. In insertion mode,
keys are directly inserted into the current buffer. In normal mode, keys
are used to manipulate the current selection and to enter insertion mode.

There is no concept of cursor in kakoune, only selections, a single character
selection can be seen as a cursor but there is no difference internally.

Building
--------

Kakoune dependencies are:

 * GCC >= 4.7
 * boost
 * ncurses
 * bash (kak scripts use some bash specific features)
 * socat (used by kak scripts to write to kak control socket)

To build, just type *make* in the src directory

To setup a basic configuration on your account, type *make userconfig* in the
src directory, this will setup an initial $XDG_CONFIG_HOME/kak directory. See
the _Kakrc_ section for more information.

Running
-------

Just running *kak* launch a new kak session with a client on local terminal.
*kak* accepts some switches:

 * +-c <session>+: connect to given session, sessions are unix sockets
       +/tmp/kak-<session>+
 * +-e <commands>+: execute commands on startup
 * +-n+: ignore kakrc file
 * +-s <session>+: set the session name, by default it will be the pid
       of the initial kak process.
 * +-d+: run Kakoune in daemon mode, without user interface. This requires
       the session name to be specified with -s. In this mode, the Kakoune
       server will keep running even if there is no connected client, and
       will quit when receiving SIGTERM.

Basic Movement
--------------

 * _space_: select the character under selection end
 * _alt-space_: flip the selections

 * _h_: select the character on the right of selection end
 * _j_: select the character below the selection end
 * _k_: select the character above the selection end
 * _l_: select the character on the left of selection end

 * _w_: select the word and following whitespaces  on the right of selection end
 * _b_: select preceding whitespaces and the word on the left of selection end
 * _e_: select preceding whitespaces and the word on the right of selection end
 * _alt-[wbe]_: same as [wbe] but select WORD instead of word

 * _x_: select line on which selection end lies (or next line when end lies on
        an end-of-line)
 * _alt-x_: expand selections to contain full lines (including end-of-lines)
 * _alt-X_: trim selections to only contain full lines (not including last
            end-of-line)

 * _%_: select whole buffer

 * _alt-H_: select to line begin
 * _alt-L_: select to line end

 * _/_: search (select next match)
 * _?_: search (extend to next match)
 * _n_: select next match
 * _N_: add a new selection with next match
 * _alt-n_: replace main selection with next match (preserving the others)

 * _pageup_: scroll up
 * _pagedown_: scroll down

 * _alt-r_: rotate selections (the main selection becomes the next one)

Appending
---------

for most selection commands, using shift permits to extend current selection
instead of replacing it. for example, _wWW_ selects 3 consecutive words

Using Counts
------------

Most selection commands also support counts, which are entered before the
command itself.

for example, _3W_ selects 3 consecutive words and _3w_ select the third word on
the right of selection end.

 * _space_: when used with count, keep only the counth selection
 * _alt-space_: when used with count, remove the counth selection

Changes
-------

 * _i_: insert before current selection
 * _a_: insert after current selection
 * _d_: yank and delete current selection
 * _c_: yank and delete current selection and insert

 * _I_: insert at current selection begin line start
 * _A_: insert at current selection end line end
 * _o_: insert in a new line below current selection end
 * _O_: insert in a new line above current selection begin

 * _p_: paste after current selection end
 * _P_: paste before current selection begin
 * _alt-p_: replace current selection with yanked text

 * _alt-j_: join selected lines
 * _alt-J_: join selected lines and select spaces inserted
            in place of line breaks

 * _>_: indent selected lines
 * _<_: deindent selected lines

 * _|_: pipe each selections through the given external filter program
        and replace with it's output.

 * _u_: undo last change
 * _U_: redo last change

 * _r_: replace each character with the next entered one
 * _&_: align selection, align the last character of selections by
        inserting spaces the last character
 * _alt-&_: align selection, align the last character of selections by
        inserting spaces before the selection begin
 * _`_: to lower case
 * _~_: to upper case
 * _alt-`_: swap case

 * _alt-R_: rotate selections content

Goto Commands
-------------

Commands begining with g are used to goto certain position and or buffer:

 * _gh_: select to line begin
 * _gl_: select to line end

 * _gg_, _gk_: go to the first line
 * _gj_: go to the last line

 * _gt_, _gk_: go to the first displayed line
 * _gc_, _gk_: go to the middle displayed line
 * _gb_: go to the last displayed line

 * _ga_: go to the previous (alternate) buffer
 * _gf_: open the file whose name is selected

View commands
-------------

Some commands, all begining with v permit to manipulate the current
view.

 * _vv_ or _vc_: center the main selection in the window
 * _vt_: scroll to put the main selection on the top line of the window
 * _vb_: scroll to put the main selection on the bottom line of the window
 * _vh_: scroll the window count columns left
 * _vj_: scroll the window count line downward
 * _vk_: scroll the window count line upward
 * _vl_: scroll the window count columns right

Jump list
---------

Some commands, like the goto commands, buffer switch or search commands,
push the previous selections to the client's jump list. It is possible
to forward or backward in the jump list using:

 * _control-i_: Jump forward
 * _control-o_: Jump backward
 * _control-s_: save current selections

Multi Selection
---------------

Kak was designed from the start to handle multiple selections.
One way to get a multiselection is via the _s_ key.

For example, to change all occurences of word 'roger' to word 'marcel'
in a paragraph, here is what can be done:

select the paragraph with enough _x_. press _s_ and enter roger then enter.
now paragraph selection was replaced with multiselection of each roger in
the paragraph. press _c_ and marcel<esc> to replace rogers with marcels.

A multiselection can also be obtained with _S_, which splits the current
selection according to the regex entered. To split a comma separated list,
use _S_ then ', *'

_s_ and _S_ share the search pattern with _/_, and hence entering an empty
pattern uses the last one.

As a convenience, _alt-s_ allows you to split the current selections on
line boundaries.

To clear multiple selections, use _space_. To keep only the nth selection
use _n_ followed by _space_, to remove only the nth selection, use _n_
followed by _alt-space_.

_alt-k_ allows you to enter a regex and keep only the selections that
contains a match for this regex. using _alt-K_ you can keep the selections
not containing a match.

Object Selection
----------------

Some keys allow you to select a text object:

 * _alt-a_: selects the whole object
 * _alt-i_: selects the inner object, that is the object excluding it's surrounder.
            for example, for a quoted string, this will not select the quote, and
            for a word this will not select trailing spaces.
 * _[_: selects to object start
 * _]_: selects to object end
 * _{_: extends selections to object start
 * _}_: extends selections to object end

After this key, you need to enter a second key in order to specify which
object you want.

 * _b_, _(_ or _)_: select the enclosing parenthesis
 * _B_, _{_ or _}_: select the enclosing {} block
 * _r_, _[_ or _]_: select the enclosing [] block
 * _<_ or _>_: select the enclosing <> block
 * _"_: select the enclosing double quoted string
 * _'_: select the enclosing single quoted string
 * _w_: select the whole word
 * _W_: select the whole WORD
 * _s_: select the sentence
 * _p_: select the paragraph
 * _i_: select the current indentation block

For nestable objects, a count can be used in order to specify which surrounding
level to select.

Registers
---------

registers are named list of text. They are used for various purpose, like
storing the last yanked test, or the captures groups associated with the
selections.

While in insert mode, ctrl-r followed by a register name (one character)
inserts it.

For example, ctrl-r followed by " will insert the currently yanked text.
ctrl-r followed by 2 will insert the second capture group from the last regex
selection.

Registers are lists, instead of simply text in order to interact well with
multiselection. Each selection have it's own captures, or yank buffer.

Search selection
----------------

Using the _*_ key, you can set the search pattern to the current selection.
This tries to be intelligent. It will for example detect if current selection
begins and/or end at word boundaries, and set the search pattern accordingly.

with _alt-*_ you can set the search pattern to the current seletion without
kakoune trying to be smart.

Basic Commands
--------------

Commands are entered using +:+.

 * +e[dit] <filename> [<line> [<column>]]+: open buffer on file, go to given
     line and column. If file is already opened, just switch to this file.
     use edit! to force reloading.
 * +w[rite] [<filename>]+: write buffer to <filename> or use it's name if
      filename is not given.
 * +q[uit]+: exit Kakoune, use quit! to force quitting even if there is some
      unsaved buffers remaining.
 * +wq+: write current buffer and quit
 * +b[uffer] <name>+: switch to buffer <name>
 * +d[el]b[uf] [<name>]+: delete the buffer <name>, use d[el]b[uf]! to force
      deleting a modified buffer.
 * +source <filename>+: execute commands in <filename>
 * +runtime <filename>+: execute commands in <filename>, <filename>
      is relative to kak executable path.
 * +nameclient <name>+: set current client name
 * +namebuf <name>+: set current buffer name
 * +exec [-client <name>] [-draft [-itersel]] <keys>+: execute <keys> as if
     pressed in normal mode. if +client+ if specified, exec keys in the named
     client context. if +draft+ is specified, execute the keys in a draft
     context. if +itersel+ is specified, apply the keys on each selection
     separately.
 * +eval [-client <name>] [-draft [-itersel]] <command>+: execute <command> as
     if entered in command line. +draft+, +client+ and +itersel+ works the same
     as for the +exec+ command.
 * +echo <text>+: show <text> in status line
 * +name <name>+: sets current client name to name
 * +nop+: does nothing, but as with every other commands, arguments may be
      evaluated. So nop can be used for example to execute a shell command
      while being sure that it's output will not be interpreted by kak.
      +:%sh{ echo echo tchou }+ will echo tchou in kakoune, whereas
      +:nop %sh{ echo echo tchou }+ will not, but both will execute the
      shell command.

String syntax
-------------

When entering a command, parameters are separated by whitespace (shell like),
if you want to give parameters with spaces, you should quote them.

Kakoune support three string syntax:

 * +"strings" and \'strings\'+: classic strings, use \' or \" to escape the
     separator.

 * +%\{strings\}+: these strings are very useful when entering commands

   - the '{' and '}' delimiter are configurable: you can use any non
     alphanumeric character. like %[string], %<string>, %(string), %~string~
     or %!string!...
   - if the character following the % is one of {[(<, then the closing one is
     the matching }])> and the delimiters are not escapable but are nestable.
     for example +%{ roger {}; }+ is a valid string, +%{ marcel \}+ as well.

Options
-------

For user configuration, Kakoune supports options.

Options are typed, their type can be

 * +int+: an integer number
 * +bool+: a boolean value, +yes/true+ or +no/false+
 * +yesnoask+: similar to a boolean, but the additional
   value +ask+ is supported.
 * +str+: a string, some freeform text
 * +regex+: as a string but the +set+ commands will complain
   if the entered text is not a valid regex.
 * +{int,str}-list+: a list, elements are separated by a colon (:)
   if an element needs to contain a colon, it can be escaped with a
   backslash.

Options value can be changed using the +set+ commands:

--------------------------------------------------------------
:set [global,buffer,window] <option> <value> # buffer, window, or global scope
--------------------------------------------------------------

Option values can be different by scope, an option can have a global
value, a buffer value and a window value. The effective value of an
option depends on the current context. If we have a window in the
context (interactive edition for example), then the window value
(if any) is used, if not we try the buffer value (if we have a buffer
in the context), and if not we use the global value.

That means that two windows on the same buffer can use different options
(like different filetype, or different tabstop). However some options
might end up ignored if their scope is not in the command context:

Writing a file never uses the window options for example, so any
options related to writing wont be taken into account if set in the
window scope (+BOM+ or +eolformat+ for example).

New options can be declared using the +decl+ command:

-----------------------------
:decl <type> <name> [<value>]
-----------------------------

Some options are built in kakoune, and can be used to control it's behaviour:

 * +tabstop+ _int_: width of a tab character.
 * +indentwidth+ _int_: width (in spaces) used for indentation.
   0 means a tab character.
 * +scrolloff+ _int_: number of lines to keep visible above/below
   the cursor when scrolling.
 * +eolformat+ _string_ ('lf' or 'crlf'): the format of end of lines when
   writing a buffer, this is autodetected on load.
 * +BOM+ _string_ ("no" or "utf-8"): define if the file should be written
   with an unicode byte order mark.
 * +shell+ _string_ ("bash" by default): what command to run to evaluate
   shell commands.
 * +complete_prefix+ _bool_: when completing in command line, and multiple
   candidates exist, enable completion with common prefix.
 * +incsearch+ _bool_: execute search as it is typed
 * +aligntab+ _bool_: use tabs for alignement command
 * +autoinfo+ _bool_: display automatic information box for certain commands.
 * +autoshowcompl+ _bool_: automatically display possible completions when
   editing a prompt.
 * +ignored_files+ _regex_: filenames matching this regex wont be considered
   as candidates on filename completion (except if the text being completed
   already matches it).
 * +filetype+ _str_: arbitrary string defining the type of the file
   filetype dependant actions should hook on this option changing for
   activation/deactivation.
 * +completions+ _str-list_: option used for external completion, the
   first string should follow the format
   _<line>.<column>[+<length>]@<timestamp>_ to define where the completion
   apply in the buffer, and the other strings are the candidates.
 * +path+ _str-list_: directories to search for gf command.
 * +completers+ _str-list_: completion systems to use for insert mode
   completion. Support +option+ which use the +completions+ option, and
   +word=all+ or +word=buffer+ which complete using words in all buffers
   (+word=all+) or only the current one (+word=buffer+)
 * +insert_hide_sel+ _bool_: hide the selection (except the last
   element) in insert mode
 * +autoreload+ _yesnoask_: auto reload the buffers when an external
   modification is detected.

Insert mode completion
----------------------

Kakoune can propose completions while inserting text, the +completers+ option
control automatic completion, which kicks in when a certain idle timeout is
reached (100 milliseconds). Insert mode completion can be explicitely triggered
using *control-x*, followed, by:

 * *f* : filename completion
 * *w* : buffer word completion
 * *o* : option based completion

Highlighters
------------

Manipulation of the displayed text is done through highlighters, which can be added
or removed with the command

-----------------------------------------------------
:addhl <highlighter_name> <highlighter_parameters...>
-----------------------------------------------------

and

----------------------
:rmhl <highlighter_id>
----------------------

existing highlighters are:

 * +number_lines+: show line numbers
 * +group <group_name>+: highlighter group, containing other highlighters. 
       useful when multiple highlighters work together and need to be
       removed as one. Adding and removing from a group can be done using
       `:addhl -group <group> <highlighter_name> <highlighter_parameters...>`
       `:rmhl  -group <group> <highlighter_name>`
 * +regex <ex> <color>...+: highlight a regex, takes the regex as first parameter,
       followed by any number of color parameters. color format is:
       <capture_id>:<fg_color>[,<bg_color>]
       For example: `:addhl regex //(\h+TODO:)?[^\n]+ 0:cyan 1:yellow,red`
       will highlight C++ style comments in cyan, with an eventual 'TODO:' in
       yellow on red background.
 * +search <color>+: highlight every matches to the current search pattern. takes
       one parameter for the color to apply to highlighted elements.
 * +flag_lines <flag> <option_name>+: add a column in front of text, and display the
       given flag in it for everly lines contained in the int-list option named
       <option_name>.

Hooks
-----

commands can be registred to be executed when certain events arise.
to register a hook, use the hook command.

------------------------------------------------------
:hook <scope> <hook_name> <filtering_regex> <commands>
------------------------------------------------------

<scope> can be either global, buffer or window (or any of their prefixes),
the scope are hierarchical, meaning that a Window calling a hook will
execute it's own, the buffer ones and the global ones.

<command> is a string containing the commands to execute when the hook is
called.

for example, to automatically use line numbering with .cc files,
use the following command:

-----------------------------------------------------
:hook global WinCreate .*\.cc %{ addhl number_lines }
-----------------------------------------------------

existing hooks are:

 * +NormalIdle+: A certain duration has passed since last key was pressed in
       normal mode.
 * +NormalBegin+: Entering normal mode
 * +NormalEnd+: Leaving normal mode
 * +NormalKey+: A key is received in normal mode, the key is used for filtering
 * +InsertIdle+: A certain duration has passed since last key was pressed in
       insert mode.
 * +InsertBegin+: Entering insert mode
 * +InsertEnd+: Leaving insert mode
 * +InsertKey+: A key is received in insert mode, the key is used for filtering
 * +InsertMove+: The cursor moved (without inserting) in insert mode, the key
       that triggered the move is used for filtering
 * +WinCreate+: A window was created, the filtering text is the buffer name
 * +WinClose+: A window was detroyed, the filtering text is the buffer name
 * +WinDisplay+: A window was bound a client, the filtering text is the buffer
       name
 * +WinSetOption+: An option was set in a window context, the filtering text
       is '<option_name>=<new_value>'
 * +BufNew+: A buffer for a new file has been created, filename is used for
       filtering
 * +BufOpen+: A buffer for an existing file has been created, filename is
       used for filtering
 * +BufCreate+: A buffer has been created, filename is used for filtering
 * +RuntimeError+: an error was encountered while executing an user command
       the error message is used for filtering
 * +KakBegin+: Kakoune started, this is called just after reading the user
       configuration files
 * +KakEnd+: Kakoune is quitting.

when not specified, the filtering text is an empty string.

Key Mapping
-----------

You can redefine keys meaning using the map command

------------------------------------------------------
:map <scope> <mode> <key> <keys>
------------------------------------------------------

with +scope+ being one of +global, buffer or window+ (or any prefix),
mode being +insert, normal, prompt or menu+ (or any prefix), +key+ being
a single key name and +keys+ a list of keys.

Color Aliases
-------------

Colorspec takes the form <fg_color>[,<bg_color>], they can be named using the
following command.

--------------------------
:colalias <name> <colspec>
--------------------------

note that colspec can itself be a color alias.

Using color alias instead of colorspec permits to change the effective colors
afterward.

there are some builtins color aliases:

 * +PrimarySelection+: main selection color for every selected character except
     the last one
 * +SecondarySelection+: secondary selection color for every selected character
     except the last one
 * +PrimaryCursor+: last character of the primary selection
 * +SecondaryCursor+: last character of the secondary selection
 * +LineNumbers+: colors used by the number_lines highlighter
 * +MenuForeground+: colors for the selected element in menus
 * +MenuBackground+: colors for the not selected elements in menus
 * +Information+: colors the informations windows and information messages
 * +Error+: colors of error messages
 * +StatusLine+: colors used for the status line
 * +StatusCursor+: colors used for the status line cursor
 * +Prompt+: colors used prompt displayed on the status line

Shell expansion
---------------

A special string syntax is supported which replace it's content with the
output of the shell commands in it, it is similar to the shell $(...)
syntax and is evaluated only when needed.
for example: %sh{ ls } is replaced with the output of the ls command.

Some of kakoune state is available through environment variables:

 * +kak_selection+: content of the main selection
 * +kak_selections+: content of the selection separated by commas
 * +kak_bufname+: name of the current buffer
 * +kak_timestamp+: timestamp of the current buffer, the timestamp is an
       integer value which is incremented each time the buffer is modified.
 * +kak_runtime+: directory containing the kak binary
 * +kak_opt_<name>+: value of option <name>
 * +kak_reg_<r>+: value of register <r>
 * +kak_socket+: filename of session socket (/tmp/kak-<session>)
 * +kak_client+: name of current client
 * +kak_cursor_line+: line of the end of the main selection
 * +kak_cursor_cursor+: column of the end of the main selection
 * +kak_hook_param+: filtering text passed to the currently executing hook

for example you can print informations on the current file in the status
line using:

-------------------------------
:echo %sh{ ls -l $kak_bufname }
-------------------------------

Register and Option expansion
-----------------------------

Similar to shell expansion, register contents and options values can be
accessed through %reg{<register>} and %opt{<option>} syntax.

for example you can display last search pattern with

-------------
:echo %reg{/}
-------------

Defining Commands
-----------------

new commands can be defined using the +def+ command.

------------------------------
:def <command_name> <commands>
------------------------------

<commands> is a string containing the commands to execute

def can also takes some flags:

 * +-env-params+: pass parameters given to commands in the environement as
                  kak_paramN with N the parameter number
 * +-shell-params+: pass parameters given to commands as positional parameters
                    to any shell expansions used in the command.
 * +-file-completion+: try file completion on any parameter passed
                       to this command
 * +-shell-completion+: following string is a shell command which takes
                        parameters as positional params and output one
                        completion candidate per line.
 * +-allow-override+: allow the new command to replace an exisiting one
                      with the same name.

Using shell expansion permits to define complex commands or to access
kakoune state:

------------------------------------------------------
:def print_selection %{ echo %sh{ ${kak_selection} } }
------------------------------------------------------

Some helper commands can be used to define composite commands:

 * +menu <label1> <commands1> <label2> <commands2>...+: display a menu using
     labels, the selected label's commands are executed.
     +menu+ can take a -auto-single argument, to automatically run commands
     when only one choice is provided. and a -select-cmds argument, in which
     case menu takes three argument per item, the last one being a command
     to execute when the item is selected (but not validated).
 * +info <text>+: display text in an information box, at can take a -anchor
     option, which accepts +left+, +right+ and +cursor+ as value, in order to
     specify where the info box should be anchored relative to the main selection.
 * +try <commands> catch <on_error_commands>+: prevent an error in <commands>
     from aborting the whole commands execution, execute <on_error_commands>
     instead. If nothing is to be done on error, the catch part can be ommitted.
 * +reg <name> <content>+: set register <name> to <content>

Note that these commands are available in interactive command mode, but are
not that useful in this context.

FIFO Buffer
-----------

the +edit+ command can take a -fifo parameter:

-----------------------------------
:edit -fifo <filename> <buffername>
-----------------------------------

in this case, a buffer named +<buffername>+ is created which reads its content
from fifo +<filename>+. When the fifo is written to, the buffer is automatically
updated.

This is very useful for running some commands asynchronously while displaying
their result in a buffer. See rc/make.kak and rc/grep.kak for examples.

When the buffer is deleted, the fifo will be closed, so any program writing
to it will receive SIGPIPE. This is usefull as it permits to stop the writing
program when the buffer is deleted.

Menus
-----

When a menu is displayed, you can use *j*, *control-n* or *tab* to select the next
entry, and *k*, *control-p* or *shift-tab* to select the previous one.

Using the */* key, you can enter some regex in order to restrict available choices
to the matching ones.

Kakrc
-----

The kakrc file next to the kak binary (in the src directory for the moment)
is a list of kak commands to be executed at startup.

The current behaviour is to execute local user commands in the file
$HOME/.config/kak/kakrc and in all files in $HOME/.config/kak/autoload
directory

Place links to the files in src/rc/ in your autoload directory in order to
execute them on startup, or use the runtime command (which sources relative
to the kak binary) to load them on demand.

Existing commands files are:

 * *rc/kakrc.kak*: provides kak commands files autodetection and highlighting
 * *rc/cpp.kak*: provides c/c++ files autodetection and highlighting and the +alt+
     command for switching from c/cpp file to h/hpp one.
 * *rc/asciidoc.kak*: provides asciidoc files autodetection and highlighting
 * *rc/diff.kak*: provides patches/diff files autodetection and highlighting
 * *rc/git.kak*: provides various git format highlighting (commit message editing,
     interactive rebase)
 * *rc/git-tools.kak*: provides some git integration, like +git-blame+, +git-show+
     or +git-diff-show+
 * *rc/make.kak*: provides the +make+ and +errjump+ commands along with highlighting
     for compiler output.
 * *rc/man.kak*: provides the +man+ command 
 * *rc/grep.kak*: provides the +grep+ and +gjump+ commands along with highlighting
     for grep output.
 * *rc/global.kak*: provides the +tag+ command to jump on a tag definition using
     gnu global tagging system.
 * *rc/ctags.kak*: provides the +tag+ command to jump on a tag definition using
     exuberant ctags files, this script requires the *readtags* binary, available
     in the exuberant ctags package but not installed by default.
 * *rc/client.kak*: provides the +new+ command to launch a new client on the current
     session, if tmux is detected, launch the client in a new tmux split, else
     launch in a new terminal emulator.
 * *rc/clang.kak*: provides the +clang-enable-autocomplete+ command for C/C++ 
     insert mode completion support. This needs uses clang++ compiler.

Certain command files defines options, such as +grepcmd+ (for :grep) +makecmd+
(for :make) or +termcmd+ (for :new).

Some options are shared with commands. grep and make honor the +toolsclient+ option,
if specified, to open their buffer in it rather than the current client. man honor
the +docsclient+ option for the same purpose.
