├── README.md └── VimScriptForPythonDevelopers.MD /README.md: -------------------------------------------------------------------------------- 1 | # Vim Script For Python Developers 2 | 3 | A guide to Vim Script development for Python developers. Sample code for the various expressions, statements, functions and programming constructs is shown in both Python and Vim Script. This is not intended to be a tutorial for developing Vim scripts. It is assumed that the reader is familiar with Python programming. 4 | 5 | For an introduction to Vim Script development, refer to [usr_41.txt](https://vimhelp.org/usr_41.txt.html), [eval.txt](https://vimhelp.org/eval.txt.html) and [Learn Vimscript the Hard Way](https://learnvimscriptthehardway.stevelosh.com/) 6 | 7 | For a guide similar to this one for JavaScript developers, refer to [Vim Script for the JavaScripter](https://w0rp.com/blog/post/vim-script-for-the-javascripter/) 8 | 9 | This guide only describes the programming constructs that are present in both Python and Vim. The constructs that are unique to Vim (e.g. [autocommands](https://vimhelp.org/autocmd.txt.html#autocommands), [key-mapping](https://vimhelp.org/map.txt.html#key-mapping), [abbreviations](https://vimhelp.org/map.txt.html#abbreviations), [user-commands](https://vimhelp.org/map.txt.html#user-commands), [plugins](https://vimhelp.org/usr_05.txt.html#plugin), etc.) are not described in this guide. 10 | 11 | Some of the features described in this guide are available only in the recent versions of Vim (8.2). 12 | -------------------------------------------------------------------------------- /VimScriptForPythonDevelopers.MD: -------------------------------------------------------------------------------- 1 | # Vim Script for Python Developers 2 | 3 | This is a guide to Vim Script development for Python developers. Sample code for the various expressions, statements, functions and programming constructs is shown in both Python and Vim Script. This is not intended to be a tutorial for developing Vim scripts. It is assumed that the reader is familiar with Python programming. 4 | 5 | For an introduction to Vim Script development, refer to [usr_41.txt](https://vimhelp.org/usr_41.txt.html), [eval.txt](https://vimhelp.org/eval.txt.html) and [Learn Vimscript the Hard Way](https://learnvimscriptthehardway.stevelosh.com/) 6 | 7 | For a guide similar to this one for JavaScript developers, refer to [Vim Script for the JavaScripter](https://w0rp.com/blog/post/vim-script-for-the-javascripter/) 8 | 9 | This guide only describes the programming constructs that are present in both Python and Vim. The constructs that are unique to Vim (e.g. [autocommands](https://vimhelp.org/autocmd.txt.html#autocommands), [key-mapping](https://vimhelp.org/map.txt.html#key-mapping), [abbreviations](https://vimhelp.org/map.txt.html#abbreviations), [user-commands](https://vimhelp.org/map.txt.html#user-commands), [plugins](https://vimhelp.org/usr_05.txt.html#plugin), etc.) are not described in this guide. 10 | 11 | Some of the features described in this guide are available only in the recent versions of Vim (8.2). 12 | 13 | The Github repository for this gist is available at: https://github.com/yegappan/VimScriptForPythonDevelopers. 14 | 15 | ------------------------------------------------------------------------------ 16 | 17 | ## Table of Contents 18 | * [Literals](#literals) 19 | * [Variables](#variables) 20 | * [Operators](#operators) 21 | * [String](#string) 22 | * [List](#list) 23 | * [Tuple](#tuple) 24 | * [Dictionary](#dictionary) 25 | * [If Statement](#if-statement) 26 | * [For Loop](#for-loop) 27 | * [While Loop](#while-loop) 28 | * [Comment](#comment) 29 | * [Function](#function) 30 | * [Lambda Function](#lambda-function) 31 | * [Partial Function](#partial-function) 32 | * [Closure](#closure) 33 | * [Class](#class) 34 | * [Exception Handling](#exception-handling) 35 | * [Line Continuation](#line-continuation) 36 | * [File Operations](#file-operations) 37 | * [Directory Operations](#directory-operations) 38 | * [Random Numbers](#random-numbers) 39 | * [Mathematical Functions](#mathematical-functions) 40 | * [Date/Time Functions](#datetime-functions) 41 | * [External Commands](#external-commands) 42 | * [User Input/Output](#user-inputoutput) 43 | * [Environment Variables](#environment-variables) 44 | * [Command Line Arguments](#command-line-arguments) 45 | * [Regular Expressions](#regular-expressions) 46 | * [Binary Data](#binary-data) 47 | * [Timers](#timers) 48 | * [JSON encoder and decoder](#json-encoder-and-decoder) 49 | * [Network Sockets](#network-sockets) 50 | * [Background Processes](#background-processes) 51 | * [Unit Tests](#unit-tests) 52 | 53 | ------------------------------------------------------------------------------ 54 | 55 | ## Literals 56 | 57 | Type| Python | VimScript 58 | ----|--------|--------- 59 | integer| `-1, 0, 5` | `-1, 0, 5` 60 | binary| `0b1011` | `0b1011` 61 | octal| `0o477` | `0477` 62 | hexadecimal| `0x1AE` | `0x1AE` 63 | float| `3.14, -1.5e2` | `3.14, -1.5e2` 64 | string| `"hello", 'world'` | `"hello", 'world'` 65 | boolean| `True, False` | `v:true, v:false` 66 | list| `[], [5, 9], ['a', 'b']` | `[], [5, 9], ['a', 'b']` 67 | tuple| `(), (1,), (5, 9), ('a', 'b')` | `(), (1,), (5, 9), ('a', 'b')` 68 | dict| `{}, {'idx' : 2, 'name' : 'abc'}` | `{}, {'idx' : 2, 'name' : 'abc'}` 69 | special| `None` | `v:none, v:null` 70 | 71 | *Help:* [expr-number](https://vimhelp.org/eval.txt.html#expr-number), [string](https://vimhelp.org/eval.txt.html#string), [Boolean](https://vimhelp.org/eval.txt.html#Boolean), [list](https://vimhelp.org/eval.txt.html#list), [tuple](https://vimhelp.org/eval.txt.html#tuple), [dict](https://vimhelp.org/eval.txt.html#dict), [v:none](https://vimhelp.org/eval.txt.html#v:none), [v:null](https://vimhelp.org/eval.txt.html#v:null) 72 | 73 | ------------------------------------------------------------------------------ 74 | 75 | ## Variables 76 | 77 | ### Creating a Variable 78 | **Python:** 79 | ```python 80 | i = 10 81 | pi = 3.1415 82 | str = "Hello" 83 | a, b, s = 10, 20, "sky" 84 | ``` 85 | 86 | **VimScript:** 87 | ```vim 88 | let i = 10 89 | let pi = 3.1415 90 | let str = "Hello" 91 | let [a, b, s] = [10, 20, "sky"] 92 | ``` 93 | 94 | *Help:* [variables](https://vimhelp.org/eval.txt.html#variables) 95 | 96 | ### Deleting a Variable 97 | **Python:** 98 | ```python 99 | del str 100 | ``` 101 | 102 | **VimScript:** 103 | ```vim 104 | unlet str 105 | ``` 106 | 107 | *Help:* [:unlet](https://vimhelp.org/eval.txt.html#%3Aunlet) 108 | 109 | ### Here Document 110 | Assigning multi-line values to a variable. 111 | 112 | **Python:** 113 | ```python 114 | import textwrap 115 | i = textwrap.dedent(""" 116 | one 117 | two three 118 | four 119 | five 120 | """.lstrip('\n')).splitlines() 121 | # i == ['one', 'two three', ' four', 'five'] 122 | ``` 123 | 124 | **VimScript:** 125 | ```vim 126 | let i =<< trim END 127 | one 128 | two three 129 | four 130 | five 131 | END 132 | " i == ['one', 'two three', ' four', 'five'] 133 | ``` 134 | 135 | *Help:* [:let-heredoc](https://vimhelp.org/eval.txt.html#%3Alet-heredoc) 136 | 137 | ### Types 138 | 139 | Type|Python|VimScript 140 | ----|------|--------- 141 | Number| `num = 10` | `let num = 10` 142 | Float| `f = 3.4` | `let f = 3.4` 143 | Booelan| `done = True` | `let done = v:true` 144 | String| `str = "green"` | `let str = "green"` 145 | List| `l = [1, 2, 3]` | `let l = [1, 2, 3]` 146 | Tuple| `t = (1, 2, 3)` | `let t = (1, 2, 3)` 147 | Dictionary| `d = {'a' : 5, 'b' : 6}` | `let d = #{a : 5, b : 6}` 148 | 149 | *Help:* [variables](https://vimhelp.org/eval.txt.html#variables) 150 | 151 | ### Type Conversion 152 | 153 | Conversion|Python|VimScript 154 | ----------|------|--------- 155 | Number to Float| `float(n)` | `floor(n)` 156 | Float to Number| `int(f)` | `float2nr(f)` 157 | Number to String| `str(n)` | `string(n)` 158 | String to Number| `int(str)` | `str2nr(str)` 159 | Float to String| `str(f)` | `string(f)` 160 | String to Float| `float(str)` | `str2float(str)` 161 | List to String| `str(l)` | `string(l)` 162 | String to List| `eval(str)` | `eval(str)` 163 | List to Tuple| `tuple(l)` | `list2tuple(l)` 164 | Tuple to List| `list(t)` | `tuple2list(t)` 165 | Tuple to String| `str(t)` | `string(t)` 166 | String to Tuple| `eval(str)` | `eval(str)` 167 | Dict to String| `str(d)` | `string(d)` 168 | String to Dict| `eval(str)` | `eval(str)` 169 | 170 | *Help:* [string()](https://vimhelp.org/builtin.txt.html#string%28%29), [str2nr()](https://vimhelp.org/builtin.txt.html#str2nr%28%29), [str2float()](https://vimhelp.org/builtin.txt.html#str2float%28%29), [float2nr()](https://vimhelp.org/builtin.txt.html#float2nr%28%29), [floor()](https://vimhelp.org/builtin.txt.html#floor%28%29), [eval()](https://vimhelp.org/builtin.txt.html#eval%28%29), [list2tuple()](https://vimhelp.org/builtin.txt.html#list2tuple%28%29), [tuple2list()](https://vimhelp.org/builtin.txt.html#tuple2list%28%29) 171 | 172 | ### Type Check 173 | 174 | Type|Python|VimScript 175 | ----|------|--------- 176 | Number| `isintance(x, int)` | `type(x) is v:t_number` 177 | String| `isinstance(x, str)` | `type(x) is v:t_string` 178 | List| `isintance(x, list)` | `type(x) is v:t_list` 179 | Tuple| `isintance(x, tuple)` | `type(x) is v:t_tuple` 180 | Dictionary| `isintance(x, dict)` | `type(x) is v:t_dict` 181 | Float| `isintance(x, float)` | `type(x) is v:t_float` 182 | Boolean| `isinstance(x, bool)` | `type(x) is v:t_bool` 183 | 184 | *Help:* [type()](https://vimhelp.org/builtin.txt.html#type%28%29) 185 | 186 | ### Variable Namespaces 187 | 188 | All the variables in VimScript have a scope. The scope is specified by prefixing the variable name with one of the prefix strings shown in the table below. If a variable name is used without a scope prefix, then inside a function the function local scope is used. Otherwise the global variable scope is used. 189 | 190 | Scope Prefix|Description 191 | -----|----------- 192 | g: | global 193 | l: | function-local 194 | s: | script-local 195 | a: | function argument 196 | v: | internal 197 | b: | buffer local 198 | w: | window local 199 | t: | tab local 200 | 201 | *Help:* [global-variable](https://vimhelp.org/eval.txt.html#global-variable), [local-variable](https://vimhelp.org/eval.txt.html#local-variable), [script-variable](https://vimhelp.org/eval.txt.html#script-variable), [function-argument](https://vimhelp.org/eval.txt.html#function-argument), [vim-variable](https://vimhelp.org/eval.txt.html#vim-variable), [buffer-variable](https://vimhelp.org/eval.txt.html#buffer-variable), [window-variable](https://vimhelp.org/eval.txt.html#window-variable), [tabpage-variable](https://vimhelp.org/eval.txt.html#tabpage-variable) 202 | 203 | ------------------------------------------------------------------------------ 204 | 205 | ## Operators 206 | 207 | ### Arithmetic Operators 208 | 209 | What|Python|VimScript 210 | ----|------|--------- 211 | addition| `a = 10 + 20` | `let a = 10 + 20` 212 | subtraction| `a = 30 - 10` | `let a = 30 - 10` 213 | multiplication| `a = 3 * 5` | `let a = 3 * 5` 214 | division| `a = 22 / 7` | `let a = 22 / 7` 215 | modulus| `a = 10 % 3` | `let a = 10 % 3` 216 | exponentiation| `a = 2 ** 3` | `let a = float2nr(pow(2, 3))` 217 | floor division| `a = 10 // 3` | `let a = floor(10 / 3.0)` 218 | 219 | *Help:* [expr5](https://vimhelp.org/eval.txt.html#expr5) 220 | 221 | ### Assignment Operators 222 | 223 | What|Python|VimScript 224 | ----|------|--------- 225 | addition| `a += 1` | `let a += 1` 226 | subtraction| `a -= 2` | `let a -= 2` 227 | multiplication| `a *= 4` | `let a *= 4` 228 | division| `a /= 2` | `let a /= 2` 229 | modulus| `a %= 2` | `let a %= 2` 230 | 231 | *Help:* [:let+=](https://vimhelp.org/eval.txt.html#%3alet+=) 232 | 233 | ### Comparison Operators 234 | 235 | What|Python|VimScript 236 | ----|------|--------- 237 | equal to| `a == b` | `a == b` 238 | not equal to| `a != b` | `a != b` 239 | greater than| `a > b` | `a > b` 240 | less than| `a < b` | `a < b` 241 | greater than or equal to| `a >= b` | `a >= b` 242 | less than or equal to| `a <= b` | `a <= b` 243 | 244 | *Help:* [expr4](https://vimhelp.org/eval.txt.html#expr4) 245 | 246 | ### Logical Operators 247 | 248 | What|Python|VimScript 249 | ----|------|--------- 250 | logical and| `x and y` | `x && y` 251 | logical or| `x or y` | `x \|\| y` 252 | logical not| `not x` | `!x` 253 | 254 | *Help:* [expr2](https://vimhelp.org/eval.txt.html#expr2) 255 | 256 | ### Bitwise Operators 257 | 258 | What|Python|VimScript 259 | ----|------|--------- 260 | bitwise AND| `c = a & b` | `let c = and(a, b)` 261 | bitwise OR| `c = a \| b` | `let c = or(a, b)` 262 | bitwise NOT| `c = ~a` | `let c = invert(a)` 263 | bitwise XOR| `c = a ^ b` | `let c = xor(a, b)` 264 | left shift| `c = a << b` | `let c = a * float2nr(pow(2, b))` 265 | right shift| `c = a >> b` | `let c = float2nr(floor(a / pow(2, b)))` 266 | 267 | *Help:* [and()](https://vimhelp.org/builtin.txt.html#and%28%29), [or()](https://vimhelp.org/builtin.txt.html#or%28%29), [invert()](https://vimhelp.org/builtin.txt.html#invert%28%29), [xor()](https://vimhelp.org/builtin.txt.html#xor%28%29) 268 | 269 | ### Identity Operators 270 | 271 | What|Python|VimScript 272 | ----|------|--------- 273 | is| `x is y` | `x is y` 274 | is not| `x is not y` | `x isnot y` 275 | 276 | *Help:* [expr-is](https://vimhelp.org/eval.txt.html#expr-is), [expr-isnot](https://vimhelp.org/eval.txt.html#expr-isnot) 277 | 278 | ------------------------------------------------------------------------------ 279 | 280 | ## String 281 | 282 | Vim has functions for dealing with both multibyte and non-multibyte strings. Some functions deal with bytes and some functions deal with characters. Refer to the reference guide for the various functions to get the detailed information. 283 | 284 | ### Raw string 285 | 286 | **Python:** 287 | ```python 288 | s1 = r"one\ntwo\n" 289 | s2 = "one\ntwo\n" 290 | ``` 291 | 292 | **VimScript:** 293 | ```vim 294 | let s1 = 'one\ntwo\n' 295 | let s2 = "one\ntwo\n" 296 | ``` 297 | 298 | *Help:* [literal-string](https://vimhelp.org/eval.txt.html#literal-string), [string](https://vimhelp.org/eval.txt.html#string) 299 | 300 | ### Finding string length 301 | 302 | **Python:** 303 | ```python 304 | n = len("Hello World") 305 | ``` 306 | 307 | **VimScript:** 308 | ```vim 309 | " count the number of bytes in a string 310 | let n = len("Hello World") 311 | " count the number of bytes in a string 312 | let n = strlen("Hello World") 313 | " count the number of characters in a string 314 | let n = strcharlen("Hello World") 315 | " count the number of characters in a string 316 | let n = strwidth("Hello World") 317 | ``` 318 | 319 | *Help:* [len()](https://vimhelp.org/builtin.txt.html#len%28%29), [strlen()](https://vimhelp.org/builtin.txt.html#strlen%28%29), [strcharlen()](https://vimhelp.org/builtin.txt.html#strcharlen%28%29), [strwidth()](https://vimhelp.org/builtin.txt.html#strwidth%28%29), [strdisplaywidth()](https://vimhelp.org/builtin.txt.html#strdisplaywidth%28%29) 320 | 321 | ### String Concatenation 322 | 323 | **Python:** 324 | ```python 325 | str1 = "blue" 326 | str2 = "sky" 327 | s = str1 + str2 328 | ``` 329 | 330 | **VimScript:** 331 | ```vim 332 | let str1 = "blue" 333 | let str2 = "sky" 334 | let s = str1 .. str2 335 | 336 | " Deprecated way of concatenating strings 337 | let s = str1 . str2 338 | ``` 339 | 340 | ### String Comparison 341 | 342 | **Python:** 343 | ```python 344 | # compare strings matching case 345 | str1 = "blue" 346 | str2 = "blue" 347 | str3 = "sky" 348 | if str1 == str2: 349 | print("str1 and str2 are same") 350 | if str1 is str2: 351 | print("str1 and str2 are same") 352 | if str1 != str3: 353 | print("str1 and str3 are not same") 354 | if str1 is not str3: 355 | print("str1 and str3 are not same") 356 | 357 | # compare strings ignoring case 358 | str1 = "Blue" 359 | str2 = "BLUE" 360 | str3 = "sky" 361 | if str1.lower() == str2.lower(): 362 | print("str1 and str2 are same") 363 | if str1.lower() != str3.lower(): 364 | print("str1 and str3 are not same") 365 | ``` 366 | 367 | **VimScript:** 368 | ```vim 369 | " compare strings matching case 370 | let str1 = "blue" 371 | let str2 = "blue" 372 | let str3 = "sky" 373 | if str1 ==# str2 374 | echo "str1 and str2 are same" 375 | endif 376 | if str1 is# str2 377 | echo "str1 and str2 are same" 378 | endif 379 | if str1 !=# str3 380 | echo "str1 and str3 are not same" 381 | endif 382 | if str1 isnot# str3 383 | echo "str1 and str3 are not same" 384 | endif 385 | 386 | " compare strings ignoring case 387 | let str1 = "Blue" 388 | let str2 = "BLUE" 389 | let str3 = "sky" 390 | if str1 ==? str2 391 | echo "str1 and str2 are same" 392 | endif 393 | if str1 is? str2 394 | echo "str1 and str2 are same" 395 | endif 396 | if str1 !=? str3 397 | echo "str1 and str3 are not same" 398 | endif 399 | if str1 isnot? str3 400 | echo "str1 and str3 are not same" 401 | endif 402 | ``` 403 | 404 | *Help:* [expr4](https://vimhelp.org/eval.txt.html#expr4) 405 | 406 | ### Getting a substring 407 | 408 | In Python, when using an index range to specify a sequence of characters in a string, the character at the end index is not included. In Vim, the character at the end index is included. The slice() function excludes the character at the end index. 409 | 410 | **Python:** 411 | ```python 412 | str = "HelloWorld" 413 | sub = str[2:5] 414 | ``` 415 | 416 | **VimScript:** 417 | ```vim 418 | let str = "HelloWorld" 419 | " use byte index range 420 | echo str[2:4] 421 | " use a negative byte range 422 | echo str[-3:] 423 | echo str[2:-3] 424 | " use byte index and length 425 | echo strpart(str, 2, 3) 426 | " use character index and length 427 | echo strcharpart(str, 2, 3) 428 | " use the start and end character indexes 429 | echo slice(str, 2, 3) 430 | " exclude the last character 431 | echo slice(str, 6, -1) 432 | ``` 433 | 434 | *Help:* [expr-[:]](https://vimhelp.org/eval.txt.html#expr-[%3a]), [strpart()](https://vimhelp.org/builtin.txt.html#strpart%28%29), [slice()](https://vimhelp.org/builtin.txt.html#slice%28%29) 435 | 436 | ### Counting the occurrences of a substring 437 | 438 | **Python:** 439 | ```python 440 | str = "Hello World" 441 | c = str.count("l") 442 | ``` 443 | 444 | **VimScript:** 445 | ```vim 446 | let str = "Hello World" 447 | let c = str->count("l") 448 | ``` 449 | 450 | *Help:* [count()](https://vimhelp.org/builtin.txt.html#count%28%29) 451 | 452 | ### Finding the position of a substring 453 | 454 | **Python:** 455 | ```python 456 | str = "running" 457 | idx = str.find("nn") # leftmost 458 | idx = str.rfind("ing") # rightmost 459 | # idx == -1 if the substring is not present 460 | ``` 461 | 462 | **VimScript:** 463 | ```vim 464 | let str = "running" 465 | let idx = str->stridx("nn") " leftmost 466 | let idx = str->strridx("ing") " rightmost 467 | " idx == -1 if the substring is not present 468 | ``` 469 | 470 | *Help:* [stridx()](https://vimhelp.org/builtin.txt.html#stridx%28%29), [strridx()](https://vimhelp.org/builtin.txt.html#strridx%28%29) 471 | 472 | ### Checking whether a string starts with or ends with a substring 473 | 474 | **Python:** 475 | ```python 476 | str = "running" 477 | if str.startswith("run"): 478 | print("starts with run") 479 | if str.endswith("ing"): 480 | print("ends with ing") 481 | ``` 482 | 483 | **VimScript:** 484 | ```vim 485 | let str = "running" 486 | if str =~# '^run' 487 | echo "starts with run" 488 | endif 489 | if str[:len('run') - 1] is# 'run' 490 | echo "starts with run" 491 | endif 492 | 493 | if str =~# 'ing$' 494 | echo "ends with ing" 495 | endif 496 | ``` 497 | 498 | *Help:* [expr-=~#](https://vimhelp.org/eval.txt.html#expr-=~#) 499 | 500 | ### Joining strings in a List with a separator 501 | 502 | **Python:** 503 | ```python 504 | s = ":".join(['ab', 'cd', 'ef']) 505 | ``` 506 | 507 | **VimScript:** 508 | ```vim 509 | let s = join(['ab', 'cd', 'ef'], ':') 510 | ``` 511 | 512 | *Help:* [join()](https://vimhelp.org/builtin.txt.html#join%28%29) 513 | 514 | ### Changing the case of letters in a string 515 | 516 | **Python:** 517 | ```python 518 | s = "Hello World" 519 | l = s.lower() 520 | l = s.upper() 521 | ``` 522 | 523 | **VimScript:** 524 | ```vim 525 | let s = "Hello World" 526 | let l = s->tolower() 527 | let l = s->toupper() 528 | ``` 529 | 530 | *Help:* [tolower()](https://vimhelp.org/builtin.txt.html#tolower%28%29), [toupper()](https://vimhelp.org/builtin.txt.html#toupper%28%29) 531 | 532 | ### Replace a substring 533 | 534 | **Python:** 535 | ```python 536 | s = "Hello World" 537 | s2 = s.replace("Hello", "New") 538 | ``` 539 | 540 | **VimScript:** 541 | ```vim 542 | let s = "Hello World" 543 | let s2 = s->substitute("Hello", "New", 'g') 544 | ``` 545 | 546 | *Help:* [substitute()](https://vimhelp.org/builtin.txt.html#substitute%28%29) 547 | 548 | ### Split a string 549 | 550 | **Python:** 551 | ```python 552 | s = "a:b:c" 553 | s2 = s.split(":") 554 | ``` 555 | 556 | **VimScript:** 557 | ```vim 558 | let s = "a:b:c" 559 | let s2 = s->split(":") 560 | ``` 561 | 562 | *Help:* [split()](https://vimhelp.org/builtin.txt.html#split%28%29), [join()](https://vimhelp.org/builtin.txt.html#join%28%29), 563 | 564 | ### Stripping leading and trailing whitespace from a string 565 | 566 | **Python:** 567 | ```python 568 | s = " python " 569 | # strip leading and trailing whitespace 570 | s2 = s.strip() 571 | print(f"<{s2}>") 572 | # strip leading space characters 573 | s2 = s.lstrip(' ') 574 | print(f"<{s2}>") 575 | # strip trailing space characters 576 | s2 = s.rstrip(' ') 577 | print(f"<{s2}>") 578 | ``` 579 | 580 | **VimScript:** 581 | ```vim 582 | let s = " vim " 583 | " strip leading and trailing whitespace 584 | let s2 = s->trim() 585 | echo $"<{s2}>" 586 | " strip leading space characters 587 | let s2 = s->trim(' ', 1) 588 | echo $"<{s2}>" 589 | " strip trailing space characters 590 | let s2 = s->trim(' ', 2) 591 | echo $"<{s2}>" 592 | ``` 593 | 594 | *Help:* [trim()](https://vimhelp.org/builtin.txt.html#trim%28%29) 595 | 596 | ### Checking whether a string contains specific type of characters 597 | 598 | **Python:** 599 | ```python 600 | s = "text" 601 | if s.isalnum(): 602 | print("Contains only alphanumeric characters") 603 | if s.isalpha(): 604 | print("Contains only alphabetic characters") 605 | if s.isdigit(): 606 | print("Contains only digits") 607 | if s.isspace(): 608 | print("Contains only whitespace characters") 609 | if s.isupper(): 610 | print("Contains only uppercase characters") 611 | if s.islower(): 612 | print("Contains only lowercase characters") 613 | ``` 614 | 615 | **VimScript:** 616 | ```vim 617 | let s = "text" 618 | if s =~ '^[:alnum:]\+' 619 | echo "Contains only alphanumeric characters" 620 | endif 621 | if s =~ '^\a\+$' 622 | echo "Contains only alphabetic characters" 623 | endif 624 | if s =~ '^\d\+$' 625 | echo "Contains only digits" 626 | endif 627 | if s =~ '^\s\+$' 628 | echo "Contains only whitespace characters" 629 | endif 630 | if s =~ '^\u\+$' 631 | echo "Contains only uppercase characters" 632 | endif 633 | if s =~ '^\l\+$' 634 | echo "Contains only lowercase characters" 635 | endif 636 | ``` 637 | 638 | *Help:* [/collection](https://vimhelp.org/pattern.txt.html#%2fcollection) 639 | 640 | ### Data type conversion to string 641 | 642 | **Python:** 643 | ```python 644 | s = str(268) 645 | s = str(22.7) 646 | s = str([1, 2, 3]) 647 | s = str({'a' : 1, 'b' : 2}) 648 | ``` 649 | 650 | **VimScript:** 651 | ```vim 652 | let s = string(268) 653 | let s = string(22.7) 654 | let s = string([1, 2, 3]) 655 | let s = string({'a' : 1, 'b' : 2}) 656 | ``` 657 | 658 | *Help:* [string()](https://vimhelp.org/builtin.txt.html#string%28%29) 659 | 660 | ### Evaluating a string 661 | 662 | **Python:** 663 | ```python 664 | x = 10 665 | y = eval("x * 2") 666 | print(y) 667 | n = eval("min([4, 3, 5])") 668 | ``` 669 | 670 | **VimScript:** 671 | ```vim 672 | let x = 10 673 | let y = eval("x * 2") 674 | echo y 675 | let n = eval("min([4, 3, 5])") 676 | ``` 677 | 678 | *Help:* [eval()](https://vimhelp.org/builtin.txt.html#eval%28%29) 679 | 680 | ### Executing commands in a string 681 | 682 | **Python:** 683 | ```python 684 | exec("for i in range(5):\n print(i)\n") 685 | ``` 686 | 687 | **VimScript:** 688 | ```vim 689 | execute "for i in range(5)\necho i\nendfor" 690 | ``` 691 | 692 | *Help:* [:execute](https://vimhelp.org/eval.txt.html#:execute) 693 | 694 | ### Substituting variables in a string (String Interpolation) 695 | 696 | **Python:** 697 | ```python 698 | aVar = 10 699 | str = f"Value of 'a' is {aVar}" 700 | print(str) 701 | 702 | bList = [1, 2, 3] 703 | str = f"bList is {bList}" 704 | print(str) 705 | ``` 706 | 707 | **VimScript:** 708 | ```vim 709 | let aVar = 10 710 | let str = $"Value of 'a' is {aVar}" 711 | echo str 712 | 713 | let bList = [1, 2, 3] 714 | let str = $"bList is {string(bList)}" 715 | echo str 716 | ``` 717 | 718 | *Help:* [interp-string](https://vimhelp.org/eval.txt.html#interp-string) 719 | 720 | ### Getting the Unicode value of a character and vice versa 721 | 722 | **Python:** 723 | ```python 724 | print("Ordinal value of 'a' is " + str(ord("a"))) 725 | print("Character with value 65 is " + chr(65)) 726 | ``` 727 | 728 | **VimScript:** 729 | ```vim 730 | echo "Ordinal value of 'a' is " .. char2nr('a') 731 | echo "Character with value 65 is " .. nr2char(65) 732 | ``` 733 | 734 | *Help:* [char2nr()](https://vimhelp.org/builtin.txt.html#chr%28%29), [nr2char()](https://vimhelp.org/builtin.txt.html#or%28%29) 735 | 736 | ### Getting the character values of a string 737 | 738 | **Python:** 739 | ```python 740 | l = [ord(i) for i in 'Hello'] 741 | s = ''.join(chr(i) for i in l) 742 | print(s) 743 | print(l) 744 | ``` 745 | 746 | **VimScript:** 747 | ```vim 748 | let l = str2list('Hello') 749 | let s = list2str(l) 750 | echo s 751 | echo l 752 | ``` 753 | 754 | *Help:* [str2list()](https://vimhelp.org/builtin.txt.html#str2list%28%29), [list2str()](https://vimhelp.org/builtin.txt.html#list2str%28%29) 755 | 756 | ### Fuzzy matching strings 757 | 758 | **Python:** 759 | ```python 760 | from fuzzywuzzy import process 761 | from fuzzywuzzy import fuzz 762 | 763 | str_list = ['crow', 'clay', 'cobb'] 764 | m = process.extractOne('cay', str_list, scorer=fuzz.partial_ratio) 765 | print(m) 766 | ``` 767 | 768 | **VimScript:** 769 | ```vim 770 | let str_list = ['crow', 'clay', 'cobb'] 771 | let m = matchfuzzy(str_list, 'cay') 772 | echo m 773 | ``` 774 | 775 | *Help:* [matchfuzzy()](https://vimhelp.org/builtin.txt.html#matchfuzzy%28%29), [matchfuzzypos()](https://vimhelp.org/builtin.txt.html#matchfuzzypos%28%29) 776 | 777 | ### String Methods 778 | 779 | Method|Python|VimScript 780 | ----|------|--------- 781 | capitalize()| `'one two'.capitalize()` | `'one two'->substitute('.', '\u&', '')` 782 | center()| `'abc'.center(10)` | `Not available` 783 | count()| `"abbc".count('b')` | `"abbc"->count('b')` 784 | decode()| `str.decode()` | `Not available` 785 | encode()| `str.encode()` | `Not available` 786 | endswith()| `'running'.endswith('ing')` | `'running' =~# 'ing$'` 787 | expandtabs()| `"a\tb".expandtabs()` | `"a\tb"->substitute("\t", repeat(' ', 8), 'g')` 788 | find()| `"running".find('nn')` | `"running"->stridx('nn')` 789 | index()| `'hello'.index('e')` | `'hello'->stridx('e')` 790 | isalnum()| `str.isalnum()` | `str =~ '^[[:alnum:]]\+'` 791 | isalpha()| `str.isalpha()` | `str =~ '^\a\+$'` 792 | isdigit()| `str.isdigit()` | `str =~ '^\d\+$'` 793 | islower()| `str.islower()` | `str =~ '^\l\+$'` 794 | isspace()| `str.isspace()` | `str =~ '^\s\+$'` 795 | istitle()| `str.istitle()` | `str =~ '\(\<\u\l\+\>\)\s\?'` 796 | isupper()| `str.isupper()` | `str =~ '^\u\+$'` 797 | join()| `':'.join(['a', 'b', 'c'])` | `join(['a', 'b', 'c'], ':')` 798 | ljust()| `'abc'.ljust(10)` | `Not available` 799 | lower()| `'Hello'.lower()` | `'Hello'->tolower()` 800 | lstrip()| `' vim '.lstrip()` | `' vim '->trim(' ', 1)` 801 | partition()| `'ab-cd-ef'.partition('-')` | `'ab-cd-ef'->matchlist('\(.\{-}\)\(-\)\(.*\)')[1:3]` 802 | replace()| `'abc'.replace('abc', 'xyz')` | `'abc'->substitute('abc', 'xyz', 'g')` 803 | rfind()| `'running'.rfind('ing')` | `'running'->strridx('ing')` 804 | rindex()| `'running'.rindex('ing')` | `'running'->strridx('ing')` 805 | rjust()| `'abc'.rjust(10)` | `Not available` 806 | rpartition()| `'ab-cd-ef'.rpartition('-')` | `'ab-cd-ef'->matchlist('\(.*\)\(-\)\(.*\)')[1:3]` 807 | rsplit()| `'a-b-c-d'.rsplit('-', 2)` | `Not available` 808 | rstrip()| `' vim '.rstrip()` | `' vim '->trim(' ', 2)` 809 | split()| `'a-b-c'.split('-')` | `'a-b-c'->split('-')` 810 | splitlines()| `"one\ntwo".splitlines()` | `"one\ntwo"->split("\n")` 811 | startswith()| `'running'.startswith('run')` | `'running' =~# '^run'` 812 | strip()| `' vim '.strip()` | `' vim '->trim()` 813 | swapcase()| `'Abc'.swapcase()` | `Not available` 814 | title()| `'onE twO'.title()` | `'onE twO'->substitute('\<\(.\)\(\S\+\)\>', '\u\1\L\2', 'g')` 815 | translate()| `'abcd'.translate(string.maketrans('bd', '12'))` | `'abcd'->tr('bd', '12')` 816 | upper()| `'Hello'.upper()` | `'Hello'->toupper()` 817 | zfill()| `str.zfill(10)` | `Not available` 818 | 819 | *Help:* [string-functions](https://vimhelp.org/usr_41.txt.html#string-functions) 820 | 821 | ------------------------------------------------------------------------------ 822 | 823 | ## List 824 | 825 | ### Creating a List 826 | 827 | **Python:** 828 | ```python 829 | l = [1, 2, 3, 4] 830 | ``` 831 | 832 | **VimScript:** 833 | ```vim 834 | let l = [1, 2, 3, 4] 835 | ``` 836 | 837 | *Help:* [List](https://vimhelp.org/eval.txt.html#List) 838 | 839 | ### Accessing a List element 840 | 841 | **Python:** 842 | ```python 843 | l = [1, 2, 3, 4] 844 | v1 = l[2] 845 | v2 = l[-2] 846 | ``` 847 | 848 | **VimScript:** 849 | ```vim 850 | let l = [1, 2, 3, 4] 851 | let v1 = l[2] 852 | let v2 = l[-2] 853 | ``` 854 | 855 | *Help:* [list-index](https://vimhelp.org/eval.txt.html#list-index) 856 | 857 | ### Changing the value of a List element 858 | 859 | **Python:** 860 | ```python 861 | l = [1, 2, 3, 4] 862 | l[3] = 5 863 | ``` 864 | 865 | **VimScript:** 866 | ```vim 867 | let l = [1, 2, 3, 4] 868 | let l[3] = 5 869 | ``` 870 | 871 | *Help:* [list-modification](https://vimhelp.org/eval.txt.html#list-modification) 872 | 873 | ### Adding an item to a List 874 | 875 | **Python:** 876 | ```python 877 | l = [] 878 | l.append(5) 879 | l += [6, 7] 880 | ``` 881 | 882 | **VimScript:** 883 | ```vim 884 | let l = [] 885 | call add(l, 5) 886 | let l += [5, 6] 887 | ``` 888 | 889 | *Help:* [add()](https://vimhelp.org/builtin.txt.html#add%28%29) 890 | 891 | ### Extending a List using another List 892 | 893 | **Python:** 894 | ```python 895 | l = [] 896 | l.extend([2, 3]) 897 | l += [6, 7] 898 | ``` 899 | 900 | **VimScript:** 901 | ```vim 902 | let l = [] 903 | call extend(l, [2, 3]) 904 | let l += [6, 7] 905 | ``` 906 | 907 | *Help:* [extend()](https://vimhelp.org/builtin.txt.html#extend%28%29) 908 | 909 | ### Inserting an item in a List 910 | 911 | **Python:** 912 | ```python 913 | l = [1, 3] 914 | l.insert(1, 2) 915 | ``` 916 | 917 | **VimScript:** 918 | ```vim 919 | let l = [1, 3] 920 | " insert before index 1 921 | eval l->insert(2, 1) 922 | " insert at the begining 923 | eval l->insert(5) 924 | ``` 925 | 926 | *Help:* [insert()](https://vimhelp.org/builtin.txt.html#insert%28%29) 927 | 928 | ### Removing an item from a List 929 | 930 | **Python:** 931 | ```python 932 | l = [4, 5, 6] 933 | l.remove(5) 934 | del l[0] 935 | ``` 936 | 937 | **VimScript:** 938 | ```vim 939 | let l = [4, 5, 6] 940 | let idx = index(l, 5) 941 | if idx != -1 942 | call remove(l, idx) 943 | endif 944 | unlet l[0] 945 | ``` 946 | 947 | *Help:* [remove()](https://vimhelp.org/builtin.txt.html#remove%28%29), [:unlet](https://vimhelp.org/eval.txt.html#%3aunlet) 948 | 949 | ### Removing the last element from a List 950 | 951 | **Python:** 952 | ```python 953 | l = [1, 2, 3] 954 | v = l.pop() 955 | ``` 956 | 957 | **VimScript:** 958 | ```vim 959 | let l = [1, 2, 3] 960 | let v = l->remove(-1) 961 | ``` 962 | 963 | *Help:* [remove()](https://vimhelp.org/builtin.txt.html#remove%28%29) 964 | 965 | ### Find the index of an item in a List 966 | 967 | **Python:** 968 | ```python 969 | l = [1, 2, 3] 970 | x = l.index(2) 971 | ``` 972 | 973 | **VimScript:** 974 | ```vim 975 | let l = [1, 2, 3] 976 | let x = l->index(2) 977 | ``` 978 | 979 | *Help:* [index()](https://vimhelp.org/builtin.txt.html#index%28%29) 980 | 981 | ### Find the index of an item in a List of Dicts by a Dict item value 982 | 983 | **Python:** 984 | ```python 985 | colors = [{'color': 'red'}, {'color': 'blue'}, {'color': 'green'}] 986 | idx = next((i for i, v in enumerate(colors) if v['color'] == 'blue'), -1) 987 | print(idx) 988 | ``` 989 | 990 | **VimScript:** 991 | ```vim 992 | let colors = [{'color': 'red'}, {'color': 'blue'}, {'color': 'green'}] 993 | let idx = indexof(colors, {i, v -> v.color == 'blue'}) 994 | echo idx 995 | ``` 996 | 997 | *Help:* [indexof()](https://vimhelp.org/builtin.txt.html#indexof%28%29) 998 | 999 | ### List slices 1000 | 1001 | In Python, when using an index range to specify a series of items in a List, the item at the end index is not included. In Vim, the item at the end index is included. The slice() function excludes the item at the end index. 1002 | 1003 | **Python:** 1004 | ```python 1005 | l = [1, 2, 3, 4] 1006 | print(l[1:3]) 1007 | print(l[2:]) 1008 | ``` 1009 | 1010 | **VimScript:** 1011 | ```vim 1012 | let l = [1, 2, 3, 4] 1013 | echo l[1:3] 1014 | echo l[2:] 1015 | echo l[-2:] 1016 | 1017 | " slice() function excludes the item at the end index. 1018 | echo slice(l, 2, 3) 1019 | echo slice(l, 2) 1020 | ``` 1021 | 1022 | *Help:* [sublist](https://vimhelp.org/eval.txt.html#sublist), [slice()](https://vimhelp.org/builtin.txt.html#slice%28%29) 1023 | 1024 | ### List Concatenation 1025 | 1026 | **Python:** 1027 | ```python 1028 | l = [1, 2] + [3 ,4] 1029 | ``` 1030 | 1031 | **VimScript:** 1032 | ```vim 1033 | let l = [1, 2] + [3 ,4] 1034 | ``` 1035 | 1036 | *Help:* [list-index](https://vimhelp.org/eval.txt.html#list-index) 1037 | 1038 | ### Adding multiple items to a List using repetition 1039 | 1040 | **Python:** 1041 | ```python 1042 | l = ['vim'] * 4 1043 | ``` 1044 | 1045 | **VimScript:** 1046 | ```vim 1047 | let l = ['vim']->repeat(4) 1048 | ``` 1049 | 1050 | *Help:* [repeat()](https://vimhelp.org/builtin.txt.html#repeat%28%29) 1051 | 1052 | ### Count the number of occurrences of an item in a List 1053 | 1054 | **Python:** 1055 | ```python 1056 | l = [2, 4, 4, 5] 1057 | x = l.count(4) 1058 | ``` 1059 | 1060 | **VimScript:** 1061 | ```vim 1062 | let l = [2, 4, 4, 5] 1063 | let x = l->count(2) 1064 | ``` 1065 | 1066 | *Help:* [count()](https://vimhelp.org/builtin.txt.html#count%28%29) 1067 | 1068 | ### Finding the List length 1069 | 1070 | **Python:** 1071 | ```python 1072 | l = ['a', 'b', 'c'] 1073 | n = len(l) 1074 | ``` 1075 | 1076 | **VimScript:** 1077 | ```vim 1078 | let l = ['a', 'b', 'c'] 1079 | let n = l->len() 1080 | ``` 1081 | 1082 | *Help:* [len()](https://vimhelp.org/builtin.txt.html#len%28%29) 1083 | 1084 | ### List Iteration 1085 | 1086 | **Python:** 1087 | ```python 1088 | l = [10, 20, 30] 1089 | for v in l: 1090 | print(v) 1091 | 1092 | # Print both the list index and the value 1093 | for i, v in enumerate(l): 1094 | print(i, v) 1095 | 1096 | # Use a for loop for list iteration 1097 | for i in range(len(l)): 1098 | print(i, l[i]) 1099 | ``` 1100 | 1101 | **VimScript:** 1102 | ```vim 1103 | let l = [10, 20, 30] 1104 | for v in l 1105 | echo v 1106 | endfor 1107 | 1108 | " Print both the list index and the value 1109 | for [i, v] in items(l) 1110 | echo i v 1111 | endfor 1112 | 1113 | " Use a for loop for list iteration 1114 | for i in range(len(l)) 1115 | echo i l[i] 1116 | endfor 1117 | ``` 1118 | 1119 | *Help:* [:for](https://vimhelp.org/eval.txt.html#%3Afor) 1120 | 1121 | ### Sort a List 1122 | 1123 | **Python:** 1124 | ```python 1125 | l = [3, 2, 1] 1126 | l.sort() 1127 | print(l) 1128 | ``` 1129 | 1130 | **VimScript:** 1131 | ```vim 1132 | let l = [3, 2, 1] 1133 | echo l->sort() 1134 | ``` 1135 | 1136 | *Help:* [sort()](https://vimhelp.org/builtin.txt.html#sort%28%29) 1137 | 1138 | ### Getting unique elements in a List 1139 | 1140 | **Python:** 1141 | ```python 1142 | l = ['a', 'b', 'b', 'c', 'c', 'd'] 1143 | # order of the elements is not retained 1144 | tset = set(l) 1145 | print(list(tset)) 1146 | ``` 1147 | 1148 | **VimScript:** 1149 | ```vim 1150 | " needs a sorted list 1151 | let l = ['a', 'b', 'b', 'c', 'c', 'd'] 1152 | echo copy(l)->uniq() 1153 | ``` 1154 | 1155 | *Help:* [uniq()](https://vimhelp.org/builtin.txt.html#uniq%28%29) 1156 | 1157 | ### Reverse a List 1158 | 1159 | **Python:** 1160 | ```python 1161 | l = [1, 2, 3] 1162 | l.reverse() 1163 | print(l) 1164 | ``` 1165 | 1166 | **VimScript:** 1167 | ```vim 1168 | let l = [1, 2, 3] 1169 | echo reverse(l) 1170 | ``` 1171 | 1172 | *Help:* [reverse()](https://vimhelp.org/builtin.txt.html#reverse%28%29) 1173 | 1174 | ### Copying a List 1175 | 1176 | **Python:** 1177 | ```python 1178 | l = [3, 2, 1] 1179 | l2 = l.copy() 1180 | ``` 1181 | 1182 | **VimScript:** 1183 | ```vim 1184 | let l = [3, 2, 1] 1185 | let l2 = l->copy() 1186 | ``` 1187 | 1188 | *Help:* [copy()](https://vimhelp.org/builtin.txt.html#copy%28%29) 1189 | 1190 | ### Deep Copying a List 1191 | 1192 | **Python:** 1193 | ```python 1194 | import copy 1195 | a = [[1, 2], [3, 4]] 1196 | b = copy.deepcopy(a) 1197 | ``` 1198 | 1199 | **VimScript:** 1200 | ```vim 1201 | let a = [[1, 2], [3, 4]] 1202 | let b = a->deepcopy() 1203 | ``` 1204 | 1205 | *Help:* [deepcopy()](https://vimhelp.org/builtin.txt.html#deepcopy%28%29) 1206 | 1207 | ### Empty a List 1208 | 1209 | **Python:** 1210 | ```python 1211 | l = [3, 2, 1] 1212 | l.clear() 1213 | ``` 1214 | 1215 | **VimScript:** 1216 | ```vim 1217 | let l = [3, 2, 1] 1218 | unlet l[:] 1219 | ``` 1220 | 1221 | *Help:* [:unlet](https://vimhelp.org/eval.txt.html#%3aunlet) 1222 | 1223 | ### Comparing two Lists 1224 | 1225 | **Python:** 1226 | ```python 1227 | l1 = [1, 2] 1228 | l2 = l1 1229 | l3 = [1, 2] 1230 | if l1 is l2: 1231 | print("Lists l1 and l2 refer to the same list") 1232 | if l1 is not l3: 1233 | print("Lists l1 and l3 do not refer to the same list") 1234 | if l1 == l3: 1235 | print("Lists l1 and l3 contain the same elements") 1236 | if l1 != l3: 1237 | print("Lists l1 and l3 are different") 1238 | ``` 1239 | 1240 | **VimScript:** 1241 | ```vim 1242 | let l1 = [1, 2] 1243 | let l2 = l1 1244 | let l3 = [1, 2] 1245 | if l1 is l2 1246 | echo "Lists l1 and l2 refer to the same list" 1247 | endif 1248 | if l1 isnot l3 1249 | echo "Lists l1 and l2 do not refer to the same list" 1250 | endif 1251 | if l1 == l3 1252 | echo "Lists l1 and l3 contain the same elements" 1253 | endif 1254 | if l1 != l3 1255 | echo "Lists l1 and l3 are different" 1256 | endif 1257 | ``` 1258 | 1259 | *Help:* [list-identity](https://vimhelp.org/eval.txt.html#list-identity) 1260 | 1261 | ### Filter selected elements from a List 1262 | 1263 | Note that Vim does not support List comprehension. 1264 | 1265 | **Python:** 1266 | ```python 1267 | odd = list(filter(lambda x: x % 2, range(10))) 1268 | odd = [x for x in range(10) if x % 2] 1269 | ``` 1270 | 1271 | **VimScript:** 1272 | ```vim 1273 | let odd = filter(range(10), {idx, v -> v % 2}) 1274 | ``` 1275 | 1276 | *Help:* [filter()](https://vimhelp.org/builtin.txt.html#filter%28%29) 1277 | 1278 | ### Map List elements 1279 | 1280 | Note that Vim does not support List comprehension. 1281 | 1282 | **Python:** 1283 | ```python 1284 | num_str = list(map(lambda x: str(x), range(10))) 1285 | num_str = [str(x) for x in range(10)] 1286 | ``` 1287 | 1288 | **VimScript:** 1289 | ```vim 1290 | let num_str = map(range(10), {idx, v -> string(v)}) 1291 | ``` 1292 | 1293 | *Help:* [map()](https://vimhelp.org/builtin.txt.html#map%28%29) 1294 | 1295 | ### Reducing List elements 1296 | 1297 | **Python:** 1298 | ```python 1299 | # using a lambda function 1300 | from functools import reduce 1301 | sum = reduce((lambda x, y: x + y), [1, 2, 3, 4]) 1302 | 1303 | # using a function 1304 | def SumNum(a, b): 1305 | return a + b 1306 | sum = reduce(SumNum, [1, 2, 3, 4]) 1307 | ``` 1308 | 1309 | **VimScript:** 1310 | ```vim 1311 | " using a lambda function 1312 | let sum = reduce([1, 2, 3, 4], {x, y -> x + y}) 1313 | 1314 | " using a function 1315 | func SumNum(x, y) 1316 | return a:x + a:y 1317 | endfunc 1318 | let sum = reduce([1, 2, 3, 4], function('SumNum')) 1319 | echo sum 1320 | ``` 1321 | 1322 | *Help:* [reduce()](https://vimhelp.org/builtin.txt.html#reduce%28%29) 1323 | 1324 | ### Flattening a List 1325 | 1326 | **Python:** 1327 | ```python 1328 | l = [[5, 9], [1, 3], [10, 20]] 1329 | flattenlist = [i for subl in l for i in subl] 1330 | print(flattenlist) 1331 | ``` 1332 | 1333 | **VimScript:** 1334 | ```vim 1335 | let l = [[5, 9], [1, 3], [10, 20]] 1336 | let flattenlist = flattennew(l) 1337 | echo flattenlist 1338 | ``` 1339 | 1340 | *Help:* [flatten()](https://vimhelp.org/builtin.txt.html#flatten%28%29), [flattennew()](https://vimhelp.org/builtin.txt.html#flattennew%28%29) 1341 | 1342 | ### Finding the mix/max value in a List 1343 | 1344 | **Python:** 1345 | ```python 1346 | l = [3, 10, 8] 1347 | v1 = min(l) 1348 | v2 = max(l) 1349 | print(v1, v2) 1350 | ``` 1351 | 1352 | **VimScript:** 1353 | ```vim 1354 | let l = [3, 10, 8] 1355 | let v1 = l->min() 1356 | let v2 = l->max() 1357 | echo v1 v2 1358 | ``` 1359 | 1360 | *Help:* [max()](https://vimhelp.org/builtin.txt.html#max%28%29), [min()](https://vimhelp.org/builtin.txt.html#min%28%29) 1361 | 1362 | ### Converting a List to a string 1363 | 1364 | **Python:** 1365 | ```python 1366 | s = str([3, 5, 7]) 1367 | ``` 1368 | 1369 | **VimScript:** 1370 | ```vim 1371 | let s = string([3, 5, 7]) 1372 | ``` 1373 | 1374 | *Help:* [string()](https://vimhelp.org/builtin.txt.html#string%28%29) 1375 | 1376 | ### List Methods 1377 | 1378 | Method|Python|VimScript 1379 | ----|------|--------- 1380 | append()| `m.append(6)` | `m->add(6)` 1381 | clear()| `m.clear()` | `unlet m[:]` 1382 | copy()| `m.copy()` | `m->copy()` 1383 | count()| `m.count(6)` | `m->count(6)` 1384 | extend()| `m.extend([5, 6])` | `m->extend([5, 6])` 1385 | index()| `m.index(6)` | `m-index(6)` 1386 | insert()| `m.insert(2, 9)` | `m->insert(9, 2)` 1387 | pop()| `m.pop()` | `m->remove(-1)` 1388 | remove()| `m.remove(6)` | `m->remove(m->index(6))` 1389 | reverse()| `m.reverse()` | `m->reverse()` 1390 | sort()| `m.sort()` | `m->sort()` 1391 | 1392 | *Help:* [list-functions](https://vimhelp.org/usr_41.txt.html#list-functions) 1393 | 1394 | ------------------------------------------------------------------------------ 1395 | 1396 | ## Tuple 1397 | 1398 | ### Creating a Tuple 1399 | 1400 | **Python:** 1401 | ```python 1402 | t = (1, 2, 3, 4) 1403 | ``` 1404 | 1405 | **VimScript:** 1406 | ```vim 1407 | let t = (1, 2, 3, 4) 1408 | ``` 1409 | 1410 | *Help:* [Tuple](https://vimhelp.org/eval.txt.html#Tuple) 1411 | 1412 | ### Accessing a Tuple element 1413 | 1414 | **Python:** 1415 | ```python 1416 | t = (1, 2, 3, 4) 1417 | v1 = t[2] 1418 | v2 = t[-2] 1419 | ``` 1420 | 1421 | **VimScript:** 1422 | ```vim 1423 | let t = (1, 2, 3, 4) 1424 | let v1 = t[2] 1425 | let v2 = t[-2] 1426 | ``` 1427 | 1428 | *Help:* [tuple-index](https://vimhelp.org/eval.txt.html#tuple-index) 1429 | 1430 | ### Changing the value of a List/Dict item in a Tuple 1431 | 1432 | **Python:** 1433 | ```python 1434 | t = (1, [2, 3], {'a': 4}) 1435 | t[1][0] = 5 1436 | t[2]['a'] = 10 1437 | ``` 1438 | 1439 | **VimScript:** 1440 | ```vim 1441 | let t = (1, [2, 3], {'a': 6}) 1442 | let t[1][0] = 5 1443 | let t[2]['a'] = 10 1444 | ``` 1445 | 1446 | *Help:* [tuple-modification](https://vimhelp.org/eval.txt.html#tuple-modification) 1447 | 1448 | ### Find the index of an item in a Tuple 1449 | 1450 | **Python:** 1451 | ```python 1452 | t = (1, 2, 3) 1453 | x = t.index(2) 1454 | ``` 1455 | 1456 | **VimScript:** 1457 | ```vim 1458 | let t = (1, 2, 3) 1459 | let x = t->index(2) 1460 | ``` 1461 | 1462 | *Help:* [index()](https://vimhelp.org/builtin.txt.html#index%28%29) 1463 | 1464 | ### Find the index of an item in a Tuple of Dicts by a Dict item value 1465 | 1466 | **Python:** 1467 | ```python 1468 | colors = ({'color': 'red'}, {'color': 'blue'}, {'color': 'green'}) 1469 | idx = next((i for i, v in enumerate(colors) if v['color'] == 'blue'), -1) 1470 | print(idx) 1471 | ``` 1472 | 1473 | **VimScript:** 1474 | ```vim 1475 | let colors = ({'color': 'red'}, {'color': 'blue'}, {'color': 'green'}) 1476 | let idx = indexof(colors, {i, v -> v.color == 'blue'}) 1477 | echo idx 1478 | ``` 1479 | 1480 | *Help:* [indexof()](https://vimhelp.org/builtin.txt.html#indexof%28%29) 1481 | 1482 | ### Tuple slices 1483 | 1484 | In Python, when using an index range to specify a series of items in a Tuple, the item at the end index is not included. In Vim, the item at the end index is included. The slice() function excludes the item at the end index. 1485 | 1486 | **Python:** 1487 | ```python 1488 | t = (1, 2, 3, 4) 1489 | print(t[1:3]) 1490 | print(t[2:]) 1491 | ``` 1492 | 1493 | **VimScript:** 1494 | ```vim 1495 | let t = (1, 2, 3, 4) 1496 | echo t[1:3] 1497 | echo t[2:] 1498 | echo t[-2:] 1499 | 1500 | " slice() function excludes the item at the end index. 1501 | echo slice(t, 2, 3) 1502 | echo slice(t, 2) 1503 | ``` 1504 | 1505 | *Help:* [subtuple](https://vimhelp.org/eval.txt.html#subtuple), [slice()](https://vimhelp.org/builtin.txt.html#slice%28%29) 1506 | 1507 | ### Tuple Concatenation 1508 | 1509 | **Python:** 1510 | ```python 1511 | t = (1, 2) + (3 ,4) 1512 | ``` 1513 | 1514 | **VimScript:** 1515 | ```vim 1516 | let t = (1, 2) + (3 ,4) 1517 | ``` 1518 | 1519 | *Help:* [tuple-concatenation](https://vimhelp.org/eval.txt.html#tuple-concatenation) 1520 | 1521 | ### Adding multiple items to a Tuple using repetition 1522 | 1523 | **Python:** 1524 | ```python 1525 | t = ('vim',) * 4 1526 | ``` 1527 | 1528 | **VimScript:** 1529 | ```vim 1530 | let t = ('vim')->repeat(4) 1531 | ``` 1532 | 1533 | *Help:* [repeat()](https://vimhelp.org/builtin.txt.html#repeat%28%29) 1534 | 1535 | ### Count the number of occurrences of an item in a Tuple 1536 | 1537 | **Python:** 1538 | ```python 1539 | t = (2, 4, 4, 5) 1540 | x = t.count(4) 1541 | ``` 1542 | 1543 | **VimScript:** 1544 | ```vim 1545 | let t = (2, 4, 4, 5) 1546 | let x = t->count(2) 1547 | ``` 1548 | 1549 | *Help:* [count()](https://vimhelp.org/builtin.txt.html#count%28%29) 1550 | 1551 | ### Finding the Tuple length 1552 | 1553 | **Python:** 1554 | ```python 1555 | t = ('a', 'b', 'c') 1556 | n = len(t) 1557 | ``` 1558 | 1559 | **VimScript:** 1560 | ```vim 1561 | let t = ('a', 'b', 'c') 1562 | let n = t->len() 1563 | ``` 1564 | 1565 | *Help:* [len()](https://vimhelp.org/builtin.txt.html#len%28%29) 1566 | 1567 | ### Tuple Iteration 1568 | 1569 | **Python:** 1570 | ```python 1571 | t = (10, 20, 30) 1572 | for v in t: 1573 | print(v) 1574 | 1575 | # Print both the tuple index and the value 1576 | for i, v in enumerate(t): 1577 | print(i, v) 1578 | 1579 | # Use a for loop for tuple iteration 1580 | for i in range(len(t)): 1581 | print(i, t[i]) 1582 | ``` 1583 | 1584 | **VimScript:** 1585 | ```vim 1586 | let t = (10, 20, 30) 1587 | for v in t 1588 | echo v 1589 | endfor 1590 | 1591 | " Print both the tuple index and the value 1592 | for [i, v] in items(t) 1593 | echo i v 1594 | endfor 1595 | 1596 | " Use a for loop for tuple iteration 1597 | for i in range(len(t)) 1598 | echo i t[i] 1599 | endfor 1600 | ``` 1601 | 1602 | *Help:* [:for](https://vimhelp.org/eval.txt.html#%3Afor) 1603 | 1604 | ### Reverse a Tuple 1605 | 1606 | **Python:** 1607 | ```python 1608 | t = (1, 2, 3) 1609 | t.reverse() 1610 | print(t) 1611 | ``` 1612 | 1613 | **VimScript:** 1614 | ```vim 1615 | let t = (1, 2, 3) 1616 | echo reverse(t) 1617 | ``` 1618 | 1619 | *Help:* [reverse()](https://vimhelp.org/builtin.txt.html#reverse%28%29) 1620 | 1621 | ### Copying a Tuple 1622 | 1623 | **Python:** 1624 | ```python 1625 | t = (3, 2, 1) 1626 | t2 = t.copy() 1627 | ``` 1628 | 1629 | **VimScript:** 1630 | ```vim 1631 | let t = (3, 2, 1) 1632 | let t2 = t->copy() 1633 | ``` 1634 | 1635 | *Help:* [copy()](https://vimhelp.org/builtin.txt.html#copy%28%29) 1636 | 1637 | ### Deep Copying a Tuple 1638 | 1639 | **Python:** 1640 | ```python 1641 | import copy 1642 | a = ([1, 2], [3, 4]) 1643 | b = copy.deepcopy(a) 1644 | ``` 1645 | 1646 | **VimScript:** 1647 | ```vim 1648 | let a = ([1, 2], [3, 4]) 1649 | let b = a->deepcopy() 1650 | ``` 1651 | 1652 | *Help:* [deepcopy()](https://vimhelp.org/builtin.txt.html#deepcopy%28%29) 1653 | 1654 | ### Comparing two Tuples 1655 | 1656 | **Python:** 1657 | ```python 1658 | t1 = (1, 2) 1659 | t2 = l1 1660 | t3 = (1, 2) 1661 | if t1 is t2: 1662 | print("Tuples t1 and t2 refer to the same tuple") 1663 | if t1 is not t3: 1664 | print("Tuples t1 and t3 do not refer to the same tuple") 1665 | if t1 == t3: 1666 | print("Tuples t1 and t3 contain the same elements") 1667 | if t1 != t3: 1668 | print("Tuples t1 and t3 are different") 1669 | ``` 1670 | 1671 | **VimScript:** 1672 | ```vim 1673 | let t1 = (1, 2) 1674 | let t2 = l1 1675 | let t3 = (1, 2) 1676 | if t1 is t2 1677 | echo "Tuples t1 and t2 refer to the same tuple" 1678 | endif 1679 | if t1 isnot t3 1680 | echo "Tuples t1 and t2 do not refer to the same tuple" 1681 | endif 1682 | if t1 == t3 1683 | echo "Tuples t1 and t3 contain the same elements" 1684 | endif 1685 | if t1 != t3 1686 | echo "Tuples t1 and t3 are different" 1687 | endif 1688 | ``` 1689 | 1690 | *Help:* [tuple-identity](https://vimhelp.org/eval.txt.html#tuple-identity) 1691 | 1692 | ### Reducing Tuple elements 1693 | 1694 | **Python:** 1695 | ```python 1696 | # using a lambda function 1697 | from functools import reduce 1698 | sum = reduce((lambda x, y: x + y), (1, 2, 3, 4)) 1699 | 1700 | # using a function 1701 | def SumNum(a, b): 1702 | return a + b 1703 | sum = reduce(SumNum, (1, 2, 3, 4)) 1704 | ``` 1705 | 1706 | **VimScript:** 1707 | ```vim 1708 | " using a lambda function 1709 | let sum = reduce((1, 2, 3, 4), {x, y -> x + y}) 1710 | 1711 | " using a function 1712 | func SumNum(x, y) 1713 | return a:x + a:y 1714 | endfunc 1715 | let sum = reduce((1, 2, 3, 4), function('SumNum')) 1716 | echo sum 1717 | ``` 1718 | 1719 | *Help:* [reduce()](https://vimhelp.org/builtin.txt.html#reduce%28%29) 1720 | 1721 | ### Finding the mix/max value in a Tuple 1722 | 1723 | **Python:** 1724 | ```python 1725 | t = (3, 10, 8) 1726 | v1 = min(t) 1727 | v2 = max(t) 1728 | print(v1, v2) 1729 | ``` 1730 | 1731 | **VimScript:** 1732 | ```vim 1733 | let t = (3, 10, 8) 1734 | let v1 = t->min() 1735 | let v2 = t->max() 1736 | echo v1 v2 1737 | ``` 1738 | 1739 | *Help:* [max()](https://vimhelp.org/builtin.txt.html#max%28%29), [min()](https://vimhelp.org/builtin.txt.html#min%28%29) 1740 | 1741 | ### Converting a Tuple to a string 1742 | 1743 | **Python:** 1744 | ```python 1745 | s = str((3, 5, 7)) 1746 | ``` 1747 | 1748 | **VimScript:** 1749 | ```vim 1750 | let s = string((3, 5, 7)) 1751 | ``` 1752 | 1753 | *Help:* [string()](https://vimhelp.org/builtin.txt.html#string%28%29) 1754 | 1755 | ### Tuple Methods 1756 | 1757 | Method|Python|VimScript 1758 | ----|------|--------- 1759 | copy()| `m.copy()` | `m->copy()` 1760 | count()| `m.count(6)` | `m->count(6)` 1761 | index()| `m.index(6)` | `m-index(6)` 1762 | reverse()| `m.reverse()` | `m->reverse()` 1763 | 1764 | *Help:* [tuple-functions](https://vimhelp.org/usr_41.txt.html#tuple-functions) 1765 | 1766 | ------------------------------------------------------------------------------ 1767 | ## Dictionary 1768 | 1769 | ### Creating a Dict 1770 | 1771 | **Python:** 1772 | ```python 1773 | d = {'red' : 10, 'blue' : 20} 1774 | x = {} 1775 | ``` 1776 | 1777 | **VimScript:** 1778 | ```vim 1779 | let d = {'red' : 10, 'blue' : 20} 1780 | let d = #{red : 10, blue : 20} 1781 | let x = {} 1782 | ``` 1783 | 1784 | *Help:* [Dict](https://vimhelp.org/eval.txt.html#Dict) 1785 | 1786 | ### Retrieving the value of a Dict item 1787 | 1788 | **Python:** 1789 | ```python 1790 | d = {'red' : 10, 'blue' : 20} 1791 | x = d['red'] 1792 | ``` 1793 | 1794 | **VimScript:** 1795 | ```vim 1796 | let d = #{red : 10, blue : 20} 1797 | let x = d['red'] 1798 | let x = d.red 1799 | ``` 1800 | 1801 | *Help:* [dict](https://vimhelp.org/eval.txt.html#dict) 1802 | 1803 | ### Changing the value of a Dict item 1804 | 1805 | **Python:** 1806 | ```python 1807 | d = {'red' : 10, 'blue' : 20} 1808 | d['red'] = 15 1809 | ``` 1810 | 1811 | **VimScript:** 1812 | ```vim 1813 | let d = #{red : 10, blue : 20} 1814 | let d.red = 15 1815 | ``` 1816 | 1817 | *Help:* [dict-modification](https://vimhelp.org/eval.txt.html#dict-modification) 1818 | 1819 | ### Accessing a Dict item 1820 | 1821 | **Python:** 1822 | ```python 1823 | d = {'red' : 10, 'blue' : 20} 1824 | v = d.get('red') 1825 | ``` 1826 | 1827 | **VimScript:** 1828 | ```vim 1829 | let d = {'red' : 10, 'blue' : 20} 1830 | let v = get(d, 'red') 1831 | ``` 1832 | 1833 | *Help:* [get()](https://vimhelp.org/builtin.txt.html#get%28%29) 1834 | 1835 | ### Adding a new Dict item 1836 | 1837 | **Python:** 1838 | ```python 1839 | d = {'red' : 10, 'blue' : 20} 1840 | d['green'] = 30 1841 | ``` 1842 | 1843 | **VimScript:** 1844 | ```vim 1845 | let d = {'red' : 10, 'blue' : 20} 1846 | let d.green = 30 1847 | ``` 1848 | 1849 | *Help:* [dict-modification](https://vimhelp.org/eval.txt.html#dict-modification) 1850 | 1851 | ### Extending a Dict using another Dict 1852 | 1853 | **Python:** 1854 | ```python 1855 | d = {} 1856 | d.update({'color' : 'grey'}) 1857 | ``` 1858 | 1859 | **VimScript:** 1860 | ```vim 1861 | let d = {} 1862 | eval d->extend({'color' : 'grey'}) 1863 | ``` 1864 | 1865 | *Help:* [extend()](https://vimhelp.org/builtin.txt.html#extend%28%29) 1866 | 1867 | ### Removing an item from a Dict 1868 | 1869 | **Python:** 1870 | ```python 1871 | d = {'red' : 10, 'blue' : 20} 1872 | d.pop('red') 1873 | ``` 1874 | 1875 | **VimScript:** 1876 | ```vim 1877 | let d = {'red' : 10, 'blue' : 20} 1878 | call remove(d, 'red') 1879 | ``` 1880 | 1881 | *Help:* [remove()](https://vimhelp.org/builtin.txt.html#remove%28%29), 1882 | 1883 | ### Clearing all the items from a Dict 1884 | 1885 | **Python:** 1886 | ```python 1887 | d = {'red' : 10, 'blue' : 20} 1888 | d.clear() 1889 | ``` 1890 | 1891 | **VimScript:** 1892 | ```vim 1893 | let d = {'red' : 10, 'blue' : 20} 1894 | call filter(d, "0") 1895 | ``` 1896 | 1897 | *Help:* [dict-modification](https://vimhelp.org/eval.txt.html#dict-modification) 1898 | 1899 | ### Getting the size of a Dict 1900 | 1901 | **Python:** 1902 | ```python 1903 | d = {'red' : 10, 'blue' : 20} 1904 | n = len(d) 1905 | ``` 1906 | 1907 | **VimScript:** 1908 | ```vim 1909 | let d = {'red' : 10, 'blue' : 20} 1910 | let n = d->len() 1911 | ``` 1912 | 1913 | *Help:* [len()](https://vimhelp.org/builtin.txt.html#len%28%29) 1914 | 1915 | ### Count the number of occurrences of a value in a Dict 1916 | 1917 | **Python:** 1918 | ```python 1919 | d = {'red' : 10, 'blue' : 10} 1920 | x = sum(n == 10 for n in d.values()) 1921 | print(x) 1922 | ``` 1923 | 1924 | **VimScript:** 1925 | ```vim 1926 | let d = {'red' : 10, 'blue' : 10} 1927 | let x = d->count(10) 1928 | echo x 1929 | ``` 1930 | 1931 | *Help:* [count()](https://vimhelp.org/builtin.txt.html#count%28%29) 1932 | 1933 | ### Checking Dict membership 1934 | 1935 | **Python:** 1936 | ```python 1937 | d = {'red' : 10, 'blue' : 20} 1938 | if 'red' in d: 1939 | print("found red key") 1940 | ``` 1941 | 1942 | **VimScript:** 1943 | ```vim 1944 | let d = {'red' : 10, 'blue' : 20} 1945 | if d->has_key('red') 1946 | echo "found red key" 1947 | endif 1948 | ``` 1949 | 1950 | *Help:* [has_key()](https://vimhelp.org/builtin.txt.html#has_key%28%29) 1951 | 1952 | ### Iterating through all the keys in a Dict 1953 | 1954 | **Python:** 1955 | ```python 1956 | d = {'red' : 10, 'blue' : 20} 1957 | for k in d: 1958 | print(k) 1959 | for k in d: 1960 | print(d[k]) 1961 | ``` 1962 | 1963 | **VimScript:** 1964 | ```vim 1965 | let d = {'red' : 10, 'blue' : 20} 1966 | for k in keys(d) 1967 | echo k 1968 | endfor 1969 | for k in d->keys() 1970 | echo d[k] 1971 | endfor 1972 | ``` 1973 | 1974 | *Help:* [keys()](https://vimhelp.org/builtin.txt.html#keys%28%29) 1975 | 1976 | ### Iterating through all the values in a Dict 1977 | 1978 | **Python:** 1979 | ```python 1980 | d = {'red' : 10, 'blue' : 20} 1981 | for v in d.values(): 1982 | print(v) 1983 | ``` 1984 | 1985 | **VimScript:** 1986 | ```vim 1987 | let d = {'red' : 10, 'blue' : 20} 1988 | for v in d->values() 1989 | echo v 1990 | endfor 1991 | ``` 1992 | 1993 | *Help:* [values()](https://vimhelp.org/builtin.txt.html#values%28%29) 1994 | 1995 | ### Iterating through all the key, value pairs in a Dict 1996 | 1997 | **Python:** 1998 | ```python 1999 | d = {'red' : 10, 'blue' : 20} 2000 | for k, v in d.items(): 2001 | print(k, v) 2002 | ``` 2003 | 2004 | **VimScript:** 2005 | ```vim 2006 | let d = {'red' : 10, 'blue' : 20} 2007 | for [k, v] in d->items() 2008 | echo k v 2009 | endfor 2010 | ``` 2011 | 2012 | *Help:* [items()](https://vimhelp.org/builtin.txt.html#items%28%29) 2013 | 2014 | ### Copying a Dict 2015 | 2016 | **Python:** 2017 | ```python 2018 | d = {'red' : 10, 'blue' : 20} 2019 | new_d = d.copy() 2020 | ``` 2021 | 2022 | **VimScript:** 2023 | ```vim 2024 | let d = {'red' : 10, 'blue' : 20} 2025 | let new_d = d->copy() 2026 | ``` 2027 | 2028 | *Help:* [copy()](https://vimhelp.org/builtin.txt.html#copy%28%29) 2029 | 2030 | ### Deep Copying a Dict 2031 | 2032 | **Python:** 2033 | ```python 2034 | import copy 2035 | a = {'x' : [1, 2], 'y' : [3, 4]} 2036 | b = copy.deepcopy(a) 2037 | ``` 2038 | 2039 | **VimScript:** 2040 | ```vim 2041 | let a = {'x' : [1, 2], 'y' : [3, 4]} 2042 | let b = a->deepcopy() 2043 | ``` 2044 | 2045 | *Help:* [deepcopy()](https://vimhelp.org/builtin.txt.html#deepcopy%28%29) 2046 | 2047 | ### Comparing two Dicts 2048 | 2049 | **Python:** 2050 | ```python 2051 | d1 = {'a' : 10, 'b' : 20} 2052 | d2 = {'a' : 10, 'b' : 20} 2053 | if d1 == d2: 2054 | print("Dicts d1 and d2 have the same content") 2055 | d3 = d1 2056 | if d1 is d3: 2057 | print("Dicts d1 and d3 refer to the same dict") 2058 | if d2 is not d3: 2059 | print("Dicts d2 and d3 do not refer to the same dict") 2060 | ``` 2061 | 2062 | **VimScript:** 2063 | ```vim 2064 | let d1 = {'a' : 10, 'b' : 20} 2065 | let d2 = {'a' : 10, 'b' : 20} 2066 | if d1 == d2 2067 | echo "Dicts d1 and d2 have the same content" 2068 | endif 2069 | let d3 = d1 2070 | if d1 is d3 2071 | echo "Dicts d1 and d3 refer to the same dict" 2072 | endif 2073 | if d2 isnot d3 2074 | echo "Dicts d2 and d3 do not refer to the same dict" 2075 | endif 2076 | ``` 2077 | 2078 | *Help:* [dict-identity](https://vimhelp.org/eval.txt.html#dict-identity) 2079 | 2080 | ### Filter selected elements from a Dict 2081 | 2082 | Note that Vim does not support Dict comprehension. 2083 | 2084 | **Python:** 2085 | ```python 2086 | d1 = {'red' : 10, 'green' : 20, 'blue' : 10} 2087 | # filter dict items with value 10 2088 | d2 = dict(filter(lambda e : e[1] == 10, d1.items())) 2089 | print(d1, d2) 2090 | # use dict comprehension 2091 | d3 = {k: v for [k, v] in d1.items() if v == 10} 2092 | print(d1, d3) 2093 | ``` 2094 | 2095 | **VimScript:** 2096 | ```vim 2097 | let d1 = {'red' : 10, 'green' : 20, 'blue' : 10} 2098 | " filter dict items with value 10 2099 | let d2 = copy(d1)->filter({k, v -> v == 10}) 2100 | echo d1 d2 2101 | ``` 2102 | 2103 | *Help:* [filter()](https://vimhelp.org/builtin.txt.html#filter%28%29) 2104 | 2105 | ### Map Dict elements 2106 | 2107 | Note that Vim does not support Dict comprehension. 2108 | 2109 | **Python:** 2110 | ```python 2111 | d1 = {'red' : 10, 'green' : 20, 'blue' : 30} 2112 | # increment the values by 5 2113 | d2 = dict(map(lambda e : (e[0], e[1] + 5), d1.items())) 2114 | print(d1, d2) 2115 | # use dict comprehension 2116 | d3 = {k: v + 5 for k, v in d1.items()} 2117 | print(d1, d3) 2118 | ``` 2119 | 2120 | **VimScript:** 2121 | ```vim 2122 | let d1 = {'red' : 10, 'green' : 20, 'blue' : 30} 2123 | " increment the values by 5 2124 | let d2 = copy(d1)->map({k, v -> v + 5}) 2125 | echo d1 d2 2126 | ``` 2127 | 2128 | *Help:* [map()](https://vimhelp.org/builtin.txt.html#map%28%29) 2129 | 2130 | ### Finding the min/max value in a Dict 2131 | 2132 | **Python:** 2133 | ```python 2134 | d = {'red' : 10, 'green' : 20} 2135 | v1 = min(d.values()) 2136 | v2 = max(d.values()) 2137 | print(v1, v2) 2138 | ``` 2139 | 2140 | **VimScript:** 2141 | ```vim 2142 | let d = {'red' : 10, 'green' : 20} 2143 | let v1 = d->min() 2144 | let v2 = d->max() 2145 | echo v1 v2 2146 | ``` 2147 | 2148 | *Help:* [max()](https://vimhelp.org/builtin.txt.html#max%28%29), [min()](https://vimhelp.org/builtin.txt.html#min%28%29) 2149 | 2150 | ### Converting a Dict to a string 2151 | 2152 | **Python:** 2153 | ```python 2154 | d = str({'a' : 1, 'b' : 2}) 2155 | ``` 2156 | 2157 | **VimScript:** 2158 | ```vim 2159 | let d = string({'a' : 1, 'b' : 2}) 2160 | ``` 2161 | 2162 | *Help:* [string()](https://vimhelp.org/builtin.txt.html#string%28%29) 2163 | 2164 | ### Dictionary Methods 2165 | 2166 | Method|Python|VimScript 2167 | ----|------|--------- 2168 | clear()| `d.clear()` | `call filter(d, '0')` 2169 | copy()| `newDict = d.copy()` | `let newDict = d->copy()` 2170 | fromkeys()| `d = dict.fromkeys(x)` | `Not available` 2171 | get()| `v = d.get('red')` | `let v = d->get('red')` 2172 | in or has_key() | `'red' in d` | `d->has_key('red')` 2173 | items()| `d.items()` | `d->items()` 2174 | keys()| `d.keys()` | `d->keys()` 2175 | pop()| `d.pop('red')` | `call d->remove('red')` 2176 | popitem()| `d.popitem()` | `Not available` 2177 | setdefault()| `d.setdefault('red', 10)` | `Not available` 2178 | update()| `d.update({'a' : 10, 'b' : 20}` | `d->extend({'a' : 10, 'b' : 20})` 2179 | values()| `d.values()` | `d->values()` 2180 | 2181 | *Help:* [dict-functions](https://vimhelp.org/usr_41.txt.html#dict-functions) 2182 | 2183 | ------------------------------------------------------------------------------ 2184 | 2185 | ## If statement 2186 | 2187 | ### Basic If statement 2188 | 2189 | **Python:** 2190 | ```python 2191 | if a > b: 2192 | print("a is greater than b") 2193 | ``` 2194 | 2195 | **VimScript:** 2196 | ```vim 2197 | if a > b 2198 | echo "a is greater than b" 2199 | endif 2200 | ``` 2201 | 2202 | *Help:* [:if](https://vimhelp.org/eval.txt.html#%3aif) 2203 | 2204 | ### If-else statement 2205 | 2206 | **Python:** 2207 | ```python 2208 | if a > b: 2209 | print("a is greater than b") 2210 | else: 2211 | print("a is less than or equal to b") 2212 | ``` 2213 | 2214 | **VimScript:** 2215 | ```vim 2216 | if a > b 2217 | echo "a is greater than b" 2218 | else 2219 | echo "a is less than or equal to b" 2220 | endif 2221 | ``` 2222 | 2223 | *Help:* [:else](https://vimhelp.org/eval.txt.html#%3aelse) 2224 | 2225 | ### If-elseif statement 2226 | 2227 | **Python:** 2228 | ```python 2229 | if a > b: 2230 | print("a is greater than b") 2231 | elif a < b: 2232 | print("a is less than b") 2233 | else: 2234 | print("a is equal to b") 2235 | ``` 2236 | 2237 | **VimScript:** 2238 | ```vim 2239 | if a > b 2240 | echo "a is greater than b" 2241 | elseif a < b 2242 | echo "a is less than b" 2243 | else 2244 | echo "a is equal to b" 2245 | endif 2246 | ``` 2247 | 2248 | *Help:* [:elseif](https://vimhelp.org/eval.txt.html#%3aelseif) 2249 | 2250 | ### Checking multiple conditions 2251 | 2252 | **Python:** 2253 | ```python 2254 | if a > b and (a > c or a > d): 2255 | print "a is greater than b and greater than c or d" 2256 | ``` 2257 | 2258 | **VimScript:** 2259 | ```vim 2260 | if a > b && (a > c || a > d) 2261 | echo "a is greater than b and greater than c or d" 2262 | endif 2263 | ``` 2264 | 2265 | *Help:* [expr2](https://vimhelp.org/eval.txt.html#expr2) 2266 | 2267 | ### Nested If statements 2268 | **Python:** 2269 | ```python 2270 | if status == True: 2271 | if a >= 1: 2272 | print("Nested if") 2273 | ``` 2274 | 2275 | **VimScript:** 2276 | ```vim 2277 | if status == v:true 2278 | if a >= 1 2279 | echo "Nested if" 2280 | endif 2281 | endif 2282 | ``` 2283 | 2284 | *Help:* [:if](https://vimhelp.org/eval.txt.html#%3aif) 2285 | 2286 | ------------------------------------------------------------------------------ 2287 | 2288 | ## For Loop 2289 | 2290 | **Python:** 2291 | ```python 2292 | for i in range(5): 2293 | print(i) 2294 | ``` 2295 | 2296 | **VimScript:** 2297 | ```vim 2298 | for i in range(5) 2299 | echo i 2300 | endfor 2301 | ``` 2302 | 2303 | *Help:* [:for](https://vimhelp.org/eval.txt.html#%3afor) 2304 | 2305 | ### Breaking out of a For loop 2306 | **Python:** 2307 | ```python 2308 | for i in ['a', 'b', 'c']: 2309 | if i == 'b': 2310 | break 2311 | print(i) 2312 | ``` 2313 | 2314 | **VimScript:** 2315 | ```vim 2316 | for i in ['a', 'b', 'c'] 2317 | if i == 'b' 2318 | break 2319 | endif 2320 | echo i 2321 | endfor 2322 | ``` 2323 | 2324 | *Help:* [:break](https://vimhelp.org/eval.txt.html#%3abreak) 2325 | 2326 | ### Continuing a For loop 2327 | **Python:** 2328 | ```python 2329 | for i in ['a', 'b', 'c']: 2330 | if i == 'b': 2331 | continue 2332 | print(i) 2333 | ``` 2334 | 2335 | **VimScript:** 2336 | ```vim 2337 | for i in ['a', 'b', 'c'] 2338 | if i == 'b' 2339 | continue 2340 | endif 2341 | echo i 2342 | endfor 2343 | ``` 2344 | 2345 | *Help:* [:continue](https://vimhelp.org/eval.txt.html#%3acontinue) 2346 | 2347 | ### Nested For Loops 2348 | **Python:** 2349 | ```python 2350 | for i in range(10): 2351 | for j in range(10): 2352 | print(str(i) + 'x' + str(j) + '=' + str(i * j)) 2353 | ``` 2354 | 2355 | **VimScript:** 2356 | ```vim 2357 | for i in range(4) 2358 | for j in range(4) 2359 | echo i .. 'x' .. j .. '=' .. i * j 2360 | endfor 2361 | endfor 2362 | ``` 2363 | 2364 | *Help:* [:for](https://vimhelp.org/eval.txt.html#%3afor) 2365 | 2366 | ------------------------------------------------------------------------------ 2367 | 2368 | ## While Loop 2369 | 2370 | **Python:** 2371 | ```python 2372 | i = 1 2373 | while i <= 5 : 2374 | print(i) 2375 | i += 1 2376 | ``` 2377 | 2378 | **VimScript:** 2379 | ```vim 2380 | let i = 1 2381 | while i <= 5 2382 | echo i 2383 | let i += 1 2384 | endwhile 2385 | ``` 2386 | 2387 | *Help:* [:while](https://vimhelp.org/eval.txt.html#%3awhile) 2388 | 2389 | ------------------------------------------------------------------------------ 2390 | 2391 | ## Comment 2392 | 2393 | **Python:** 2394 | ```python 2395 | # This is a python comment 2396 | i = 0 # First iteration 2397 | ``` 2398 | 2399 | **VimScript:** 2400 | ```vim 2401 | " This is a Vimscript comment 2402 | let i = 0 " First iteration 2403 | ``` 2404 | 2405 | *Help:* [:comment](https://vimhelp.org/cmdline.txt.html#%3acomment) 2406 | 2407 | ------------------------------------------------------------------------------ 2408 | 2409 | ## Function 2410 | 2411 | The names of global functions in Vim must start with an uppercase letter. 2412 | The examples in this document use the "function" and "endfunction" keywords for 2413 | defining a function. But these can be abbreviated as "func" and "endfunc". 2414 | 2415 | When a function encounters an error, it will continue to execute the rest of the function unless the "abort" argument is specified when defining the function. So it is recommended to specify the "abort" keyword at the end of the "function" line. To simplify the example code, this keyword is not used in this guide. 2416 | 2417 | ### Defining a Function 2418 | 2419 | **Python:** 2420 | ```python 2421 | def Min(x, y): 2422 | return x if < y else y 2423 | 2424 | print(Min(6, 3) 2425 | ``` 2426 | 2427 | **VimScript:** 2428 | ```vim 2429 | function Min(x, y) abort 2430 | return a:x < a:y ? a:x : a:y 2431 | endfunction 2432 | 2433 | echo Min(6, 3) 2434 | ``` 2435 | 2436 | *Help:* [user-functions](https://vimhelp.org/eval.txt.html#user-functions) 2437 | 2438 | ### Calling a Function 2439 | 2440 | **Python:** 2441 | ```python 2442 | def EchoValue(v): 2443 | print(v) 2444 | 2445 | EchoValue(100) 2446 | ``` 2447 | 2448 | **VimScript:** 2449 | ```vim 2450 | function EchoValue(v) 2451 | echo a:v 2452 | endfunction 2453 | 2454 | call EchoValue(100) 2455 | ``` 2456 | 2457 | *Help:* [:call](https://vimhelp.org/eval.txt.html#%3acall) 2458 | 2459 | ### Function return value 2460 | 2461 | **Python:** 2462 | ```python 2463 | def Sum(a, b): 2464 | return a + b 2465 | 2466 | s = Sum(10, 20) 2467 | ``` 2468 | 2469 | **VimScript:** 2470 | ```vim 2471 | function Sum(a, b) 2472 | return a:a + a:b 2473 | endfunction 2474 | 2475 | let s = Sum(10, 20) 2476 | ``` 2477 | 2478 | *Help:* [:return](https://vimhelp.org/eval.txt.html#%3areturn) 2479 | 2480 | ### Pass by reference 2481 | 2482 | **Python:** 2483 | ```python 2484 | def AddValues(l): 2485 | l.extend([1, 2, 3, 4]) 2486 | ``` 2487 | 2488 | **VimScript:** 2489 | ```vim 2490 | function AddValues(l) 2491 | call extend(a:l, [1, 2, 3, 4]) 2492 | endfunction 2493 | ``` 2494 | 2495 | *Help:* [function-argument](https://vimhelp.org/eval.txt.html#function-argument) 2496 | 2497 | ### Variable number of arguments 2498 | 2499 | **Python:** 2500 | ```python 2501 | def Sum(v1, *args): 2502 | sum = v1 2503 | for i in *args: 2504 | sum += i 2505 | return sum 2506 | ``` 2507 | 2508 | **VimScript:** 2509 | ```vim 2510 | function Sum(v1, ...) 2511 | let sum = a:v1 2512 | for i in a:000 2513 | let sum +=i 2514 | endfor 2515 | return sum 2516 | endfunction 2517 | let s1 = Sum(10, 20, 30, 40) 2518 | let s1 = Sum(10) 2519 | ``` 2520 | 2521 | *Help:* [a:000](https://vimhelp.org/eval.txt.html#a%3a000) 2522 | 2523 | ### Default value for arguments 2524 | 2525 | **Python:** 2526 | ```python 2527 | def Powerof(base, exp = 2): 2528 | return base ** exp 2529 | ``` 2530 | 2531 | **VimScript:** 2532 | ```vim 2533 | function PowerOf(base, exp = 2) 2534 | return float2nr(pow(a:base, a:exp)) 2535 | endfunction 2536 | let val = PowerOf(4) 2537 | let val = PowerOf(4, 3) 2538 | ``` 2539 | 2540 | *Help:* [optional-function-argument](https://vimhelp.org/eval.txt.html#optional-function-argument) 2541 | 2542 | ### Accessing global variables 2543 | 2544 | **Python:** 2545 | ```python 2546 | counter = 1 2547 | def Incr(): 2548 | global counter 2549 | counter += 1 2550 | ``` 2551 | 2552 | **VimScript:** 2553 | ```vim 2554 | let counter = 1 2555 | function Incr() 2556 | let g:counter += 1 2557 | endfunction 2558 | cal Incr() 2559 | ``` 2560 | 2561 | *Help:* [global-variable](https://vimhelp.org/eval.txt.html#global-variable) 2562 | 2563 | ### Function reference 2564 | 2565 | **Python:** 2566 | ```python 2567 | def Foo(): 2568 | print("Foo") 2569 | Bar = Foo 2570 | Bar() 2571 | ``` 2572 | 2573 | **VimScript:** 2574 | ```vim 2575 | function Foo() 2576 | echo "Foo" 2577 | endfunction 2578 | let Bar = function("Foo") 2579 | call Bar() 2580 | ``` 2581 | 2582 | *Help:* [Funcref](https://vimhelp.org/eval.txt.html#Funcref) 2583 | 2584 | ------------------------------------------------------------------------------ 2585 | 2586 | ## Lambda Function 2587 | 2588 | **Python:** 2589 | ```python 2590 | F = lambda x , y: x - y 2591 | print(F(5,2)) 2592 | ``` 2593 | 2594 | **VimScript:** 2595 | ```vim 2596 | let F = {x, y -> x - y} 2597 | echo F(5,2) 2598 | ``` 2599 | 2600 | *Help:* [lambda](https://vimhelp.org/eval.txt.html#lambda) 2601 | 2602 | ------------------------------------------------------------------------------ 2603 | 2604 | ## Partial Function 2605 | 2606 | **Python:** 2607 | ```python 2608 | import functools 2609 | def Mylog(subsys, msg): 2610 | print("%s: %s" % (subsys, msg)) 2611 | 2612 | ErrLog = functools.partial(Mylog, 'ERR') 2613 | ErrLog("Failed to open file") 2614 | ``` 2615 | 2616 | **VimScript:** 2617 | ```vim 2618 | function Mylog(subsys, msg) 2619 | echo printf("%s: %s", a:subsys, a:msg) 2620 | endfunction 2621 | 2622 | let ErrLog = function('Mylog', ['ERR']) 2623 | call ErrLog("Failed to open file") 2624 | ``` 2625 | 2626 | *Help:* [Partial](https://vimhelp.org/eval.txt.html#Partial) 2627 | 2628 | ------------------------------------------------------------------------------ 2629 | 2630 | ## Closure 2631 | 2632 | ### Closure with a lambda function 2633 | 2634 | **Python:** 2635 | ```python 2636 | def foo(arg): 2637 | i = 3 2638 | return lambda x: x + i - arg 2639 | 2640 | bar = foo(4) 2641 | print(bar(6)) 2642 | ``` 2643 | 2644 | **VimScript:** 2645 | ```vim 2646 | function Foo(arg) 2647 | let i = 3 2648 | return {x -> x + i - a:arg} 2649 | endfunction 2650 | 2651 | let Bar = Foo(4) 2652 | echo Bar(6) 2653 | ``` 2654 | 2655 | *Help:* [closure](https://vimhelp.org/eval.txt.html#closure) 2656 | 2657 | ### Closure with a function reference 2658 | 2659 | **Python:** 2660 | ```python 2661 | def Foo(base): 2662 | def Bar(val): 2663 | return base + val 2664 | return Bar 2665 | 2666 | F = Foo(10) 2667 | print(F(2)) 2668 | F = Foo(20) 2669 | print(F(2)) 2670 | ``` 2671 | 2672 | **VimScript:** 2673 | ```vim 2674 | function Foo(base) 2675 | function Bar(val) closure 2676 | return a:base + a:val 2677 | endfunction 2678 | return funcref('Bar') 2679 | endfunction 2680 | 2681 | let F = Foo(10) 2682 | echo F(2) 2683 | let F = Foo(20) 2684 | echo F(2) 2685 | ``` 2686 | 2687 | *Help:* [func-closure](https://vimhelp.org/eval.txt.html#%3Afunc-closure) 2688 | 2689 | ------------------------------------------------------------------------------ 2690 | 2691 | ## Class 2692 | 2693 | ### Defining a class 2694 | 2695 | **Python:** 2696 | ```python 2697 | class Point: 2698 | def __init__(self, x, y): 2699 | self.x = x 2700 | self.y = y 2701 | 2702 | def getX(self): 2703 | return self.x 2704 | 2705 | def getY(self): 2706 | return self.y 2707 | 2708 | def setX(self, x): 2709 | self.x = x 2710 | 2711 | def setY(self, y): 2712 | self.y = y 2713 | 2714 | def Print(self): 2715 | print("Pt = (" + str(self.x) + ", " + str(self.y) + ")") 2716 | 2717 | pt = Point(10, 20) 2718 | pt.setX(40) 2719 | pt.setY(50) 2720 | pt.Print() 2721 | ``` 2722 | 2723 | **VimScript:** 2724 | ```vim 2725 | function s:new(x, y) dict 2726 | let newpt = copy(self) 2727 | let newpt.x = a:x 2728 | let newpt.y = a:y 2729 | return newpt 2730 | endfunction 2731 | 2732 | function s:getX() dict 2733 | return self.x 2734 | endfunction 2735 | 2736 | function s:getY() dict 2737 | return self.y 2738 | endfunction 2739 | 2740 | function s:setX(x) dict 2741 | let self.x = a:x 2742 | endfunction 2743 | 2744 | function s:setY(y) dict 2745 | let self.y = a:y 2746 | endfunction 2747 | 2748 | function s:Print() dict 2749 | echo "Pt = (" .. self.x .. ", " .. self.y .. ")" 2750 | endfunction 2751 | 2752 | let Point = {} 2753 | let Point.new = function("s:new") 2754 | let Point.getX = function("s:getX") 2755 | let Point.getY = function("s:getY") 2756 | let Point.setX = function("s:setX") 2757 | let Point.setY = function("s:setY") 2758 | let Point.Print = function("s:Print") 2759 | 2760 | let p = Point.new(10, 20) 2761 | call p.setX(40) 2762 | call p.setY(50) 2763 | call p.Print() 2764 | ``` 2765 | 2766 | *Help:* [Dictionary-function](https://vimhelp.org/eval.txt.html#Dictionary-function), [numbered-function](https://vimhelp.org/eval.txt.html#numbered-function), [:func-dict](https://vimhelp.org/eval.txt.html#%3afunc-dict) 2767 | 2768 | ------------------------------------------------------------------------------ 2769 | 2770 | ## Exception Handling 2771 | 2772 | ### Basic exception handling 2773 | 2774 | **Python:** 2775 | ```python 2776 | try: 2777 | f = open('buf.java', 'r') 2778 | lines = f.readlines() 2779 | f.close() 2780 | except IOError: 2781 | print("Failed to open file") 2782 | ``` 2783 | 2784 | **VimScript:** 2785 | ```vim 2786 | try 2787 | let l = readfile('buf.java') 2788 | catch /E484:/ 2789 | echo "Failed to read file" 2790 | endtry 2791 | ``` 2792 | 2793 | *Help:* [exception-handling](https://vimhelp.org/eval.txt.html#exception-handling) 2794 | 2795 | ### Catching all exceptions 2796 | 2797 | **Python:** 2798 | ```python 2799 | try: 2800 | f = open('buf.java', 'r') 2801 | lines = f.readlines() 2802 | f.close() 2803 | except Exception as e: 2804 | print("Caught " + str(e)) 2805 | ``` 2806 | 2807 | **VimScript:** 2808 | ```vim 2809 | try 2810 | let l = readfile('buf.java') 2811 | catch 2812 | echo "Caught " .. v:exception 2813 | endtry 2814 | ``` 2815 | 2816 | *Help:* [catch-errors](https://vimhelp.org/eval.txt.html#catch-errors) 2817 | 2818 | ### Executing code after a try block (finally) 2819 | 2820 | **Python:** 2821 | ```python 2822 | try: 2823 | f = open('buf.java', 'r') 2824 | lines = f.readlines() 2825 | f.close() 2826 | finally: 2827 | print("executing code in finally block") 2828 | ``` 2829 | 2830 | **VimScript:** 2831 | ```vim 2832 | try 2833 | let l = readfile('buf.java') 2834 | finally 2835 | echo "executing code in finally block" 2836 | endtry 2837 | ``` 2838 | 2839 | *Help:* [try-finally](https://vimhelp.org/eval.txt.html#try-finally) 2840 | 2841 | ### Raising a custom exception 2842 | 2843 | **Python:** 2844 | ```python 2845 | try: 2846 | raise Exception('MyException') 2847 | except Exception as e: 2848 | if str(e) == 'MyException': 2849 | print("Caught MyException") 2850 | finally: 2851 | print("Finally block") 2852 | ``` 2853 | 2854 | **VimScript:** 2855 | ```vim 2856 | try 2857 | throw 'MyException' 2858 | catch /MyException/ 2859 | echo "Caught MyException" 2860 | finally 2861 | echo "Finally block" 2862 | endtry 2863 | ``` 2864 | 2865 | *Help:* [throw-catch](https://vimhelp.org/eval.txt.html#throw-catch) 2866 | 2867 | ------------------------------------------------------------------------------ 2868 | 2869 | ## Line Continuation 2870 | 2871 | **Python:** 2872 | ```python 2873 | a = 1 + 2 + 3 + \ 2874 | 4 + 5 + 6 2875 | ``` 2876 | 2877 | **VimScript:** 2878 | ```vim 2879 | let a = 1 + 2 + 3 + 2880 | \ 4 + 5 + 6 2881 | ``` 2882 | 2883 | *Help:* [line-continuation](https://vimhelp.org/eval.txt.html#line-continuation) 2884 | 2885 | ------------------------------------------------------------------------------ 2886 | 2887 | ## File Operations 2888 | 2889 | ### Reading all the lines from a file 2890 | 2891 | Vim has a function to read the entire file but doesn't have a function to read a file one line at a time. 2892 | 2893 | **Python:** 2894 | ```python 2895 | with open('myfile.txt', 'r') as f: 2896 | lines = f.readlines() 2897 | # lines == ['line1\n', 'line2\n'] 2898 | ``` 2899 | 2900 | **VimScript:** 2901 | ```vim 2902 | let lines = readfile("myfile.txt") 2903 | " lines == ['line1', 'line2'] 2904 | ``` 2905 | 2906 | *Help:* [readfile()](https://vimhelp.org/builtin.txt.html#readfile%28%29) 2907 | 2908 | ### Writing lines to a file 2909 | **Python:** 2910 | ```python 2911 | lines = ['line1\n', 'line2\n'] 2912 | with open('myfile.txt', 'w') as fh: 2913 | fh.writelines(lines) 2914 | 2915 | lines = ['line1', 'line2'] 2916 | with open('myfile.txt', 'w') as fh: 2917 | print(*lines, sep='\n', file=fh) 2918 | ``` 2919 | 2920 | **VimScript:** 2921 | ```vim 2922 | call writefile(['line1', 'line2'], 'myfile.txt') 2923 | ``` 2924 | 2925 | *Help:* [writefile()](https://vimhelp.org/builtin.txt.html#writefile%28%29) 2926 | 2927 | ### Appending lines to a file 2928 | **Python:** 2929 | ```python 2930 | lines = ["line3\n", "line4\n"] 2931 | with open('myfile.txt', 'a') as fh: 2932 | fh.writelines(lines) 2933 | ``` 2934 | 2935 | **VimScript:** 2936 | ```vim 2937 | call writefile(['line3', 'line4'], 'myfile.txt', 'a') 2938 | ``` 2939 | 2940 | *Help:* [writefile()](https://vimhelp.org/builtin.txt.html#writefile%28%29) 2941 | 2942 | ### Checking whether a file exists 2943 | **Python:** 2944 | ```python 2945 | import os.path 2946 | if os.path.isfile('myfile.txt'): 2947 | print("File exists") 2948 | ``` 2949 | 2950 | **VimScript:** 2951 | ```vim 2952 | if filereadable('myfile.txt') 2953 | echo "File is readable" 2954 | endif 2955 | ``` 2956 | 2957 | *Help:* [filereadable()](https://vimhelp.org/builtin.txt.html#filereadable%28%29) 2958 | 2959 | ### Deleting a file 2960 | **Python:** 2961 | ```python 2962 | import os 2963 | os.remove('myfile.txt') 2964 | ``` 2965 | 2966 | **VimScript:** 2967 | ```vim 2968 | call delete('myfile.txt') 2969 | ``` 2970 | 2971 | *Help:* [remove()](https://vimhelp.org/builtin.txt.html#remove%28%29) 2972 | 2973 | ### Renaming a file 2974 | **Python:** 2975 | ```python 2976 | import os 2977 | os.rename('myfile.txt', 'somefile.txt) 2978 | ``` 2979 | 2980 | **VimScript:** 2981 | ```vim 2982 | call rename('myfile.txt', 'somefile.txt') 2983 | ``` 2984 | 2985 | *Help:* [rename()](https://vimhelp.org/builtin.txt.html#rename%28%29) 2986 | 2987 | ### Getting the size of a file 2988 | **Python:** 2989 | ```python 2990 | import os 2991 | sz = os.path.getsize('move.py') 2992 | ``` 2993 | 2994 | **VimScript:** 2995 | ```vim 2996 | let sz = getfsize('move.py') 2997 | ``` 2998 | 2999 | *Help:* [getfsize()](https://vimhelp.org/builtin.txt.html#getfsize%28%29) 3000 | 3001 | ------------------------------------------------------------------------------ 3002 | 3003 | ## Directory Operations 3004 | 3005 | ### Creating a directory 3006 | **Python:** 3007 | ```python 3008 | os.mkdir('somedir') 3009 | ``` 3010 | 3011 | **VimScript:** 3012 | ```vim 3013 | call mkdir('somedir') 3014 | ``` 3015 | 3016 | *Help:* [mkdir()](https://vimhelp.org/builtin.txt.html#mkdir%28%29) 3017 | 3018 | ### Changing to a directory 3019 | **Python:** 3020 | ```python 3021 | os.chdir('someotherdir') 3022 | ``` 3023 | 3024 | **VimScript:** 3025 | ```vim 3026 | call chdir('someotherdir') 3027 | ``` 3028 | 3029 | *Help:* [chdir()](https://vimhelp.org/builtin.txt.html#chdir%28%29) 3030 | 3031 | ### Getting the current directory 3032 | **Python:** 3033 | ```python 3034 | dir = os.getcwd() 3035 | ``` 3036 | 3037 | **VimScript:** 3038 | ```vim 3039 | let dir = getcwd() 3040 | ``` 3041 | 3042 | *Help:* [getcwd()](https://vimhelp.org/builtin.txt.html#getcwd%28%29) 3043 | 3044 | ### Deleting a directory 3045 | **Python:** 3046 | ```python 3047 | os.rmdir('somedir') 3048 | ``` 3049 | 3050 | **VimScript:** 3051 | ```vim 3052 | call delete('somedir', 'd') 3053 | ``` 3054 | 3055 | *Help:* [delete()](https://vimhelp.org/builtin.txt.html#delete%28%29) 3056 | 3057 | ### Reading the directory contents 3058 | **Python:** 3059 | ```python 3060 | import os 3061 | dir = os.scandir('.') 3062 | for f in dir: 3063 | print(f.name) 3064 | 3065 | # get extended file information 3066 | dir = os.scandir('.') 3067 | for f in dir: 3068 | print(f.stat()) 3069 | ``` 3070 | 3071 | **VimScript:** 3072 | ```vim 3073 | let dir = readdir('.') 3074 | for f in dir 3075 | echo f 3076 | endfor 3077 | 3078 | " get extended file information 3079 | let dir = readdirex('.') 3080 | for f in dir 3081 | echo f 3082 | endfor 3083 | ``` 3084 | 3085 | *Help:* [readdir()](https://vimhelp.org/builtin.txt.html#readdir%28%29), [readdirex()](https://vimhelp.org/builtin.txt.html#readdirex%28%29), [glob()](https://vimhelp.org/builtin.txt.html#glob%28%29) 3086 | 3087 | ------------------------------------------------------------------------------ 3088 | 3089 | ## Random numbers 3090 | 3091 | ### Generating a random number 3092 | **Python:** 3093 | ```python 3094 | import random 3095 | r = random.randint(0, 2147483647) 3096 | ``` 3097 | 3098 | **VimScript:** 3099 | ```vim 3100 | let r = rand() 3101 | ``` 3102 | 3103 | *Help:* [rand()](https://vimhelp.org/builtin.txt.html#rand%28%29) 3104 | 3105 | ### Generating a random number from a seed 3106 | **Python:** 3107 | ```python 3108 | import random 3109 | random.seed() 3110 | r = random.randint(0, 2147483647) 3111 | print(r) 3112 | ``` 3113 | 3114 | **VimScript:** 3115 | ```vim 3116 | let seed = srand() 3117 | let r = rand(seed) 3118 | ``` 3119 | 3120 | *Help:* [srand()](https://vimhelp.org/builtin.txt.html#srand%28%29) 3121 | 3122 | ------------------------------------------------------------------------------ 3123 | 3124 | ## Mathematical Functions 3125 | 3126 | Function|Python|VimScript 3127 | ----|------|--------- 3128 | abs| `f = math.fabs(-10)` | `let f = abs(-10)` 3129 | acos| `f = math.acos(0.8)` | `let f = acos(0.8)` 3130 | asin| `f = math.asin(0.8)` | `let f = asin(0.8)` 3131 | atan| `f = math.atan(0.8)` | `let f = atan(0.8)` 3132 | atan2| `f = math.atan2(0.4, 0.8)` | `let f = atan2(0.4, 0.8)` 3133 | ceil| `f = math.ceil(1.2)` | `let f = ceil(1.2)` 3134 | cos| `f = math.cos(4)` | `let f = cos(4)` 3135 | cosh| `f = math.cosh(4)` | `let f = cosh(4)` 3136 | exp| `f = math.exp(2)` | `let f = exp(2)` 3137 | floor| `f = math.floor(1.4)` | `let f = floor(1.4)` 3138 | log| `f = math.log(12)` | `let f = log(12)` 3139 | log10| `f = math.log10(100)` | `let f = log10(100)` 3140 | mod| `f = math.fmod(4, 3)` | `let f = fmod(4, 3)` 3141 | pow| `f = math.pow(2, 3)` | `let f = pow(2, 3)` 3142 | sin| `f = math.sin(4)` | `let f = sin(4)` 3143 | sinh| `f = math.sinh(4)` | `let f = sinh(4)` 3144 | sqrt| `f = math.sqrt(9)` | `let f = sqrt(9)` 3145 | tan| `f = math.tan(4)` | `let f = tan(4)` 3146 | tanh| `f = math.tanh(4)` | `let f = tanh(4)` 3147 | trunc| `f = math.trunc(1.3)` | `let f = trunc(1.3)` 3148 | 3149 | *Help:* [ceil()](https://vimhelp.org/builtin.txt.html#ceil%28%29), [abs()](https://vimhelp.org/builtin.txt.html#abs%28%29), [floor()](https://vimhelp.org/builtin.txt.html#floor%28%29), [fmod()](https://vimhelp.org/builtin.txt.html#fmod%28%29), [trunc()](https://vimhelp.org/builtin.txt.html#trunc%28%29), [exp()](https://vimhelp.org/builtin.txt.html#exp%28%29), [log()](https://vimhelp.org/builtin.txt.html#log%28%29), [log10()](https://vimhelp.org/builtin.txt.html#log10%28%29), [pow()](https://vimhelp.org/builtin.txt.html#pow%28%29), [sqrt()](https://vimhelp.org/builtin.txt.html#sqrt%28%29), [cos()](https://vimhelp.org/builtin.txt.html#cos%28%29), [sin()](https://vimhelp.org/builtin.txt.html#sin%28%29), [tan()](https://vimhelp.org/builtin.txt.html#tan%28%29), [cosh()](https://vimhelp.org/builtin.txt.html#cosh%28%29), [sinh()](https://vimhelp.org/builtin.txt.html#sinh%28%29), [tanh()](https://vimhelp.org/builtin.txt.html#tanh%28%29), [acos()](https://vimhelp.org/builtin.txt.html#acos%28%29), [asin()](https://vimhelp.org/builtin.txt.html#asin%28%29), [atan()](https://vimhelp.org/builtin.txt.html#atan%28%29), [atan2()](https://vimhelp.org/builtin.txt.html#atan2%28%29) 3150 | 3151 | ------------------------------------------------------------------------------ 3152 | 3153 | ## Date/Time functions 3154 | 3155 | ### Get current date and time 3156 | 3157 | **Python:** 3158 | ```python 3159 | from datetime import datetime 3160 | d = datetime.now() 3161 | print(d.strftime("%c")) 3162 | ``` 3163 | 3164 | **VimScript:** 3165 | ```vim 3166 | echo strftime("%c") 3167 | ``` 3168 | 3169 | *Help:* [strftime()](https://vimhelp.org/builtin.txt.html#strftime%28%29) 3170 | 3171 | ### Parse a date/time string 3172 | 3173 | **Python:** 3174 | ```python 3175 | from datetime import datetime 3176 | print(datetime.strptime("1997 Apr 27 11:49:23", "%Y %b %d %X")) 3177 | ``` 3178 | 3179 | **VimScript:** 3180 | ```vim 3181 | echo strptime("%Y %b %d %X", "1997 Apr 27 11:49:23") 3182 | ``` 3183 | 3184 | *Help:* [strptime()](https://vimhelp.org/builtin.txt.html#strptime%28%29) 3185 | 3186 | ### Getting the time in seconds since epoch 3187 | 3188 | **Python:** 3189 | ```python 3190 | import time 3191 | print int(time.time()) 3192 | ``` 3193 | 3194 | **VimScript:** 3195 | ```vim 3196 | echo localtime() 3197 | ``` 3198 | 3199 | *Help:* [localtime()](https://vimhelp.org/builtin.txt.html#localtime%28%29) 3200 | 3201 | ### Measuring elapsed time 3202 | 3203 | **Python:** 3204 | ```python 3205 | import time 3206 | start_time = time.perf_counter() 3207 | sum = 1 3208 | for i in range(1000): 3209 | sum += i 3210 | end_time = time.perf_counter() 3211 | print("Elapsed time " + str(end_time - start_time)) 3212 | ``` 3213 | 3214 | **VimScript:** 3215 | ```vim 3216 | let start = reltime() 3217 | let sum = 0 3218 | for i in range(1000) 3219 | let sum += i 3220 | endfor 3221 | let elapsed_time = reltime(start) 3222 | echo "Elasped time" reltimefloat(elapsed_time) 3223 | ``` 3224 | 3225 | *Help:* [reltime()](https://vimhelp.org/builtin.txt.html#reltime%28%29), [reltimestr()](https://vimhelp.org/builtin.txt.html#reltimestr%28%29), [reltimefloat()](https://vimhelp.org/builtin.txt.html#reltimefloat%28%29) 3226 | 3227 | ------------------------------------------------------------------------------ 3228 | 3229 | ## External commands 3230 | 3231 | ### Getting the output of an external command as a string 3232 | 3233 | **Python:** 3234 | ```python 3235 | import subprocess 3236 | procObj = subprocess.Popen('grep class *.java', 3237 | stdout=subprocess.PIPE, 3238 | shell=True) 3239 | lines, err = procObj.communicate() 3240 | print(lines) 3241 | print("Error = " + str(procObj.returncode)) 3242 | ``` 3243 | 3244 | **VimScript:** 3245 | ```vim 3246 | let lines = system('grep class *.java') 3247 | echo lines 3248 | echo "Error = " .. v:shell_error 3249 | ``` 3250 | 3251 | *Help:* [system()](https://vimhelp.org/builtin.txt.html#system%28%29), [v:shell_error](https://vimhelp.org/eval.txt.html#v%3ashell_error) 3252 | 3253 | ### Splitting the output of an external command into lines 3254 | 3255 | **Python:** 3256 | ```python 3257 | import subprocess 3258 | procObj = subprocess.Popen('grep class *.java', 3259 | stdout=subprocess.PIPE, 3260 | shell=True) 3261 | lines, err = procObj.communicate() 3262 | print("Number of matches = " + str(len(lines.splitlines()))) 3263 | ``` 3264 | 3265 | **VimScript:** 3266 | ```vim 3267 | let lines = systemlist('grep class *.java') 3268 | echo "Number of matches = " .. len(lines) 3269 | ``` 3270 | 3271 | *Help:* [systemlist()](https://vimhelp.org/builtin.txt.html#systemlist%28%29) 3272 | 3273 | ### Sending input to an external command and getting the output 3274 | 3275 | **Python:** 3276 | ```python 3277 | import subprocess 3278 | procObj = subprocess.Popen('wc', 3279 | stdout=subprocess.PIPE, 3280 | stdin=subprocess.PIPE, 3281 | shell=True) 3282 | lines, err = procObj.communicate("one\ntwo\n") 3283 | print(lines) 3284 | print("Error = " + str(procObj.returncode)) 3285 | ``` 3286 | 3287 | **VimScript:** 3288 | ```vim 3289 | let lines = system('wc', "one\ntwo\n") 3290 | echo lines 3291 | echo "Error = " .. v:shell_error 3292 | ``` 3293 | 3294 | *Help:* [system()](https://vimhelp.org/builtin.txt.html#system%28%29) 3295 | 3296 | ------------------------------------------------------------------------------ 3297 | 3298 | ## User Input/Output 3299 | 3300 | ### Getting input from the user 3301 | 3302 | **Python:** 3303 | ```python 3304 | choice = input("coffee or tea? ") 3305 | print("You selected " + choice) 3306 | ``` 3307 | 3308 | **VimScript:** 3309 | ```vim 3310 | let ans = input("coffee or tea? ", "tea") 3311 | echo "You selected " .. ans 3312 | ``` 3313 | 3314 | *Help:* [input()](https://vimhelp.org/builtin.txt.html#input%28%29), [inputlist()](https://vimhelp.org/builtin.txt.html#inputlist%28%29), [inputdialog()](https://vimhelp.org/builtin.txt.html#inputdialog%28%29) 3315 | 3316 | ### Getting password from the user 3317 | 3318 | **Python:** 3319 | ```python 3320 | import getpass 3321 | passwd = getpass.getpass("Password: ") 3322 | print("You entered " + passwd) 3323 | ``` 3324 | 3325 | **VimScript:** 3326 | ```vim 3327 | let passwd = inputsecret("Password: ") 3328 | echo "You entered " .. passwd 3329 | ``` 3330 | 3331 | *Help:* [inputsecret()](https://vimhelp.org/builtin.txt.html#inputsecret%28%29) 3332 | 3333 | ### Print an expression 3334 | 3335 | **Python:** 3336 | ```python 3337 | print("Hello World\n") 3338 | s = "vim" 3339 | print("Editor = %s" % (s)) 3340 | ``` 3341 | 3342 | **VimScript:** 3343 | ```vim 3344 | echo "Hello World" 3345 | let s = "vim" 3346 | echo "Editor = " .. s 3347 | ``` 3348 | 3349 | *Help:* [:echo](https://vimhelp.org/eval.txt.html#%3Aecho), [:echon](https://vimhelp.org/eval.txt.html#%3Aechon), [echoraw()](https://vimhelp.org/builtin.txt.html#echoraw%28%29), [:echohl](https://vimhelp.org/eval.txt.html#%3Aechohl), [:echoerr](https://vimhelp.org/eval.txt.html#%3Aechoerr), [:echomsg](https://vimhelp.org/eval.txt.html#%3Aechomsg) 3350 | 3351 | ### Formatted Output 3352 | 3353 | **Python:** 3354 | ```python 3355 | name = "John" 3356 | id = 1001 3357 | print(f"Name: {name}, ID: {id}") 3358 | print("Name: {}, ID: {}".format(name, id)) 3359 | print("Name: %s, ID: %d" % (name, id)) 3360 | ``` 3361 | 3362 | **VimScript:** 3363 | ```vim 3364 | let name = "John" 3365 | let id = 1001 3366 | echo printf("Name: %s, ID: %d", name, id) 3367 | ``` 3368 | 3369 | *Help:* [printf()](https://vimhelp.org/builtin.txt.html#printf%28%29) 3370 | 3371 | ------------------------------------------------------------------------------ 3372 | 3373 | ## Environment Variables 3374 | 3375 | ### Getting the value of an environment variable 3376 | 3377 | **Python:** 3378 | ```python 3379 | import os 3380 | h = os.environ.get('HOME', '') 3381 | if h == '': 3382 | print("HOME is not set") 3383 | else: 3384 | print("HOME = " + h) 3385 | ``` 3386 | 3387 | **VimScript:** 3388 | ```vim 3389 | let h = getenv('HOME') 3390 | if h == v:null 3391 | echo 'HOME is not set' 3392 | else 3393 | echo 'HOME = ' .. h 3394 | endif 3395 | 3396 | if !exists('$HOME') 3397 | echo 'HOME is not set' 3398 | else 3399 | echo 'HOME = ' .. $HOME 3400 | endif 3401 | ``` 3402 | 3403 | *Help:* [getenv()](https://vimhelp.org/builtin.txt.html#getenv%28%29), [expr-env](https://vimhelp.org/eval.txt.html#expr-env), [exists()](https://vimhelp.org/builtin.txt.html#exists%28%29) 3404 | 3405 | ### Setting an environment variable 3406 | 3407 | **Python:** 3408 | ```python 3409 | import os 3410 | os.environ['FOO'] = "BAR" 3411 | ``` 3412 | 3413 | **VimScript:** 3414 | ```vim 3415 | call setenv('FOO', 'BAR') 3416 | 3417 | let $FOO = 'BAR' 3418 | ``` 3419 | 3420 | *Help:* [setenv()](https://vimhelp.org/builtin.txt.html#setenv%28%29), [:let-environment](https://vimhelp.org/eval.txt.html#%3alet-environment) 3421 | 3422 | ### Removing an environment variable 3423 | 3424 | **Python:** 3425 | ```python 3426 | import os 3427 | del os.environ['FOO'] 3428 | ``` 3429 | 3430 | **VimScript:** 3431 | ```vim 3432 | call setenv('FOO', v:null) 3433 | 3434 | unlet $FOO 3435 | ``` 3436 | 3437 | *Help:* [setenv()](https://vimhelp.org/builtin.txt.html#setenv%28%29), [:unlet-environment](https://vimhelp.org/eval.txt.html#%3aunlet-environment) 3438 | 3439 | ### Getting all the environment variables 3440 | 3441 | **Python:** 3442 | ```python 3443 | import os 3444 | print(os.environ) 3445 | ``` 3446 | 3447 | **VimScript:** 3448 | ```vim 3449 | echo environ() 3450 | ``` 3451 | 3452 | *Help:* [environ()](https://vimhelp.org/builtin.txt.html#environ%28%29) 3453 | 3454 | ------------------------------------------------------------------------------ 3455 | 3456 | ## Command-line Arguments 3457 | 3458 | ### Displaying the command-line arguments 3459 | 3460 | **Python:** 3461 | ```python 3462 | import sys 3463 | print("Number of arguments = " + str(len(sys.argv))) 3464 | print("Arguments = " + str(sys.argv)) 3465 | for arg in sys.argv: 3466 | print(arg) 3467 | ``` 3468 | 3469 | **VimScript:** 3470 | ```vim 3471 | echo "Number of arguments = " .. len(v:argv) 3472 | echo "Arguments = " .. string(v:argv) 3473 | for arg in v:argv 3474 | echo arg 3475 | endfor 3476 | ``` 3477 | 3478 | *Help:* [v:argv](https://vimhelp.org/eval.txt.html#v%3aargv) 3479 | 3480 | ------------------------------------------------------------------------------ 3481 | 3482 | ## Regular Expressions 3483 | 3484 | ### Finding whether a pattern matches a string 3485 | 3486 | **Python:** 3487 | ```python 3488 | import re 3489 | s = 'Test failed with error E123:' 3490 | if re.search(r'E\d+:', s): 3491 | print('Error code found') 3492 | 3493 | s = 'Test successful' 3494 | if re.search(r'E\d+:', s) is None: 3495 | print("Test passed") 3496 | ``` 3497 | 3498 | **VimScript:** 3499 | ```vim 3500 | let s = 'Test failed with error E123:' 3501 | if s =~# 'E\d\+:' 3502 | echo "Error code found" 3503 | endif 3504 | 3505 | let s = 'Test successful' 3506 | if s !~# 'E\d\+:' 3507 | echo "Test passed" 3508 | endif 3509 | ``` 3510 | 3511 | *Help:* [expr-=~](https://vimhelp.org/eval.txt.html#expr-%3d~), [expr-!~](https://vimhelp.org/eval.txt.html#expr-%21~) 3512 | 3513 | ### Finding the beginning or ending index of a pattern in a string 3514 | 3515 | **Python:** 3516 | ```python 3517 | import re 3518 | m = re.search(r'\d+', "Abc 123 Def") 3519 | if m is not None: 3520 | idx = m.start() 3521 | end_idx = m.end() 3522 | ``` 3523 | 3524 | **VimScript:** 3525 | ```vim 3526 | let idx = match("Abc 123 Def", '\d\+') 3527 | let end_idx = matchend("Abc 123 Def", '\d\+') 3528 | 3529 | let l = matchstrpos("Abc 123 Def", '\d\+') 3530 | echo "start:" l[1] "end:" l[2] 3531 | ``` 3532 | 3533 | *Help:* [match()](https://vimhelp.org/builtin.txt.html#match%28%29), [matchend()](https://vimhelp.org/builtin.txt.html#matchend%28%29), [matchstrpos()](https://vimhelp.org/builtin.txt.html#matchstrpos%28%29) 3534 | 3535 | ### Getting matching substring using a pattern 3536 | 3537 | **Python:** 3538 | ```python 3539 | import re 3540 | m = re.search(r'\d+', "Abc 123 Def") 3541 | if m is not None: 3542 | s = m.group(0) 3543 | print s 3544 | ``` 3545 | 3546 | **VimScript:** 3547 | ```vim 3548 | let s = matchstr("Abc 123 Def", '\d\+') 3549 | ``` 3550 | 3551 | *Help:* [matchstr()](https://vimhelp.org/builtin.txt.html#matchstr%28%29) 3552 | 3553 | ### Getting multiple matches using a pattern 3554 | 3555 | **Python:** 3556 | ```python 3557 | import re 3558 | m = re.match(r'(\w+) (\w+) (\w+)', "foo bar baz") 3559 | if m is not None: 3560 | print("Full match: " + m.group(0)) 3561 | print("1: " + m.group(1) + " 2: " + m.group(2) + " 3: " + m.group(3)) 3562 | ``` 3563 | 3564 | **VimScript:** 3565 | ```vim 3566 | let list = matchlist("foo bar baz", '\(\w\+\) \(\w\+\) \(\w\+\)') 3567 | echo "Full match:" list[0] 3568 | echo "1:" list[1] "2:" list[2] "3:" list[3] 3569 | ``` 3570 | 3571 | *Help:* [matchlist()](https://vimhelp.org/builtin.txt.html#matchlist%28%29) 3572 | 3573 | ### Substituting text using a pattern 3574 | 3575 | **Python:** 3576 | ```python 3577 | import re 3578 | s = re.sub(r'bar', r'baz', "foo bar") 3579 | print(s) 3580 | ``` 3581 | 3582 | **VimScript:** 3583 | ```vim 3584 | let s = substitute("foo bar", 'bar', 'baz', '') 3585 | echo s 3586 | ``` 3587 | 3588 | *Help:* [substitute()](https://vimhelp.org/builtin.txt.html#substitute%28%29) 3589 | 3590 | ### Using a function to get the replacement string 3591 | 3592 | **Python:** 3593 | ```python 3594 | import re 3595 | def Dashrepl(m): 3596 | if m.group(0) == '-': 3597 | return ' ' 3598 | else: 3599 | return '-' 3600 | s = re.sub('-{1,2}', Dashrepl, 'pro----gram-files') 3601 | print(s) 3602 | ``` 3603 | 3604 | **VimScript:** 3605 | ```vim 3606 | function Dashrepl(m) 3607 | if a:m[0] == '-' 3608 | return ' ' 3609 | else 3610 | return '-' 3611 | endif 3612 | endfunction 3613 | let s = substitute("pro----gram-files", '-\{1,2}', function('Dashrepl'), 'g') 3614 | echo s 3615 | ``` 3616 | 3617 | *Help:* [substitute()](https://vimhelp.org/builtin.txt.html#substitute%28%29) 3618 | 3619 | ### Regular expression comparison 3620 | 3621 | Note that the below table contains only the regular expressions that are present in both Python and Vim. 3622 | 3623 | What|Python|Vim 3624 | ----|------|--- 3625 | single character| `.` | `.` 3626 | start of string| `^` | `^` 3627 | end of string| `$` | `$` 3628 | 0 or more matches| `*` | `*` 3629 | 1 or more matches| `+` | `\+` 3630 | 0 or 1 match| `?` | `\?` 3631 | non-greedy match| `*?` | `\{-}` 3632 | fixed matches| `{n}` | `\{n}` 3633 | m to n matches| `{m,n}` | `\{m,n}` 3634 | m to n non-greedy matches| `{m,n}?` | `\{-m,n}` 3635 | character class| `[...]` | `[...]` 3636 | negated character class| `[^...]` | `[^...]` 3637 | range| `[a-z]` | `[a-z]` 3638 | either-or branch| `\|` | `\\|` 3639 | capturing group| `(...)` | `\(...\)` 3640 | non-capturing match| `(?:...)` | `\%(...\)` 3641 | positive look-ahead| `(?=...)` | `\(...\)\@=` 3642 | negative look-ahead| `(?!...)` | `\(...\)\@!` 3643 | positive look-behind| `(?<=...)` | `\(...\)\@<=` 3644 | negative look-behind| `(?` 3647 | digit| `\d` | `\d` 3648 | non-digit| `\D` | `\D` 3649 | whitespace| `\s` | `\s` 3650 | non-whitespace| `\S` | `\S` 3651 | word character| `\w` | `\w` 3652 | non-word character| `\W` | `\W` 3653 | ignore case| `(?i)` | `\c` 3654 | 3655 | *Help:* [pattern](https://vimhelp.org/pattern.txt.html#pattern) 3656 | 3657 | ------------------------------------------------------------------------------ 3658 | 3659 | ## Binary Data 3660 | 3661 | ### Storing binary data in a variable 3662 | 3663 | **Python:** 3664 | ```python 3665 | data = bytearray(b'\x12\xF6\xAB\xFF\x49\xC0\x88\x3A\xE2\xC1\x42\xAA') 3666 | print(data) 3667 | print(data[0:4]) 3668 | ``` 3669 | 3670 | **VimScript:** 3671 | ```vim 3672 | let data = 0z12F6ABFF.49C0883A.E2C142AA 3673 | echo data 3674 | echo data[0:3] 3675 | ``` 3676 | 3677 | *Help:* [blob](https://vimhelp.org/eval.txt.html#blob) 3678 | 3679 | ### Manipulating binary data stored in a variable 3680 | 3681 | **Python:** 3682 | ```python 3683 | data = bytearray(b'') 3684 | data.append(0xC2) 3685 | data += b'\xB3\xF7\xA5' 3686 | del data[2] 3687 | print(data) 3688 | ``` 3689 | 3690 | **VimScript:** 3691 | ```vim 3692 | let data = 0z 3693 | let data[0] = 0xC2 3694 | let data += 0zB3F7A5 3695 | call remove(data, 2) 3696 | echo data 3697 | ``` 3698 | 3699 | *Help:* [blob-index](https://vimhelp.org/eval.txt.html#blob-index), [blob-modification](https://vimhelp.org/eval.txt.html#blob-modification) 3700 | 3701 | ### Converting a List of numbers to binary data and vice versa 3702 | 3703 | **Python:** 3704 | ```python 3705 | l = [11, 12, 14] 3706 | data = bytearray(l) 3707 | print(data) 3708 | 3709 | data = bytearray(b'\xDE\xAD\xBE\xEF') 3710 | l = list(data) 3711 | print(l) 3712 | ``` 3713 | 3714 | **VimScript:** 3715 | ```vim 3716 | let l = [11, 12, 14] 3717 | let data = list2blob(l) 3718 | echo data 3719 | 3720 | let data = 0zDEADBEEF 3721 | let l = blob2list(data) 3722 | echo l 3723 | ``` 3724 | 3725 | *Help:* [list2blob()](https://vimhelp.org/builtin.txt.html#list2blob%28%29), [blob2list()](https://vimhelp.org/builtin.txt.html#blob2list%28%29) 3726 | 3727 | ### Reading and writing binary data from a file 3728 | 3729 | **Python:** 3730 | ```python 3731 | with open("datafile.bin", "rb") as bin_fh: 3732 | data = bytearray(bin_fh.read()) 3733 | 3734 | with open("data2.bin", "wb") as bin_fh: 3735 | bin_fh.write(data) 3736 | ``` 3737 | 3738 | **VimScript:** 3739 | ```vim 3740 | let data = readblob('datafile.bin') 3741 | call writefile(data, 'data2.bin') 3742 | ``` 3743 | 3744 | *Help:* [readblob()](https://vimhelp.org/builtin.txt.html#readblob%28%29), [writefile()](https://vimhelp.org/builtin.txt.html#writefile%28%29) 3745 | 3746 | ------------------------------------------------------------------------------ 3747 | 3748 | ## Timers 3749 | 3750 | ### One-shot Timer 3751 | 3752 | **Python:** 3753 | ```python 3754 | import threading 3755 | def TimerCallback(ctx): 3756 | print("Timer callback, context = " + ctx) 3757 | 3758 | timer = threading.Timer(5, TimerCallback, args=["green"]) 3759 | timer.start() 3760 | ``` 3761 | 3762 | **VimScript:** 3763 | ```vim 3764 | func TimerCallback(ctx, timer_id) 3765 | echo "Timer callback, context = " .. a:ctx .. ", id = " .. a:timer_id 3766 | endfunc 3767 | 3768 | " Run a function after 5 seconds 3769 | let timer_id = timer_start(5 * 1000, function('TimerCallback', ["green"])) 3770 | ``` 3771 | 3772 | *Help:* [timer_start()](https://vimhelp.org/builtin.txt.html#timer_start%28%29) 3773 | 3774 | ### Periodic Timer 3775 | 3776 | **Python:** 3777 | ```python 3778 | import threading 3779 | def TimerCallback(): 3780 | print("Timer callback") 3781 | threading.Timer(5, TimerCallback).start() 3782 | 3783 | # run a function every 5 seconds (approximately) 3784 | timer = threading.Timer(5, TimerCallback) 3785 | timer.start() 3786 | ``` 3787 | 3788 | **VimScript:** 3789 | ```vim 3790 | func TimerCallback(timer_id) 3791 | echo "Timer callback" 3792 | endfunc 3793 | 3794 | " run a function every 5 seconds periodically 3795 | let timer_id = timer_start(5 * 1000, function('TimerCallback'), {'repeat' : -1}) 3796 | ``` 3797 | 3798 | *Help:* [timer](https://vimhelp.org/eval.txt.html#timer) 3799 | 3800 | ### Stopping a timer 3801 | 3802 | **Python:** 3803 | ```python 3804 | import threading 3805 | def TimerCallback(): 3806 | print("Timer callback") 3807 | 3808 | timer = threading.Timer(1, TimerCallback) 3809 | timer.start() 3810 | timer.cancel() 3811 | ``` 3812 | 3813 | **VimScript:** 3814 | ```vim 3815 | func TimerCallback(timer_id) 3816 | echo "Timer callback" 3817 | endfunc 3818 | 3819 | " start a timer and then stop it 3820 | let timer_id = timer_start(1000, 'TimerCallback') 3821 | call timer_stop(timer_id) 3822 | 3823 | " to stop all the timers 3824 | call timer_stopall() 3825 | ``` 3826 | 3827 | *Help:* [timer_start()](https://vimhelp.org/builtin.txt.html#timer_start%28%29) 3828 | 3829 | ### Sleeping for a specified number of seconds 3830 | 3831 | **Python:** 3832 | ```python 3833 | import time 3834 | time.sleep(5) 3835 | time.sleep(0.2) 3836 | ``` 3837 | 3838 | **VimScript:** 3839 | ```vim 3840 | " sleep for 5 seconds 3841 | sleep 5 3842 | " sleep for 200 milliseconds 3843 | sleep 200m 3844 | ``` 3845 | 3846 | *Help:* [:sleep](https://vimhelp.org/various.txt.html#%3asleep) 3847 | 3848 | ------------------------------------------------------------------------------ 3849 | 3850 | ## JSON encoder and decoder 3851 | 3852 | **Python:** 3853 | ```python 3854 | import json 3855 | v = ['foo', {'a' : 3}, True] 3856 | # encode data to JSON 3857 | str = json.dumps(v) 3858 | # decode data from JSON 3859 | x = json.loads(str) 3860 | ``` 3861 | 3862 | **VimScript:** 3863 | ```vim 3864 | let v = ['foo', {'a' : 3}, v:true] 3865 | " encode data to JSON 3866 | let str = v->json_encode() 3867 | echo str 3868 | " decode data from JSON 3869 | let x = str->json_decode() 3870 | echo x 3871 | ``` 3872 | 3873 | *Help:* [json_encode()](https://vimhelp.org/builtin.txt.html#json_encode%28%29), [json_decode()](https://vimhelp.org/builtin.txt.html#json_decode%28%29), [js_encode()](https://vimhelp.org/builtin.txt.html#js_encode%28%29), [js_decode()](https://vimhelp.org/builtin.txt.html#js_decode%28%29) 3874 | 3875 | ------------------------------------------------------------------------------ 3876 | 3877 | ## Network Sockets 3878 | 3879 | **Python:** 3880 | ```python 3881 | import requests 3882 | # Get a web page from http://httpbin.org 3883 | def Display_Page(): 3884 | r = requests.get('http://httpbin.org/') 3885 | if r.status_code == requests.codes.ok: 3886 | # display the received header and contents 3887 | print(r.headers) 3888 | print(r.text) 3889 | else: 3890 | print("Error: Failed to open URL") 3891 | Display_Page() 3892 | ``` 3893 | 3894 | **VimScript:** 3895 | ```vim 3896 | let g:rcvd_data = [] 3897 | 3898 | " channel data callback function. Called for every received line. 3899 | func Chan_data_cb(ch, msg) 3900 | call add(g:rcvd_data, a:msg) 3901 | endfunc 3902 | 3903 | " channel close callback function. 3904 | func Chan_close_cb(ch) 3905 | echo g:rcvd_data 3906 | endfunc 3907 | 3908 | func Display_Page() 3909 | let addr = "httpbin.org:80" 3910 | let ch_opt = {} 3911 | " data received is processed one line at a time 3912 | let ch_opt.mode = 'nl' 3913 | let ch_opt.waittime = -1 3914 | let ch_opt.drop = "never" 3915 | let ch_opt.callback = function('Chan_data_cb') 3916 | let ch_opt.close_cb = function('Chan_close_cb') 3917 | " open the channel 3918 | let ch = ch_open(addr, ch_opt) 3919 | if ch_status(ch) != "open" 3920 | echomsg "Failed to open channel, status = " .. ch_status(ch) 3921 | return 3922 | endif 3923 | " send a http request 3924 | call ch_sendraw(ch, "GET / HTTP/1.0\nHost: httpbin.org\n\n") 3925 | endfunc 3926 | 3927 | call Display_Page() 3928 | ``` 3929 | 3930 | *Help:* [job-channel-overview](https://vimhelp.org/channel.txt.html#job-channel-overview), [ch_open()](https://vimhelp.org/channel.txt.html#ch_open%28%29), [ch_status()](https://vimhelp.org/channel.txt.html#ch_status%28%29), [ch_sendraw()](https://vimhelp.org/channel.txt.html#ch_sendraw%28%29), [ch_close()](https://vimhelp.org/channel.txt.html#ch_close%28%29) 3931 | 3932 | ------------------------------------------------------------------------------ 3933 | 3934 | ## Background Processes 3935 | 3936 | ### Starting a background process and communicating with it 3937 | 3938 | The 'bc' calculator utility is used in the below example for illustrative purposes only. 3939 | 3940 | **Python:** 3941 | ```python 3942 | import subprocess 3943 | procObj = subprocess.Popen('bc', 3944 | stdin=subprocess.PIPE, 3945 | stdout=subprocess.PIPE, 3946 | shell=True) 3947 | lines, err = procObj.communicate("12 * 6\n") 3948 | print("Result = " + lines) 3949 | print("Exitcode = " + str(procObj.returncode)) 3950 | ``` 3951 | 3952 | **VimScript:** 3953 | ```vim 3954 | let job = job_start('bc') 3955 | if job_status(job) != "run" 3956 | echo "Failed to start bc" 3957 | else 3958 | let output = ch_evalraw(job, "6 * 12\n") 3959 | echo "Result =" output 3960 | call job_stop(job, "kill") 3961 | let info = job_info(job) 3962 | echo "Exitcode = " info.exitval 3963 | endif 3964 | ``` 3965 | 3966 | *Help:* [job](https://vimhelp.org/channel.txt.html#job), [job_start()](https://vimhelp.org/channel.txt.html#job_start%28%29), [job_status()](https://vimhelp.org/channel.txt.html#job_status%28%29), [job_stop()](https://vimhelp.org/channel.txt.html#job_stop%28%29), [job_info()](https://vimhelp.org/channel.txt.html#job_info%28%29) 3967 | 3968 | ------------------------------------------------------------------------------ 3969 | 3970 | ## Unit Tests 3971 | 3972 | **Python:** 3973 | ```python 3974 | import unittest 3975 | 3976 | class TestDemoMethods(unittest.TestCase): 3977 | def test_abc(self): 3978 | self.assertEqual('FOO'.lower(), 'foo') 3979 | self.assertNotEqual(1, 2) 3980 | self.assertTrue('foo' == 'foo') 3981 | self.assertFalse('FOO' == 'foo') 3982 | self.assertIsNot('foo', 1) 3983 | self.assertRegex('ab123xy', '\d+') 3984 | self.assertNotRegex('abcd', '\d+') 3985 | with self.assertRaises(TypeError): 3986 | 'a:b'.split(2) 3987 | 3988 | unittest.main() 3989 | ``` 3990 | 3991 | **VimScript:** 3992 | ```vim 3993 | let v:errors = [] 3994 | call assert_equal(tolower('FOO'), 'foo') 3995 | call assert_notequal(1, 2) 3996 | call assert_true('foo' == 'foo') 3997 | call assert_false('FOO' == 'foo') 3998 | call assert_fails('let l = split("a:b", [])', 'E730:') 3999 | call assert_match('\d\+', 'ab123xy') 4000 | call assert_notmatch('\d\+', 'abcd') 4001 | if len(v:errors) == 0 4002 | echo "Test passed" 4003 | else 4004 | echo "Test failed: ", v:errors 4005 | endif 4006 | ``` 4007 | 4008 | *Help:* [testing](https://vimhelp.org/testing.txt.html#testing), [v:errors](https://vimhelp.org/eval.txt.html#errors-variable) 4009 | --------------------------------------------------------------------------------