Viml datatypes: Difference between revisions

From wikinotes
 
 
(19 intermediate revisions by the same user not shown)
Line 1: Line 1:
= Basics =
= Documentation =
<blockquote>
<blockquote>
{| class="wikitable"
|-
| <code>:h variables</code> || https://vimhelp.org/eval.txt.html#variables
|-
|}
</blockquote><!-- Documentation -->


== Variable Scope ==
= Literals =
Rather than automatically setting scope for variables in vim, by default
<blockquote>
everything is global.
<syntaxhighlight lang="vim">
" boolean
" =======
v:true  " 1
v:false " 0


<source lang="vim">
" strings
:help internal-variables
" =======
let a:var = "test"        "variable 'var' is local to current function
"abcdefg"
 
123
g:var  " global-variable    - Global.
</syntaxhighlight>
l:var  " local-variable    - Local to a function.
</blockquote><!-- Literals -->
s:var  " script-variable    - Local to a :source ed Vim script.
a:var  " function-argument  - Function argument (only inside a function).
 
b:var  " buffer-variable    - Local to the current buffer.
w:var  " window-variable    - Local to the current window.
t:var  " tabpage-variable  - Local to the current tab page.
v:var  " vim-variable      - Global, predefined by Vim.
</source>
 
== Settings ==
<source lang="vim">
set filetype = 'mel'  " assign vim-setting
 
let var = &filetype  " vim-setting TO variable
let &filetype = var  " vim-seteting AS variable
</source>
 
== Variable Persistence ==
This setting sets up vim so that the <code>viminfo</code> file (<code>shada</code> for nvim)
automatically saves/restores global-variables stored in all-caps between vim sessions.
 
Save occurs on vim-exit. Restore occurs during startup (see <code>:help initialization</code>).
 
<source lang="vim">
:set viminfo+=!   
</source>
 
If your plugin depends on loading these variables, during vim's init, you'll
need to write an <code>autocmd</code> to load it.
 
<source lang="vim">
autocmd VimEnter * call RestoreLastModColorscheme()
</source>
</blockquote><!-- core -->


= String/Int Variables =
= String/Int Variables =
Line 54: Line 30:
" Assign
" Assign
let var = 5                          " Int variable
let var = 5                          " Int variable
let var = midnight                   " String variable
let var = "midnight"                " String variable


" Results
" Results
Line 72: Line 48:
let var = $HOME . "/.vimrc"          " concatenate
let var = $HOME . "/.vimrc"          " concatenate
execute 'read ' . vimrc              " execute string with variable
execute 'read ' . vimrc              " execute string with variable
strlen(var)                          " length of string (or empty)
repeat(" ", 3)                      " repeat ' ' character 3 times
</source>
</source>


Line 79: Line 57:
" (beware that 'string' is a raw-string, and "string" requires escaping)
" (beware that 'string' is a raw-string, and "string" requires escaping)
let var = '  string  '
let var = '  string  '
let var = substitute(var, '[^a-zA-Z_\\\-]', '', 'g')
let var = substitute(var, '[^a-zA-Z_\\\-]', '', 'g')


</syntaxhighlight>
</syntaxhighlight>
Line 97: Line 75:
let var=printf('__%s__%s', 'abc', 'def')  "> '__abc__def'
let var=printf('__%s__%s', 'abc', 'def')  "> '__abc__def'
</source>
</source>
If string contains substring
<syntaxhighlight lang="vim">
if stridx("abc def hij", "def") >= 0
</syntaxhighlight>
</blockquote><!-- String/int variables -->
</blockquote><!-- String/int variables -->


Line 107: Line 90:
let var = ['a','b','c']              " Regular List
let var = ['a','b','c']              " Regular List
let var = [['a','b','c'], [1,2,3]]    " Nested List
let var = [['a','b','c'], [1,2,3]]    " Nested List
let var2 = copy(var)                  " Copy a list


" Retrieve Items
" Retrieve Items
Line 112: Line 96:
echo var[0]                          " Item at Index
echo var[0]                          " Item at Index
echo var[0][0]                        " Sublist Item at Index
echo var[0][0]                        " Sublist Item at Index
echo len(var)                        " List Length
echo len(var)                        " List Length/Size
echo get(var, 1)                      " get item at index 1 (returns 0 if not set)
echo get(var, 1, 'nope')              " get item at index 1 (returns 'nope' if not set)


" Usage
" Usage
Line 118: Line 104:
let var = ['a','b','c'] + ['d','e']  " Extend List
let var = ['a','b','c'] + ['d','e']  " Extend List
remove(list, 0)                      " Remove index from list
remove(list, 0)                      " Remove index from list
call filter(list, 'v:val=="a"')       " Remove item from list
call filter(list, 'v:val=="a"')       " Remove item from list
index(list, 'f')                      " Index of Item
index(list, 'f')                      " Index of Item
if (index(mylist, 'a') >= 0)          " Item in list
if (index(mylist, 'a') >= 0)          " Item in list
call sort(['b', 'a', 'c'])            " Sort a list
call sort(['b', 'a', 'c'])            " Sort a list
call sort(                            " Sort list with a lambda
  \ [['a', 2], ['b', 1']],
  \ {l1, l2 -> l1[1] > l2[1]})
for item in ['a','b', 'c']            " iterate over list
call filter(name['namespace'], '!empty(v:val)')                " remove empty items from list
call filter(name['namespace'], '!empty(v:val)')                " remove empty items from list
call filter(copy(mylist), 'index(mylist, v:val, v:key+1)==-1')  " remove duplicates from list
call filter(copy(mylist), 'index(mylist, v:val, v:key+1)==-1')  " remove duplicates from list
" Slices
let foo = ['a', 'b', 'c']
let bar = foo[1:-1]        " ['b', 'c']
" subtract lists (WARNING: MUTATES LIST IF COPY NOT USED!)
let foo = ['a', 'b', 'c']
let bar = ['c']
filter(copy(foo), 'index(bar, v:val)<0')  " ['a', 'b']
</source>
</source>
</blockquote><!-- lists -->
</blockquote><!-- lists -->
Line 140: Line 139:
echo var['a']
echo var['a']
echo var.a
echo var.a
echo get(var, 'a')              " Get value of key 'a', or 0 if not assigned
echo get(var, 'a', 'nope')      " Get value of key 'a', or 'nope' if not assigned


let var.a    = 'abcdefg'        " Modify Item in dictionary
let var.a    = 'abcdefg'        " Modify Item in dictionary
Line 147: Line 148:
remove var.a
remove var.a


extend(adict, bdict)            " merge/update a dictionary  
extend(adict, bdict)            " merge/update a dictionary


for k in keys(dictionary)      " iterate over dict keys
for k in keys(dictionary)      " iterate over dict keys

Latest revision as of 00:37, 8 April 2023

Documentation

:h variables https://vimhelp.org/eval.txt.html#variables

Literals

" boolean
" =======
v:true  " 1
v:false " 0

" strings
" =======
"abcdefg"
123

String/Int Variables

vim doesn't really use variable types. They're all treated as strings, and expanded as ints, etc wherever they are needed.

" Assign
let var = 5                          " Int variable
let var = "midnight"                 " String variable

" Results
let var = getcwd()                   " call function result
let var = $HOME                      " envvar result
let var = pyeval('platform.node()')  " python result as vim var
py val = vim.eval('your#script()')   " vim result as python var
let var = system("ls -la")           " process result
let var = @%                         " ?internalvar? result

" String Types
let var = 'some\string'              " raw-strings use single-quotes
let var = "some\\string"             " normal-strings use double-quotes

" Usage
var[2:-1]                            " String Slices
let var = $HOME . "/.vimrc"          " concatenate
execute 'read ' . vimrc              " execute string with variable
strlen(var)                          " length of string (or empty)
repeat(" ", 3)                       " repeat ' ' character 3 times

Substitute

" Performs like as s/[^a-zA-Z_\-]//g
" (beware that 'string' is a raw-string, and "string" requires escaping)
let var = '   string   '
let var = substitute(var, '[^a-zA-Z_\\\-]', '', 'g')

Split

let var = split('/abc/def/ghi', '/')

Join

call join(["a", "b", "c"], ".")    "> a.b.c

String Formatting

let var=printf('__%s__%s', 'abc', 'def')   "> '__abc__def'

If string contains substring

if stridx("abc def hij", "def") >= 0

Lists

Lists are syntactically very similar to python.

" Assign Lists
let var = ['a','b','c']               " Regular List
let var = [['a','b','c'], [1,2,3]]    " Nested List
let var2 = copy(var)                  " Copy a list

" Retrieve Items
echo var[-1]                          " Negative Index
echo var[0]                           " Item at Index
echo var[0][0]                        " Sublist Item at Index
echo len(var)                         " List Length/Size
echo get(var, 1)                      " get item at index 1 (returns 0 if not set)
echo get(var, 1, 'nope')              " get item at index 1 (returns 'nope' if not set)

" Usage
call add(list, 'f')                   " Append to List
let var = ['a','b','c'] + ['d','e']   " Extend List
remove(list, 0)                       " Remove index from list
call filter(list, 'v:val=="a"')        " Remove item from list
index(list, 'f')                      " Index of Item
if (index(mylist, 'a') >= 0)          " Item in list
call sort(['b', 'a', 'c'])            " Sort a list
call sort(                            " Sort list with a lambda
  \ [['a', 2], ['b', 1']],
  \ {l1, l2 -> l1[1] > l2[1]})
for item in ['a','b', 'c']            " iterate over list
call filter(name['namespace'], '!empty(v:val)')                 " remove empty items from list
call filter(copy(mylist), 'index(mylist, v:val, v:key+1)==-1')  " remove duplicates from list

" Slices
let foo = ['a', 'b', 'c']
let bar = foo[1:-1]        " ['b', 'c']

" subtract lists (WARNING: MUTATES LIST IF COPY NOT USED!)
let foo = ['a', 'b', 'c']
let bar = ['c']
filter(copy(foo), 'index(bar, v:val)<0')  " ['a', 'b']

Dictionaries

Dictionaries in vimscript are almost identical to dictionaries in python.
See https://vimhelp.org/eval.txt.html#Dictionaries

let var = {'a':100, 'b':200}    " Dictionary keys must be strings
let var = {
    \ "a": 100,
    \ "b": 200,
    \}
echo var['a']
echo var.a
echo get(var, 'a')              " Get value of key 'a', or 0 if not assigned
echo get(var, 'a', 'nope')      " Get value of key 'a', or 'nope' if not assigned

let var.a    = 'abcdefg'        " Modify Item in dictionary
let var['a'] = 'abcdefg'

remove var['a']                 " Remove Item to dictionary
remove var.a

extend(adict, bdict)            " merge/update a dictionary

for k in keys(dictionary)       " iterate over dict keys
for v in values(dictionary)
for [k,v] in items(dictionary)

has_key(var, 'a')                " Test if dict has a particular key