├── FAQ.md ├── LICENSE ├── README.md ├── setup.cfg ├── test.py └── vimode.py /FAQ.md: -------------------------------------------------------------------------------- 1 | # Problematic key bindings 2 | `meta-meta-…` key bindings may conflict with vimode. For example, these 3 | default key bindings are all considered problematic: 4 | 5 | * `meta-jmeta-l` -> `/input jump_last_buffer` 6 | * `meta-jmeta-r` -> `/server raw` 7 | * `meta-jmeta-s` -> `/server jump` 8 | * `meta-wmeta-meta2-A` -> `/window up` 9 | * `meta-wmeta-meta2-B` -> `/window down` 10 | * `meta-wmeta-meta2-C` -> `/window right` 11 | * `meta-wmeta-meta2-D` -> `/window left` 12 | * `meta-wmeta-b` -> `/window balance` 13 | * `meta-wmeta-s` -> `/window swap` 14 | 15 | This only matters after you press Esc. For example: 16 | 17 | * Press `Esc` to switch to Normal mode. 18 | * Press `w` expecting to move the cursor to the next word. 19 | * `Esc-w` is actually detected as `meta-w` by your terminal (and therefore 20 | WeeChat). However, `meta-w` matches the beginning of known keybindings, such 21 | as `meta-wmeta-meta2-A`. This means WeeChat won't report that `meta-w` was 22 | pressed just yet, and will wait for another keystroke to see if that still 23 | matches a known keybinding. 24 | * The result is that vimode won't know you pressed `w`. Once you press another 25 | key (e.g. `w`), it'll then receive a `ww` press and ignore that (since it's 26 | bound to nothing). You'll have to press `w` a third time for vimode to detect 27 | it. 28 | 29 | You have a few choices to solve this: 30 | 31 | * Live with it if you consider it's not important enough. 32 | * Remove the problematic key bindings entirely. 33 | * Rebind the problematic key bindings to something that won't conflict. 34 | 35 | To remove the conflicting key bindings and add recommended key bindings, 36 | you can run the `/vimode bind_keys` command inside WeeChat. To only list 37 | changes, run `/vimode bind_keys --list` instead. 38 | 39 | # Esc key not being detected instantly 40 | This can happen if you're using a terminal multiplexer, such as tmux or screen. 41 | You can decrease (or remove) the time your multiplexer waits to determine 42 | input key sequences to fix this. 43 | 44 | * tmux: set `escape-time` to 0 (e.g. `tmux set-option escape-time 0`, or add 45 | `set -sg escape-time 0` to your `.tmux.conf` file). 46 | * screen: set `maptimeout` to 0 (e.g. `C-a :` followed by `maptimeout 0`, or 47 | add `maptimeout 0` to your `.screenrc`). 48 | 49 | # Exiting insert mode upon sending a message 50 | 51 | If you want to go to normal mode after sending a message, you can rebind the 52 | `` key in WeeChat: 53 | 54 | /key bind ctrl-M /vimode_go_to_normal;/input return 55 | 56 | If you're using a script that rebinds `` like multiline.pl, replace 57 | `/input return` with the appropriate command. To check the current binding, 58 | you can press `Alt-K` followed by `` in WeeChat. 59 | 60 | You'll need to manually rebind `` if you remove weechat-vimode. For 61 | example: 62 | 63 | /key bind ctrl-M /input return 64 | 65 | You can always use `^J` instead of `` if something goes wrong. 66 | 67 | # Custom key mappings examples (in Normal mode) 68 | 69 | To swap the behavior of `J` and `K`, you map one to the other: 70 | ``` 71 | :nmap J K 72 | :nmap K J 73 | ``` 74 | 75 | If you'd like `j`/`k`/`^j`/`^k` to behave like `↑`/`↓`/`^↑`/`^↓`, execute the 76 | following commands: 77 | ``` 78 | :nmap j 79 | :nmap k 80 | :nmap 81 | :nmap 82 | ``` 83 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | {one line to give the program's name and a brief idea of what it does.} 635 | Copyright (C) {year} {name of author} 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | {project} Copyright (C) {year} {fullname} 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Description: 2 | Add vi/vim-like modes and keybindings to WeeChat. 3 | 4 | 5 | # Download: 6 | weechat-vimode is available in the WeeChat scripts repo. You can install it by 7 | running the following command: 8 | 9 | /script install vimode.py 10 | 11 | The version on GitHub may be more recent. You can install it from the shell as 12 | follows: 13 | 14 | cd ~/.weechat/python/ 15 | wget 'https://github.com/GermainZ/weechat-vimode/raw/master/vimode.py' 16 | cd autoload/ 17 | ln -s ../vimode.py . 18 | 19 | If you prefer to clone the git repo (allowing you to easily update it), you can 20 | do the following instead: 21 | 22 | git clone 'https://github.com/GermainZ/weechat-vimode.git' 23 | ln -s /path/to/git/repo/vimode.py ~/.weechat/python/autoload/vimode.py 24 | 25 | If you're using Arch Linux, you can also install 26 | [weechat-vimode-git](https://aur.archlinux.org/packages/weechat-vimode-git/) 27 | from the AUR. 28 | 29 | 30 | # Screencast: 31 | [![weechat-vimode demo by @gotbletu (YouTube)](https://img.youtube.com/vi/tjHEbfwHlR4/0.jpg)](https://www.youtube.com/watch?v=tjHEbfwHlR4) 32 | 33 | # Usage: 34 | To switch to Normal mode, press `Esc` or `Ctrl+Space`. You can also use an 35 | alternate mapping while in Insert mode, similar to `:imap jk ` in vim. 36 | See the `imap_esc` and `imap_esc_timeout` options for more details. 37 | 38 | Three bar items are provided: 39 | 40 | * **mode_indicator**: shows the currently active mode (e.g. `NORMAL`). Has 41 | various customization options (see `/fset vimode.mode_indicator`). 42 | * **vi_buffer**: shows partial commands (e.g. `df`). 43 | * **cmd_completion**: shows completion suggestions for `:commands` (triggered 44 | with ``). 45 | 46 | It is highly recommended you add **mode_indicator** and **vi_buffer** to your 47 | input bar. For example: 48 | 49 | * `/fset weechat.bar.input.items` 50 | * `` or type `s` and press `Enter` 51 | * Add `mode_indicator+` at the start, and `,[vi_buffer]` at the end. 52 | * Final result example: 53 | `"mode_indicator+[input_prompt]+(away),[input_search], 54 | [input_paste],input_text,[vi_buffer]"` 55 | 56 | You can also add **cmd_completion** to the status bar: 57 | 58 | * `/fset weechat.bar.status.items` 59 | * `` or type `s` and press `Enter` 60 | * Add `,cmd_completion` at the end. 61 | * Final result example: 62 | `"[time],[buffer_last_number],[buffer_plugin],buffer_number+:+buffer_name+(buffer_modes)+{buffer_nicklist_count}+buffer_zoom+buffer_filter,scroll,[lag],[hotlist],completion,cmd_completion"` 63 | 64 | To switch back to Insert mode, you can use `i`, `a`, `A`, etc. 65 | 66 | To execute an Ex command, simply precede it with a ":" while in Normal mode, 67 | for example: ":h" or ":s/foo/bar". 68 | 69 | 70 | # Showing line numbers: 71 | The `vi_line_numbers` bar (comes with a bar item) is provided but hidden by 72 | default, and can be shown to display line numbers next to the chat window 73 | (similar to vi's `:set number`). You can show it by using the command: 74 | `/set weechat.bar.vi_line_numbers.hidden off`. 75 | 76 | (Depending on your configuration, you may need to adjust some of its settings 77 | for it to be displayed correctly, but the defaults should suit most users.) 78 | 79 | It is useful for `:` commands, which will start WeeChat's cursor mode and 80 | take you to the appropriate line. You can then use the default key bindings to 81 | quote the message (`Q`, `m` and `q`). 82 | 83 | You can customize the prefix/suffix for each line: `/fset vimode.line_number`. 84 | 85 | 86 | # Enabling vim-like search: 87 | By default, pressing `/` will simply launch WeeChat's search mode. 88 | 89 | Optionally, weechat-vimode can also handle `n`/`N` presses after pressing `/` 90 | and confirming the query. To enable this setting: 91 | `/set plugins.var.python.vimode.search_vim on`. 92 | Note that having this setting enabled will require an extra `` press to 93 | exit search mode (where only `n`/`N` are recognized and handled) and return to 94 | Normal mode. When in search mode, pressing `/` will start a new search. 95 | 96 | 97 | # Current key bindings: 98 | 99 | ## Input line: 100 | 101 | ### Operators: 102 | * `d{motion}` Delete text that **{motion}** moves over. 103 | * `c{motion}` Delete **{motion}** text and start Insert mode. 104 | * `y{motion}` Yank **{motion}** text to clipboard. Uses xclip by default. 105 | You can change this with the `copy\_clipboard\_cmd` option. 106 | 107 | ### Motions: 108 | * `h` **[count]** characters to the left exclusive. 109 | * `l` **[count]** characters to the right exclusive. 110 | * `w` **[count]** words forward exclusive. 111 | * `W` **[count]** WORDS forward exclusive. 112 | * `b` **[count]** words backward. 113 | * `B` **[count]** WORDS backward. 114 | * `ge` Backward to the end of word **[count]** inclusive. 115 | * `gE` Backward to the end of WORD **[count]** inclusive. 116 | * `e` Forward to the end of word **[count]** inclusive. 117 | * `E` Forward to the end of WORD **[count]** inclusive. 118 | * `0` To the first character of the line. 119 | * `^` To the first non-blank character of the line exclusive. 120 | * `$` To the end of the line exclusive. 121 | * `f{char}` To **[count]**'th occurrence of **{char}** to the right. 122 | * `F{char}` To **[count]**'th occurrence of **{char}** to the left. 123 | * `t{char}` Till before **[count]**'th occurrence of **{char}** to the 124 | right. 125 | * `T{char}` Till after **[count]**'th occurrence of **{char}** to the 126 | left. 127 | 128 | ### Other: 129 | * `` **[count]** characters to the right. 130 | * `` **[count]** characters to the left. 131 | * `x` Delete **[count]** characters under and after the cursor. 132 | * `X` Delete **[count]** characters before the cursor. 133 | * `~` Switch case of the character under the cursor. 134 | * `;` Repeat latest f, t, F or T **[count]** times. 135 | * `,` Repeat latest f, t, F or T in opposite direction 136 | **[count]** times. 137 | * `r{char}` Replace **[count]** characters with **{char}** under and 138 | after the cursor. 139 | * `R` Enter Replace mode. Counts are not supported. 140 | * `dd` Delete line. 141 | * `D` Delete the characters under the cursor until the end of the 142 | line. 143 | * `cc` Delete line and start Insert mode. 144 | * `C` Delete from the cursor position to the end of the line, 145 | and start Insert mode. 146 | * `yy` Yank line to clipboard. Uses xclip by default. You can 147 | change this with the `copy\_clipboard\_cmd` option. 148 | * `I` Insert text before the first non-blank in the line. 149 | * `p` Put the text from the clipboard after the cursor. Uses 150 | xclip by default. You can change this with the 151 | `paste\_clipboard\_cmd` option. 152 | * `u` Undo change **[count]** times. 153 | * `^R` Redo change **[count]** times. 154 | * `nt` Scroll nicklist up. 155 | * `nT` Scroll nicklist down. 156 | 157 | ## Buffers: 158 | * `^B` Scroll buffer page up. (use `weechat.look.scroll_page_percent` value) 159 | * `^F` Scroll buffer page down. (use `weechat.look.scroll_page_percent` value) 160 | * `^U` Scroll buffer up. (use `weechat.look.scroll_amount` value) 161 | * `^D` Scroll buffer down. (use `weechat.look.scroll_amount` value) 162 | * `^Y` or `k` Scroll buffer line up. 163 | * `^E` or `j` Scroll buffer line down. 164 | * `gt` or `K` or `H`Go to the previous buffer. 165 | * `gT` or `J` or `L`Go to the next buffer. 166 | * `gg` Goto first line. 167 | * `G` Goto line **[count]**, default last line. 168 | * `/` Launch WeeChat search mode 169 | * `^^` Jump to the last buffer. 170 | 171 | ## Windows: 172 | * `^Wh` Go to the window to the left. 173 | * `^Wj` Go to the window below the current one. 174 | * `^Wk` Go to the window above the current one. 175 | * `^Wl` Go to the window to the right. 176 | * `^W=` Balance windows' sizes. 177 | * `^Wx` Swap window with the next one. 178 | * `^Ws` Split current window in two. 179 | * `^Wv` Split current window in two, but vertically. 180 | * `^Wq` Quit current window. 181 | 182 | 183 | # Current commands: 184 | * `:h`, `:help` Help (`/help`) 185 | * `:set` Set WeeChat config option (`/set`) 186 | * `:q`, `:quit` Closes current buffer (`/close`) 187 | * `:qa`, `:qall`, `:quita`, `:quitall` 188 | Exits WeeChat (`/exit`) 189 | * `:w`, `:write` Saves settings (`/save`) 190 | * `:bp`, `:bprevious` 191 | Go to the previous buffer (`/buffer -1`). 192 | * `:bn`, `:bnext` `:bN` `:bNext` 193 | Go to the next buffer (`/buffer +1`). 194 | * `:bd`, `:bdel`, `:bdelete` 195 | Close the current buffer (`/close`). 196 | * `:b#` Go to the last buffer (`/input jump_last_buffer`). 197 | * `:b [N]`, `:bu [N]`, `:buf [N]`, `:buffer [N]` 198 | Go to buffer `[N]`. 199 | * `:sp`, `:split` Split current window in two (`/window splith`). 200 | * `:vs`, `:vsplit` Split current window in two, but vertically 201 | (`/window splitv`). 202 | * `:!{cmd}` Execute shell command (`/exec -buffer shell`) 203 | * `:s/pattern/repl` 204 | `:s/pattern/repl/g` 205 | Search/Replace \* 206 | * `:` Start cursor mode and go to line. 207 | * `:nmap` List user-defined key mappings. 208 | * `:nmap {lhs} {rhs}` 209 | Map `{lhs}` to `{rhs}` for Normal mode. Some (but not all) vim-like key codes are 210 | supported: ``, ``, ``, ``, `` and ``. These "user 211 | mappings" share much of the flexibility you are accustomed to from using regular 212 | vim mappings. See the [User Mappings](#usermaps) section for details and examples. 213 | * `:nunmap {lhs}` Remove the mapping of `{lhs}` for Normal mode. 214 | * `:command` All other commands will be passed to WeeChat (e.g. 215 | ":script …" is equivalent to "/script …"). 216 | 217 | \* Supports regex (check docs for the Python re module for more 218 | information). `&` in the replacement is also substituted by the pattern. If the 219 | `g` flag isn't present, only the first match will be substituted. 220 | 221 | # User Mappings 222 | User mappings are created using `:nmap {lhs} {rhs}`. The `{rhs}` argument consists of any 223 | combination of the following: 224 | 225 | * A WeeChat command, specified with: `/command [options]`. You may also use a colon (`:`) 226 | in place of the forward slash (`/`) if you wish. 227 | * An INSERT mode action, specified by an `A`, `I`, `i`, or `a` to enter INSERT mode; then an 228 | (optional) arbitrary string of characters to send to the command-line; and then (optionally) ending the 229 | pattern with a `` (to submit the text to the current buffer) or a `` to end the INSERT 230 | mode action and go back to NORMAL mode. 231 | * Keys specifying a vim motion (`h`,`j`,`k`,`l`,`^`,`0`, etc.). 232 | * Keys specifying a vim operation (`dd`, `y$`, `cw`, etc.). 233 | 234 | A count may be specified either in the mapping itself or before triggering the mapping. 235 | Furthermore, you may place the following count tag anywhere (except inside an INSERT action) within 236 | the binding (`{rhs}`): `#{N}`, where `N` is some arbitrary integer. This special "count tag" is used to 237 | consume an external count. If no external count is provided, `N` will be used as the default 238 | count. This will all probably be easier to grasp after seeing a few examples: 239 | 240 | ### Examples 241 | 242 | 1) Commands can be concatenated together: 243 | - INPUT: `:nmap h /cmd1/cmd2` 244 | - OUTPUT [h]: Runs `/cmd1` then `/cmd2`. 245 | 246 | 2) User defined bindings will be followed: 247 | - INPUT: `:nmap j /buffer 5h` 248 | - OUTPUT [j]: Go to the fifth buffer, then run `/cmd1`, and then run `/cmd2`. 249 | 250 | 3) Bindings can take advantage of INSERT mode: 251 | - INPUT: `:nmap k i/msg 0i` 252 | - OUTPUT [k]: Prints "/msg " to the command-line and then returns the user to the beginning of the line. The user is left in INSERT mode. 253 | 254 | 4) Counts are respected both internally and externally: 255 | - INPUT: `:nmap j 3J` 256 | - OUTPUT [j]: Go three buffers down. 257 | - OUTPUT [3j]: Go nine buffers down. 258 | 259 | 5) Special "count tag" gives you more flexibility when using external counts: 260 | - INPUT: `:nmap @ /buffer #{3}` 261 | - OUTPUT [7@]: Go to the seventh buffer. 262 | - OUTPUT [@]: Go to the third buffer. 263 | 264 | # History: 265 | * version 0.1: initial release 266 | * version 0.2: added esc to switch to Normal mode, various key bindings 267 | and commands. 268 | * version 0.2.1: fixes/refactoring 269 | * version 0.3: separate operators from motions and better handling. Added 270 | yank operator, I/p. Other fixes and improvements. The 271 | Escape key should work flawlessly on WeeChat ≥ 0.4.4. 272 | * version 0.4: added: f, F, t, T, r, R, W, E, B, gt, gT, J, K, ge, gE, X, 273 | ~, ,, ;, ^^, ^Wh, ^Wj, ^Wk, ^Wl, ^W=, ^Wx, ^Ws, ^Wv, ^Wq, 274 | :!cmd, :sp, :vsp. 275 | Improved substitutions (:s/foo/bar). Rewrote key handling 276 | logic to take advantage of WeeChat API additions. 277 | Many fixes and improvements. WeeChat ≥ 1.0.0 required. 278 | * version 0.5: added: line numbers bar (disabled by default), : 279 | commands, C, D. Many fixes and improvements. 280 | * version 0.6: added python3 support, `:imap `, 281 | `/vimode_go_to_normal` for use in user-defined key 282 | bindings, nt/nT to scroll nicklist, support for 283 | user-defined commands for copying/pasting, simple 284 | tab-completion for Ex mode. Flipped J/K and gT/gt. Other 285 | bug fixes and improvements. 286 | * version 0.7: added support for user-defined key mappings (`:nmap {lhs} 287 | {rhs}`/`:nunmap {lhs}`), undo history, optional vim-like 288 | search, command-line mode history, and various 289 | customization options (mode indicator colors and 290 | prefix/suffix; line numbers prefix/suffix). 291 | Removed the separate command-line bar (the input bar is now 292 | used instead). 293 | Other bug fixes and improvements. 294 | 295 | For the full change log, please check the [list of commits][1]. 296 | 297 | 298 | # Support: 299 | Please report any issues using the [GitHub issue tracker][2]. Also feel free to 300 | suggest new features that you need. 301 | 302 | You can contact me on irc.freenode.net in #weechat or via a query (nickname: 303 | GermainZ). 304 | 305 | [1]: https://github.com/GermainZ/weechat-vimode/commits/master 306 | [2]: https://github.com/GermainZ/weechat-vimode/issues/new 307 | -------------------------------------------------------------------------------- /setup.cfg: -------------------------------------------------------------------------------- 1 | [flake8] 2 | ignore = E121,E123,E126,E226,E24,E704,W503,W504,E302,E305 3 | -------------------------------------------------------------------------------- /test.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # 3 | # Copyright (C) 2013-2014 Germain Z. 4 | # 5 | # This program is free software; you can redistribute it and/or modify 6 | # it under the terms of the GNU General Public License as published by 7 | # the Free Software Foundation; either version 3 of the License, or 8 | # (at your option) any later version. 9 | # 10 | # This program is distributed in the hope that it will be useful, 11 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 12 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 | # GNU General Public License for more details. 14 | # 15 | # You should have received a copy of the GNU General Public License 16 | # along with this program. If not, see . 17 | # 18 | 19 | """Tests for weechat-vimode. Uses a gvim instance as a server to compare the 20 | behavior of our custom implementation to vim's. 21 | 22 | Note that a full test takes a fair bit of time. 23 | 24 | Usage: 25 | python2 py.test 26 | """ 27 | 28 | 29 | from mock import Mock 30 | import subprocess 31 | import sys 32 | import time 33 | 34 | sys.modules['weechat'] = Mock() 35 | 36 | import vimode 37 | 38 | 39 | SERVER_NAME = "WEECHAT-VIMODE-TEST" 40 | TEST_LINES = [" This is a test! Hello! ", 41 | " !olleH !tset a si sihT ", 42 | # I don't think those are necessary to support in real life 43 | # usage (if the above tests pass), but it would be nice to have 44 | # 100% support if it's possible without writing a parser from 45 | # scratch. 46 | "!?!?#?!#l;l;3l;14l;`4\\!124%*)^)!#^", 47 | "^#!)^)*%421!\\4`;l41;l3;l;l#!?#?!?!", 48 | "^#!)^\")*%421!\\4`;l'1;l3;';l#!?#?!?\"!", 49 | "^#!)^)*%\"4'1!\\4`;l41;l3;l;l#!?\"#'!?!"] 50 | 51 | 52 | def vim_send(keys): 53 | """Send {keys} to vim server.""" 54 | subprocess.Popen(["vim", "--servername", SERVER_NAME, "--remote-send", 55 | keys], stdout=subprocess.PIPE).wait() 56 | 57 | def vim_expr(expr): 58 | """Evaluate {expr} in vim server.""" 59 | subprocess.Popen(["vim", "--servername", SERVER_NAME, "vim", 60 | "--remote-expr", expr], stdout=subprocess.PIPE).wait() 61 | 62 | def vim_get_cur(): 63 | """Get the column of the cursor on the vim server.""" 64 | process = subprocess.Popen(["vim", "--servername", SERVER_NAME, 65 | "--remote-expr", "col('.')"], 66 | stdout=subprocess.PIPE) 67 | out = process.communicate()[0].strip() 68 | return int(out) 69 | 70 | def test_motion(motion_func, motion_keys): 71 | """Compare a custom function's behavior to the vim server's to test it.""" 72 | count = 1 73 | for line in TEST_LINES: 74 | # Clear the buffer and insert our test line. 75 | vim_send("ggdGi{}".format(line)) 76 | print(("• Testing motion \033[33m{}\033[0m with data " 77 | "\033[33m\"{}\"\033[0m…").format(motion_keys, line)) 78 | # Check the behavior of our function for each possible cursor position. 79 | for cur in range(0, len(line)): 80 | # Get the cursor position, as returned by our function. 81 | got, _, catching = motion_func(line, cur, count) 82 | # Out of bound positions are corrected anyway, so we don't mind 83 | # those inaccuracies. 84 | got = max(1, min(len(line), got + 1)) 85 | # If it's a catching motion (e.g. "f"), it's not done yet. 86 | if catching: 87 | vimode.catching_keys_data['keys'] = "a" 88 | vimode.catching_keys_data['amount'] = 0 89 | callback = vimode.catching_keys_data['callback'] 90 | getattr(vimode, callback)() 91 | got, _, _ = motion_func(line, cur, count) 92 | got = max(1, min(len(line), cur + 1 if got == -1 else got + 1)) 93 | 94 | # Set the cursor's position on the vim server. 95 | vim_expr("setpos('.', [0, 1, {}, 0])".format(cur + 1)) 96 | # Do the motion on the vim server. 97 | vim_send(motion_keys) 98 | # Complete the motion if it's catching (e.g. "f"). 99 | if catching: 100 | vim_send("a") 101 | # Get the cursor's position on the vim server. 102 | expected = vim_get_cur() 103 | # Print errors, if any. 104 | if got != expected: 105 | print(" cur: {}, count: {}: \033[31m{} ≠ {}\033[0m".format( 106 | cur, count, got, expected)) 107 | 108 | 109 | # Start a vim server (we use gvim because it forks directly). 110 | SERVERS = subprocess.Popen(["gvim", "--serverlist"], stdout=subprocess.PIPE).communicate()[0] 111 | if not (SERVERS and SERVER_NAME in SERVERS.split()): 112 | subprocess.Popen(["gvim", "--servername", SERVER_NAME]).wait() 113 | time.sleep(0.5) # To make sure it's completely ready. 114 | 115 | # Test each of weechat-vimode's custom motion implementations. 116 | for motion in vimode.VI_MOTIONS: 117 | # Get the function's name (special characters need to be replaced; for 118 | # example, "^"'s function is called "motion_carret" and not "motion_^"). 119 | if motion in vimode.SPECIAL_CHARS: 120 | func = "motion_{}".format(vimode.SPECIAL_CHARS[motion]) 121 | else: 122 | func = "motion_{}".format(motion) 123 | # Test it! 124 | test_motion(getattr(vimode, func), motion) 125 | 126 | # Exit the vim server. 127 | vim_send("ZQ") 128 | -------------------------------------------------------------------------------- /vimode.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # 3 | # Copyright (C) 2013-2014 Germain Z. 4 | # 5 | # This program is free software; you can redistribute it and/or modify 6 | # it under the terms of the GNU General Public License as published by 7 | # the Free Software Foundation; either version 3 of the License, or 8 | # (at your option) any later version. 9 | # 10 | # This program is distributed in the hope that it will be useful, 11 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 12 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 | # GNU General Public License for more details. 14 | # 15 | # You should have received a copy of the GNU General Public License 16 | # along with this program. If not, see . 17 | # 18 | 19 | # 20 | # Add vi/vim-like modes to WeeChat. 21 | # 22 | 23 | 24 | from abc import ABCMeta, abstractproperty 25 | from contextlib import contextmanager 26 | import csv 27 | import enum 28 | import functools 29 | import json 30 | import os 31 | import re 32 | import subprocess 33 | try: 34 | from StringIO import StringIO 35 | except ImportError: 36 | from io import StringIO 37 | import sys 38 | import time 39 | 40 | import weechat 41 | 42 | 43 | # Script info. 44 | # ============ 45 | 46 | SCRIPT_NAME = "vimode" 47 | SCRIPT_AUTHOR = "GermainZ " 48 | SCRIPT_VERSION = "0.8" 49 | SCRIPT_LICENSE = "GPL3" 50 | SCRIPT_DESC = ("Add vi/vim-like modes and keybindings to WeeChat.") 51 | 52 | 53 | # Global variables. 54 | # ================= 55 | 56 | # General. 57 | # -------- 58 | 59 | # Halp! Halp! Halp! 60 | GITHUB_BASE = "https://github.com/GermainZ/weechat-vimode/blob/master/" 61 | README_URL = GITHUB_BASE + "README.md" 62 | FAQ_KEYBINDINGS = GITHUB_BASE + "FAQ.md#problematic-key-bindings" 63 | FAQ_ESC = GITHUB_BASE + "FAQ.md#esc-key-not-being-detected-instantly" 64 | 65 | # Holds the text of the tab-completions for the command-line mode. 66 | cmd_compl_text = "" 67 | # Holds the original text of the command-line mode, used for completion. 68 | cmd_text_orig = None 69 | # Index of current suggestion, used for completion. 70 | cmd_compl_pos = 0 71 | # Used for command-line mode history. 72 | cmd_history = [] 73 | cmd_history_index = 0 74 | # Used to store the content of the input line when going into COMMAND mode. 75 | input_line_backup = {} 76 | # Mode we're in. One of INSERT, NORMAL, REPLACE, COMMAND or SEARCH. 77 | # SEARCH is only used if search_vim is enabled. 78 | mode = "INSERT" 79 | # Holds normal commands (e.g. "dd"). 80 | vi_buffer = "" 81 | # See `cb_key_combo_default()`. 82 | esc_pressed = 0 83 | # See `cb_key_pressed()`. 84 | last_signal_time = 0 85 | # See `start_catching_keys()` for more info. 86 | catching_keys_data = {'amount': 0} 87 | # Used for ; and , to store the last f/F/t/T motion. 88 | last_search_motion = {'motion': None, 'data': None} 89 | # Used for undo history. 90 | undo_history = {} 91 | undo_history_index = {} 92 | # Holds mode colors (loaded from vimode_settings). 93 | mode_colors = {} 94 | 95 | # Script options. 96 | vimode_settings = { 97 | 'no_warn': ("off", ("don't warn about problematic keybindings and " 98 | "tmux/screen")), 99 | 'copy_clipboard_cmd': ("xclip -selection c", 100 | ("command used to copy to clipboard; must read " 101 | "input from stdin")), 102 | 'paste_clipboard_cmd': ("xclip -selection c -o", 103 | ("command used to paste clipboard; must output " 104 | "content to stdout")), 105 | 'imap_esc': ("", ("use alternate mapping to enter Normal mode while in " 106 | "Insert mode; having it set to 'jk' is similar to " 107 | "`:imap jk ` in vim")), 108 | 'user_command_mapping': (":", ("user alternate mapping to enter Command mode while in " 109 | "Normal mode")), 110 | 'imap_esc_timeout': ("1000", ("time in ms to wait for the imap_esc " 111 | "sequence to complete")), 112 | 'search_vim': ("off", ("allow n/N usage after searching (requires an extra" 113 | " to return to normal mode)")), 114 | 'user_mappings': ("", ("see the `:nmap` command in the README for more " 115 | "info; please do not modify this field manually " 116 | "unless you know what you're doing")), 117 | 'user_mappings_noremap': ("", ("see the `:nnoremap` command in the README " 118 | "for more info; please do not modify this field " 119 | "manually unless you know what you're doing")), 120 | 'mode_indicator_prefix': ("", "prefix for the bar item mode_indicator"), 121 | 'mode_indicator_suffix': ("", "suffix for the bar item mode_indicator"), 122 | 'mode_indicator_normal_color': ("white", 123 | "color for mode indicator in Normal mode"), 124 | 'mode_indicator_normal_color_bg': ("gray", 125 | ("background color for mode indicator " 126 | "in Normal mode")), 127 | 'mode_indicator_insert_color': ("white", 128 | "color for mode indicator in Insert mode"), 129 | 'mode_indicator_insert_color_bg': ("blue", 130 | ("background color for mode indicator " 131 | "in Insert mode")), 132 | 'mode_indicator_replace_color': ("white", 133 | ("color for mode indicator in Replace " 134 | "mode")), 135 | 'mode_indicator_replace_color_bg': ("red", 136 | ("background color for mode indicator " 137 | "in Replace mode")), 138 | 'mode_indicator_cmd_color': ("white", 139 | "color for mode indicator in Command mode"), 140 | 'mode_indicator_cmd_color_bg': ("cyan", 141 | ("background color for mode indicator in " 142 | "Command mode")), 143 | 'mode_indicator_search_color': ("white", 144 | "color for mode indicator in Search mode"), 145 | 'mode_indicator_search_color_bg': ("magenta", 146 | ("background color for mode indicator " 147 | "in Search mode")), 148 | 'line_number_prefix': ("", "prefix for line numbers"), 149 | 'line_number_suffix': (" ", "suffix for line numbers"), 150 | 'is_keyword': ("a-zA-Z0-9_À-ÿ", "characters recognized as part of a word") 151 | } 152 | 153 | 154 | # Regex patterns. 155 | # --------------- 156 | 157 | WHITESPACE = re.compile(r"\s") 158 | REGEX_MOTION_UPPERCASE_W = re.compile(r"(?<=\s)\S") 159 | REGEX_MOTION_UPPERCASE_E = re.compile(r"\S(?!\S)") 160 | REGEX_MOTION_UPPERCASE_B = REGEX_MOTION_UPPERCASE_E 161 | REGEX_MOTION_G_UPPERCASE_E = REGEX_MOTION_UPPERCASE_W 162 | REGEX_MOTION_CARRET = re.compile(r"\S") 163 | REGEX_INT = r"[0-9]" 164 | keyword_regexes = {} # Loaded on runtime (uses the is_keyword config option). 165 | REGEX_MAP_KEYS_1 = { 166 | re.compile("<([^>]*-)Left>", re.IGNORECASE): '<\\1\x01[[D>', 167 | re.compile("<([^>]*-)Right>", re.IGNORECASE): '<\\1\x01[[C>', 168 | re.compile("<([^>]*-)Up>", re.IGNORECASE): '<\\1\x01[[A>', 169 | re.compile("<([^>]*-)Down>", re.IGNORECASE): '<\\1\x01[[B>', 170 | re.compile("", re.IGNORECASE): '\x01[[D', 171 | re.compile("", re.IGNORECASE): '\x01[[C', 172 | re.compile("", re.IGNORECASE): '\x01[[A', 173 | re.compile("", re.IGNORECASE): '\x01[[B' 174 | } 175 | REGEX_MAP_KEYS_2 = { 176 | # Python's regex doesn't support \U1, but we're using a simple hack when 177 | # replacing to fix this. 178 | re.compile(r"]*)>", re.IGNORECASE): '\x01\\U1', 179 | re.compile(r"]*)>", re.IGNORECASE): '\x01[\\1' 180 | } 181 | 182 | # Regex used to detect problematic keybindings. 183 | # For example: meta-wmeta-s is bound by default to ``/window swap``. 184 | # If the user pressed Esc-w, WeeChat will detect it as meta-w and will not 185 | # send any signal to `cb_key_combo_default()` just yet, since it's the 186 | # beginning of a known key combo. 187 | # Instead, `cb_key_combo_default()` will receive the Esc-ws signal, which 188 | # becomes "ws" after removing the Esc part, and won't know how to handle it. 189 | REGEX_PROBLEMATIC_KEYBINDINGS = re.compile(r"meta-\w(meta|ctrl)") 190 | 191 | class Mapping(enum.Enum): 192 | RECURSIVE = "user_mappings" 193 | NON_RECURSIVE = "user_mappings_noremap" 194 | 195 | # Vi commands. 196 | # ------------ 197 | 198 | def add_mapping(args, which): 199 | """Add a user-defined key mapping. 200 | 201 | `which` is a Mapping type, either Mapping.RECURSIVE for `:nmap` or 202 | Mapping.NON_RECURSIVE for `:nnoremap`). 203 | 204 | Some (but not all) vim-like key codes are supported to simplify things for 205 | the user: , , , , and . 206 | 207 | See Also: 208 | `cmd_unmap()`. 209 | """ 210 | args = args.lstrip() 211 | if not args: 212 | mappings = vimode_settings[which.value] 213 | if mappings: 214 | cmd = ':nnoremap' if which == Mapping.NON_RECURSIVE else ':nmap' 215 | title = "----- Vimode User Mappings ({}) -----".format(cmd) 216 | bar = '-' * len(title) 217 | 218 | weechat.prnt("", bar) 219 | weechat.prnt("", title) 220 | weechat.prnt("", bar) 221 | for keys, mapping in sorted(mappings.items(), 222 | key=lambda x: x[0].lower()): 223 | pretty_keys = keys 224 | for pttrn, repl in [(r'\u0001([A-Z])', r''), 225 | (r'\u0001\[([A-Z])', r''), 226 | (r'\u0001\[\[A', r''), 227 | (r'\u0001\[\[B', r''), 228 | (r'\u0001\[\[C', r''), 229 | (r'\u0001\[\[D', r''), 230 | ('"', '\\"')]: 231 | pretty_keys = re.sub(pttrn, repl, pretty_keys) 232 | 233 | pretty_mapping = mapping 234 | for pttrn, repl in [('"', '\\"')]: 235 | pretty_mapping = re.sub(pttrn, repl, pretty_mapping) 236 | 237 | msg_fmt = '("{}", "{}")' 238 | weechat.prnt("", msg_fmt.format(pretty_keys, pretty_mapping)) 239 | else: 240 | weechat.prnt("", "nmap: no mapping found.") 241 | elif " " not in args: 242 | weechat.prnt("", "nmap syntax -> :nmap {lhs} {rhs}") 243 | else: 244 | key, mapping = args.split(" ", 1) 245 | # First pass of replacements. We perform two passes as a simple way to 246 | # avoid incorrect replacements due to dictionaries not being 247 | # insertion-ordered prior to Python 3.7. 248 | for regex, repl in REGEX_MAP_KEYS_1.items(): 249 | key = regex.sub(repl, key) 250 | mapping = regex.sub(repl, mapping) 251 | # Second pass of replacements. 252 | for regex, repl in REGEX_MAP_KEYS_2.items(): 253 | if '\\U' in repl: # Hack, but works well for our simple case. 254 | repl = repl.replace('\\U', '\\') 255 | key = regex.sub(lambda pat: pat.expand(repl).lower(), key) 256 | else: 257 | key = regex.sub(repl, key) 258 | mapping = regex.sub(repl, mapping) 259 | vimode_settings[which.value][key] = mapping 260 | weechat.config_set_plugin(which.value, json.dumps(vimode_settings[which.value])) 261 | 262 | def cmd_nmap(args): 263 | """Add a user-defined key mapping.""" 264 | add_mapping(args, Mapping.RECURSIVE) 265 | 266 | def cmd_nnoremap(args): 267 | """Add a user-defined key mapping, without following user mappings.""" 268 | add_mapping(args, Mapping.NON_RECURSIVE) 269 | 270 | def cmd_nunmap(args): 271 | """Remove a user-defined key mapping. 272 | 273 | See Also: 274 | `cmd_map()`. 275 | """ 276 | args = args.strip() 277 | if not args: 278 | weechat.prnt("", "nunmap syntax -> :unmap {lhs}") 279 | else: 280 | key = args 281 | for regex, repl in REGEX_MAP_KEYS_1.items(): 282 | key = regex.sub(repl, key) 283 | for regex, repl in REGEX_MAP_KEYS_2.items(): 284 | if '\\U' in repl: # Hack, but works well for our simple case. 285 | repl = repl.replace('\\U', '\\') 286 | key = regex.sub(lambda pat: pat.expand(repl).upper(), key) 287 | else: 288 | key = regex.sub(repl, key) 289 | found = False 290 | for setting in ['user_mappings', 'user_mappings_noremap']: 291 | mappings = vimode_settings[setting] 292 | if key in mappings: 293 | found = True 294 | del mappings[key] 295 | del VI_KEYS[key] 296 | 297 | # restore default keys 298 | if key in VI_DEFAULT_KEYS: 299 | VI_KEYS[key] = VI_DEFAULT_KEYS[key] 300 | 301 | weechat.config_set_plugin(setting, json.dumps(mappings)) 302 | vimode_settings[setting] = mappings 303 | if not found: 304 | weechat.prnt("", "nunmap: No such mapping") 305 | 306 | # See Also: `cb_exec_cmd()`. 307 | VI_COMMAND_GROUPS = {('h', 'help'): "/help", 308 | ('qa', 'qall', 'quita', 'quitall'): "/exit", 309 | ('q', 'quit'): "/close", 310 | ('w', 'write'): "/save", 311 | ('bN', 'bNext', 'bp', 'bprevious'): "/buffer -1", 312 | ('bn', 'bnext'): "/buffer +1", 313 | ('bd', 'bdel', 'bdelete'): "/close", 314 | ('b#',): "/input jump_last_buffer_displayed", 315 | ('b', 'bu', 'buf', 'buffer'): "/buffer", 316 | ('sp', 'split'): "/window splith", 317 | ('vs', 'vsplit'): "/window splitv", 318 | ('nm', 'nmap'): cmd_nmap, 319 | ('nn', 'nnoremap'): cmd_nnoremap, 320 | ('nun', 'nunmap'): cmd_nunmap} 321 | 322 | VI_COMMANDS = dict() 323 | for T, v in VI_COMMAND_GROUPS.items(): 324 | VI_COMMANDS.update(dict.fromkeys(T, v)) 325 | 326 | 327 | # Vi operators. 328 | # ------------- 329 | 330 | # Each operator must have a corresponding function, called "operator_X" where 331 | # X is the operator. For example: `operator_c()`. 332 | VI_OPERATORS = ["c", "d", "y"] 333 | 334 | 335 | # Vi motions. 336 | # ----------- 337 | 338 | # Vi motions. Each motion must have a corresponding function, called 339 | # "motion_X" where X is the motion (e.g. `motion_w()`). 340 | # See Also: `SPECIAL_CHARS`. 341 | VI_MOTIONS = ["w", "e", "b", "^", "$", "h", "l", "W", "E", "B", "f", "F", "t", 342 | "T", "ge", "gE", "0", "iw"] 343 | 344 | # Special characters for motions. The corresponding function's name is 345 | # converted before calling. For example, "^" will call `motion_carret` instead 346 | # of `motion_^` (which isn't allowed because of illegal characters). 347 | SPECIAL_CHARS = {'^': "carret", 348 | '$': "dollar"} 349 | 350 | 351 | # Methods for vi operators, motions and key bindings. 352 | # =================================================== 353 | 354 | # Documented base examples: 355 | # ------------------------- 356 | 357 | def operator_base(buf, input_line, pos1, pos2, overwrite): 358 | """Operator method example. 359 | 360 | Args: 361 | buf (str): pointer to the current WeeChat buffer. 362 | input_line (str): the content of the input line. 363 | pos1 (int): the starting position of the motion. 364 | pos2 (int): the ending position of the motion. 365 | overwrite (bool, optional): whether the character at the cursor's new 366 | position should be overwritten or not (for inclusive motions). 367 | Defaults to False. 368 | 369 | Notes: 370 | Should be called "operator_X", where X is the operator, and defined in 371 | `VI_OPERATORS`. 372 | Must perform actions (e.g. modifying the input line) on its own, 373 | using the WeeChat API. 374 | 375 | See Also: 376 | For additional examples, see `operator_d()` and 377 | `operator_y()`. 378 | """ 379 | # Get start and end positions. 380 | start = min(pos1, pos2) 381 | end = max(pos1, pos2) 382 | # Print the text the operator should go over. 383 | weechat.prnt("", "Selection: %s" % input_line[start:end]) 384 | 385 | def motion_base(input_line, cur, count): 386 | """Motion method example. 387 | 388 | Args: 389 | input_line (str): the content of the input line. 390 | cur (int): the position of the cursor. 391 | count (int): the amount of times to multiply or iterate the action. 392 | 393 | Returns: 394 | A tuple containing four values: 395 | int: the starting position of the selection. Usually the cursor's 396 | position. 397 | int: the ending position of the motion. 398 | bool: True if the motion is inclusive, False otherwise. 399 | bool: True if the motion is catching, False otherwise. 400 | See `start_catching_keys()` for more info on catching motions. 401 | 402 | Notes: 403 | Should be called "motion_X", where X is the motion, and defined in 404 | `VI_MOTIONS`. 405 | Must not modify the input line directly. 406 | 407 | See Also: 408 | For additional examples, see `motion_w()` (normal motion) and 409 | `motion_f()` (catching motion). 410 | """ 411 | # Find (relative to cur) position of next number. 412 | pos = get_pos(input_line, REGEX_INT, cur, True, count) 413 | # Return the new (absolute) cursor position. 414 | # This motion is exclusive, so overwrite is False. 415 | return cur, cur + pos, False, False 416 | 417 | def key_base(buf, input_line, cur, count): 418 | """Key method example. 419 | 420 | Args: 421 | buf (str): pointer to the current WeeChat buffer. 422 | input_line (str): the content of the input line. 423 | cur (int): the position of the cursor. 424 | count (int): the amount of times to multiply or iterate the action. 425 | 426 | Notes: 427 | Should be called `key_X`, where X represents the key(s), and defined 428 | in `VI_KEYS`. 429 | Must perform actions on its own (using the WeeChat API). 430 | 431 | See Also: 432 | For additional examples, see `key_a()` (normal key) and 433 | `key_r()` (catching key). 434 | """ 435 | # Key was pressed. Go to Insert mode (similar to "i"). 436 | set_mode("INSERT") 437 | 438 | 439 | # Operators: 440 | # ---------- 441 | 442 | def operator_d(buf, input_line, pos1, pos2, overwrite=False): 443 | """Delete text from `pos1` to `pos2` from the input line. 444 | 445 | If `overwrite` is set to True, the character at the cursor's new position 446 | is removed as well (the motion is inclusive). 447 | 448 | See Also: 449 | `operator_base()`. 450 | """ 451 | start = min(pos1, pos2) 452 | end = max(pos1, pos2) 453 | if overwrite: 454 | end += 1 455 | input_line = list(input_line) 456 | del input_line[start:end] 457 | input_line = "".join(input_line) 458 | weechat.buffer_set(buf, "input", input_line) 459 | set_cur(buf, input_line, pos2) 460 | 461 | def operator_c(buf, input_line, pos1, pos2, overwrite=False): 462 | """Delete text from `pos1` to `pos2` from the input and enter Insert mode. 463 | 464 | If `overwrite` is set to True, the character at the cursor's new position 465 | is removed as well (the motion is inclusive.) 466 | 467 | See Also: 468 | `operator_base()`. 469 | """ 470 | operator_d(buf, input_line, pos1, pos2, overwrite) 471 | set_mode("INSERT") 472 | set_cur(buf, input_line, pos1) 473 | 474 | def operator_y(buf, input_line, pos1, pos2, _): 475 | """Yank text from `pos1` to `pos2` from the input line. 476 | 477 | See Also: 478 | `operator_base()`. 479 | """ 480 | start = min(pos1, pos2) 481 | end = max(pos1, pos2) 482 | cmd = vimode_settings['copy_clipboard_cmd'] 483 | proc = subprocess.Popen(cmd, shell=True, stdin=subprocess.PIPE) 484 | if sys.version_info > (3,): 485 | proc.communicate(input=input_line[start:end].encode()) 486 | else: 487 | proc.communicate(input=input_line[start:end]) 488 | 489 | 490 | # Motions: 491 | # -------- 492 | 493 | def motion_0(input_line, cur, count): 494 | """Go to the first character of the line. 495 | 496 | See Also; 497 | `motion_base()`. 498 | """ 499 | return cur, 0, False, False 500 | 501 | def motion_w(input_line, cur, count): 502 | """Go `count` words forward and return position. 503 | 504 | See Also: 505 | `motion_base()`. 506 | """ 507 | pos = get_pos(input_line, keyword_regexes['w'], cur, True, count) 508 | if pos == -1: 509 | return cur, len(input_line), False, False 510 | return cur, cur + pos, False, False 511 | 512 | def motion_W(input_line, cur, count): 513 | """Go `count` WORDS forward and return position. 514 | 515 | See Also: 516 | `motion_base()`. 517 | """ 518 | pos = get_pos(input_line, REGEX_MOTION_UPPERCASE_W, cur, True, count) 519 | if pos == -1: 520 | return cur, len(input_line), False, False 521 | return cur, cur + pos, False, False 522 | 523 | def motion_e(input_line, cur, count): 524 | """Go to the end of `count` words and return position. 525 | 526 | See Also: 527 | `motion_base()`. 528 | """ 529 | pos = get_pos(input_line, keyword_regexes['e'], cur, True, count) 530 | if pos == -1: 531 | return cur, len(input_line), True, False 532 | return cur, cur + pos, True, False 533 | 534 | def motion_E(input_line, cur, count): 535 | """Go to the end of `count` WORDS and return cusor position. 536 | 537 | See Also: 538 | `motion_base()`. 539 | """ 540 | pos = get_pos(input_line, REGEX_MOTION_UPPERCASE_E, cur, True, count) 541 | if pos == -1: 542 | return cur, len(input_line), False, False 543 | return cur, cur + pos, True, False 544 | 545 | def motion_b(input_line, cur, count): 546 | """Go `count` words backwards and return position. 547 | 548 | See Also: 549 | `motion_base()`. 550 | """ 551 | # "b" is just "e" on inverted data (e.g. "olleH" instead of "Hello"). 552 | pos_inv = motion_e(input_line[::-1], len(input_line) - cur - 1, count)[1] 553 | pos = len(input_line) - pos_inv - 1 554 | return cur, max(0, pos), True, False 555 | 556 | def motion_B(input_line, cur, count): 557 | """Go `count` WORDS backwards and return position. 558 | 559 | See Also: 560 | `motion_base()`. 561 | """ 562 | new_cur = len(input_line) - cur 563 | pos = get_pos(input_line[::-1], REGEX_MOTION_UPPERCASE_B, new_cur, 564 | count=count) 565 | if pos == -1: 566 | return cur, 0, False, False 567 | pos = len(input_line) - (pos + new_cur + 1) 568 | return cur, pos, True, False 569 | 570 | def motion_ge(input_line, cur, count): 571 | """Go to end of `count` words backwards and return position. 572 | 573 | See Also: 574 | `motion_base()`. 575 | """ 576 | # "ge is just "w" on inverted data (e.g. "olleH" instead of "Hello"). 577 | pos_inv = motion_w(input_line[::-1], len(input_line) - cur - 1, count)[1] 578 | pos = len(input_line) - pos_inv - 1 579 | return cur, pos, True, False 580 | 581 | def motion_gE(input_line, cur, count): 582 | """Go to end of `count` WORDS backwards and return position. 583 | 584 | See Also: 585 | `motion_base()`. 586 | """ 587 | new_cur = len(input_line) - cur - 1 588 | pos = get_pos(input_line[::-1], REGEX_MOTION_G_UPPERCASE_E, new_cur, 589 | True, count) 590 | if pos == -1: 591 | return cur, 0, False, False 592 | pos = len(input_line) - (pos + new_cur + 1) 593 | return cur, pos, True, False 594 | 595 | def motion_h(input_line, cur, count): 596 | """Go `count` characters to the left and return position. 597 | 598 | See Also: 599 | `motion_base()`. 600 | """ 601 | return cur, max(0, cur - max(count, 1)), False, False 602 | 603 | def motion_l(input_line, cur, count): 604 | """Go `count` characters to the right and return position. 605 | 606 | See Also: 607 | `motion_base()`. 608 | """ 609 | return cur, cur + max(count, 1), False, False 610 | 611 | def motion_carret(input_line, cur, count): 612 | """Go to first non-blank character of line and return position. 613 | 614 | See Also: 615 | `motion_base()`. 616 | """ 617 | pos = get_pos(input_line, REGEX_MOTION_CARRET, 0) 618 | return cur, pos, False, False 619 | 620 | def motion_dollar(input_line, cur, count): 621 | """Go to end of line and return position. 622 | 623 | See Also: 624 | `motion_base()`. 625 | """ 626 | pos = len(input_line) 627 | return cur, pos, False, False 628 | 629 | def motion_iw(input_line, cur, count): 630 | """Select `count` inner words, returning starting/ending positions. 631 | 632 | See Also: 633 | `motion_base()`. 634 | """ 635 | pos_inv = get_pos(input_line[::-1], keyword_regexes['iw'], 636 | len(input_line) - cur - 1, False, 1) 637 | start_pos = cur - pos_inv 638 | end_pos = start_pos + get_pos(input_line, keyword_regexes['iw'], 639 | start_pos, False, count) 640 | return start_pos, end_pos, True, False 641 | 642 | def motion_f(input_line, cur, count): 643 | """Go to `count`'th occurence of character and return position. 644 | 645 | See Also: 646 | `motion_base()`. 647 | """ 648 | return start_catching_keys(1, "cb_motion_f", input_line, cur, count) 649 | 650 | def cb_motion_f(update_last=True): 651 | """Callback for `motion_f()`. 652 | 653 | Args: 654 | update_last (bool, optional): should `last_search_motion` be updated? 655 | Set to False when calling from `key_semicolon()` or `key_comma()` 656 | so that the last search motion isn't overwritten. 657 | Defaults to True. 658 | 659 | See Also: 660 | `start_catching_keys()`. 661 | """ 662 | global last_search_motion 663 | pattern = catching_keys_data['keys'] 664 | pos = get_pos(catching_keys_data['input_line'], re.escape(pattern), 665 | catching_keys_data['cur'], True, 666 | catching_keys_data['count']) 667 | catching_keys_data['new_cur'] = max(0, pos) + catching_keys_data['cur'] 668 | if update_last: 669 | last_search_motion = {'motion': "f", 'data': pattern} 670 | cb_key_combo_default(None, None, "") 671 | 672 | def motion_F(input_line, cur, count): 673 | """Go to `count`'th occurence of char to the right and return position. 674 | 675 | See Also: 676 | `motion_base()`. 677 | """ 678 | return start_catching_keys(1, "cb_motion_F", input_line, cur, count) 679 | 680 | def cb_motion_F(update_last=True): 681 | """Callback for `motion_F()`. 682 | 683 | Args: 684 | update_last (bool, optional): should `last_search_motion` be updated? 685 | Set to False when calling from `key_semicolon()` or `key_comma()` 686 | so that the last search motion isn't overwritten. 687 | Defaults to True. 688 | 689 | See Also: 690 | `start_catching_keys()`. 691 | """ 692 | global last_search_motion 693 | pattern = catching_keys_data['keys'] 694 | cur = len(catching_keys_data['input_line']) - catching_keys_data['cur'] 695 | pos = get_pos(catching_keys_data['input_line'][::-1], 696 | re.escape(pattern), 697 | cur, 698 | False, 699 | catching_keys_data['count']) 700 | catching_keys_data['new_cur'] = catching_keys_data['cur'] - max(0, pos + 1) 701 | if update_last: 702 | last_search_motion = {'motion': "F", 'data': pattern} 703 | cb_key_combo_default(None, None, "") 704 | 705 | def motion_t(input_line, cur, count): 706 | """Go to `count`'th occurence of char and return position. 707 | 708 | The position returned is the position of the character to the left of char. 709 | 710 | See Also: 711 | `motion_base()`. 712 | """ 713 | return start_catching_keys(1, "cb_motion_t", input_line, cur, count) 714 | 715 | def cb_motion_t(update_last=True): 716 | """Callback for `motion_t()`. 717 | 718 | Args: 719 | update_last (bool, optional): should `last_search_motion` be updated? 720 | Set to False when calling from `key_semicolon()` or `key_comma()` 721 | so that the last search motion isn't overwritten. 722 | Defaults to True. 723 | 724 | See Also: 725 | `start_catching_keys()`. 726 | """ 727 | global last_search_motion 728 | pattern = catching_keys_data['keys'] 729 | pos = get_pos(catching_keys_data['input_line'], re.escape(pattern), 730 | catching_keys_data['cur'] + 1, 731 | True, catching_keys_data['count']) 732 | pos += 1 733 | if pos > 0: 734 | catching_keys_data['new_cur'] = pos + catching_keys_data['cur'] - 1 735 | else: 736 | catching_keys_data['new_cur'] = catching_keys_data['cur'] 737 | if update_last: 738 | last_search_motion = {'motion': "t", 'data': pattern} 739 | cb_key_combo_default(None, None, "") 740 | 741 | def motion_T(input_line, cur, count): 742 | """Go to `count`'th occurence of char to the left and return position. 743 | 744 | The position returned is the position of the character to the right of 745 | char. 746 | 747 | See Also: 748 | `motion_base()`. 749 | """ 750 | return start_catching_keys(1, "cb_motion_T", input_line, cur, count) 751 | 752 | def cb_motion_T(update_last=True): 753 | """Callback for `motion_T()`. 754 | 755 | Args: 756 | update_last (bool, optional): should `last_search_motion` be updated? 757 | Set to False when calling from `key_semicolon()` or `key_comma()` 758 | so that the last search motion isn't overwritten. 759 | Defaults to True. 760 | 761 | See Also: 762 | `start_catching_keys()`. 763 | """ 764 | global last_search_motion 765 | pattern = catching_keys_data['keys'] 766 | pos = get_pos(catching_keys_data['input_line'][::-1], re.escape(pattern), 767 | (len(catching_keys_data['input_line']) - 768 | (catching_keys_data['cur'] + 1)) + 1, 769 | True, catching_keys_data['count']) 770 | pos += 1 771 | if pos > 0: 772 | catching_keys_data['new_cur'] = catching_keys_data['cur'] - pos + 1 773 | else: 774 | catching_keys_data['new_cur'] = catching_keys_data['cur'] 775 | if update_last: 776 | last_search_motion = {'motion': "T", 'data': pattern} 777 | cb_key_combo_default(None, None, "") 778 | 779 | 780 | # Keys: 781 | # ----- 782 | 783 | def key_cc(buf, input_line, cur, count): 784 | """Delete line and start Insert mode. 785 | 786 | See Also: 787 | `key_base()`. 788 | """ 789 | weechat.command("", "/input delete_line") 790 | set_mode("INSERT") 791 | 792 | def key_C(buf, input_line, cur, count): 793 | """Delete from cursor to end of line and start Insert mode. 794 | 795 | See Also: 796 | `key_base()`. 797 | """ 798 | weechat.command("", "/input delete_end_of_line") 799 | set_mode("INSERT") 800 | 801 | def key_yy(buf, input_line, cur, count): 802 | """Yank line. 803 | 804 | See Also: 805 | `key_base()`. 806 | """ 807 | cmd = vimode_settings['copy_clipboard_cmd'] 808 | proc = subprocess.Popen(cmd, shell=True, stdin=subprocess.PIPE) 809 | if sys.version_info > (3,): 810 | proc.communicate(input=input_line.encode()) 811 | else: 812 | proc.communicate(input=input_line) 813 | 814 | def key_p(buf, input_line, cur, count): 815 | """Paste text. 816 | 817 | See Also: 818 | `key_base()`. 819 | """ 820 | cmd = vimode_settings['paste_clipboard_cmd'] 821 | weechat.hook_process(cmd, 10 * 1000, "cb_key_p", weechat.current_buffer()) 822 | 823 | def cb_key_p(data, command, return_code, output, err): 824 | """Callback for fetching clipboard text and pasting it.""" 825 | buf = "" 826 | this_buffer = data 827 | if output != "": 828 | buf += output.strip() 829 | if return_code == 0: 830 | my_input = weechat.buffer_get_string(this_buffer, "input") 831 | pos = weechat.buffer_get_integer(this_buffer, "input_pos") + 1 832 | my_input = my_input[:pos] + buf + my_input[pos:] 833 | pos += len(buf) 834 | weechat.buffer_set(this_buffer, "input", my_input) 835 | weechat.buffer_set(this_buffer, "input_pos", str(pos)) 836 | return weechat.WEECHAT_RC_OK 837 | 838 | def key_i(buf, input_line, cur, count): 839 | """Start Insert mode. 840 | 841 | See Also: 842 | `key_base()`. 843 | """ 844 | set_mode("INSERT") 845 | 846 | def key_a(buf, input_line, cur, count): 847 | """Move cursor one character to the right and start Insert mode. 848 | 849 | See Also: 850 | `key_base()`. 851 | """ 852 | set_cur(buf, input_line, cur + 1, False) 853 | set_mode("INSERT") 854 | 855 | def key_A(buf, input_line, cur, count): 856 | """Move cursor to end of line and start Insert mode. 857 | 858 | See Also: 859 | `key_base()`. 860 | """ 861 | set_cur(buf, input_line, len(input_line), False) 862 | set_mode("INSERT") 863 | 864 | def key_I(buf, input_line, cur, count): 865 | """Move cursor to first non-blank character and start Insert mode. 866 | 867 | See Also: 868 | `key_base()`. 869 | """ 870 | _, pos, _, _ = motion_carret(input_line, cur, 0) 871 | set_cur(buf, input_line, pos) 872 | set_mode("INSERT") 873 | 874 | def key_G(buf, input_line, cur, count): 875 | """Scroll to specified line or bottom of buffer. 876 | 877 | See Also: 878 | `key_base()`. 879 | """ 880 | if count > 0: 881 | # This is necessary to prevent weird scroll jumps. 882 | weechat.command("", "/window scroll_top") 883 | weechat.command("", "/window scroll %s" % (count - 1)) 884 | else: 885 | weechat.command("", "/window scroll_bottom") 886 | 887 | def key_r(buf, input_line, cur, count): 888 | """Replace `count` characters under the cursor. 889 | 890 | See Also: 891 | `key_base()`. 892 | """ 893 | start_catching_keys(1, "cb_key_r", input_line, cur, count, buf) 894 | 895 | def cb_key_r(): 896 | """Callback for `key_r()`. 897 | 898 | See Also: 899 | `start_catching_keys()`. 900 | """ 901 | global catching_keys_data 902 | input_line = list(catching_keys_data['input_line']) 903 | count = max(catching_keys_data['count'], 1) 904 | cur = catching_keys_data['cur'] 905 | if cur + count <= len(input_line): 906 | for _ in range(count): 907 | input_line[cur] = catching_keys_data['keys'] 908 | cur += 1 909 | input_line = "".join(input_line) 910 | weechat.buffer_set(catching_keys_data['buf'], "input", input_line) 911 | set_cur(catching_keys_data['buf'], input_line, cur - 1) 912 | catching_keys_data = {'amount': 0} 913 | 914 | def key_R(buf, input_line, cur, count): 915 | """Start Replace mode. 916 | 917 | See Also: 918 | `key_base()`. 919 | """ 920 | set_mode("REPLACE") 921 | 922 | def key_tilda(buf, input_line, cur, count): 923 | """Switch the case of `count` characters under the cursor. 924 | 925 | See Also: 926 | `key_base()`. 927 | """ 928 | input_line = list(input_line) 929 | count = max(1, count) 930 | while count and cur < len(input_line): 931 | input_line[cur] = input_line[cur].swapcase() 932 | count -= 1 933 | cur += 1 934 | input_line = "".join(input_line) 935 | weechat.buffer_set(buf, "input", input_line) 936 | set_cur(buf, input_line, cur) 937 | 938 | def key_alt_j(buf, input_line, cur, count): 939 | """Go to WeeChat buffer. 940 | 941 | Called to preserve WeeChat's alt-j buffer switching. 942 | 943 | This is only called when alt-j is pressed after pressing Esc, because 944 | \x01\x01j is received in key_combo_default which becomes \x01j after 945 | removing the detected Esc key. 946 | If Esc isn't the last pressed key, \x01j is directly received in 947 | key_combo_default. 948 | """ 949 | start_catching_keys(2, "cb_key_alt_j", input_line, cur, count) 950 | 951 | def cb_key_alt_j(): 952 | """Callback for `key_alt_j()`. 953 | 954 | See Also: 955 | `start_catching_keys()`. 956 | """ 957 | global catching_keys_data 958 | weechat.command("", "/buffer " + catching_keys_data['keys']) 959 | catching_keys_data = {'amount': 0} 960 | 961 | def key_semicolon(buf, input_line, cur, count, swap=False): 962 | """Repeat last f, t, F, T `count` times. 963 | 964 | Args: 965 | swap (bool, optional): if True, the last motion will be repeated in the 966 | opposite direction (e.g. "f" instead of "F"). Defaults to False. 967 | 968 | See Also: 969 | `key_base()`. 970 | """ 971 | global catching_keys_data, vi_buffer 972 | catching_keys_data = ({'amount': 0, 973 | 'input_line': input_line, 974 | 'cur': cur, 975 | 'keys': last_search_motion['data'], 976 | 'count': count, 977 | 'new_cur': 0, 978 | 'buf': buf}) 979 | if not last_search_motion['motion']: 980 | return 981 | # Swap the motion's case if called from key_comma. 982 | if swap: 983 | motion = last_search_motion['motion'].swapcase() 984 | else: 985 | motion = last_search_motion['motion'] 986 | func = "cb_motion_%s" % motion 987 | vi_buffer = motion 988 | globals()[func](False) 989 | 990 | def key_comma(buf, input_line, cur, count): 991 | """Repeat last f, t, F, T in opposite direction `count` times. 992 | 993 | See Also: 994 | `key_base()`. 995 | """ 996 | key_semicolon(buf, input_line, cur, count, True) 997 | 998 | def key_u(buf, input_line, cur, count): 999 | """Undo change `count` times. 1000 | 1001 | See Also: 1002 | `key_base()`. 1003 | """ 1004 | buf = weechat.current_buffer() 1005 | if buf not in undo_history: 1006 | return 1007 | for _ in range(max(count, 1)): 1008 | if undo_history_index[buf] > -len(undo_history[buf]): 1009 | undo_history_index[buf] -= 1 1010 | input_line = undo_history[buf][undo_history_index[buf]] 1011 | weechat.buffer_set(buf, "input", input_line) 1012 | else: 1013 | break 1014 | 1015 | def key_ctrl_r(buf, input_line, cur, count): 1016 | """Redo change `count` times. 1017 | 1018 | See Also: 1019 | `key_base()`. 1020 | """ 1021 | if buf not in undo_history: 1022 | return 1023 | for _ in range(max(count, 1)): 1024 | if undo_history_index[buf] < -1: 1025 | undo_history_index[buf] += 1 1026 | input_line = undo_history[buf][undo_history_index[buf]] 1027 | weechat.buffer_set(buf, "input", input_line) 1028 | else: 1029 | break 1030 | 1031 | 1032 | # Vi key bindings. 1033 | # ================ 1034 | 1035 | # String values will be executed as normal WeeChat commands. 1036 | # For functions, see `key_base()` for reference. 1037 | VI_DEFAULT_KEYS = {'G': key_G, 1038 | 'gg': "/window scroll_top", 1039 | 'x': "/input delete_next_char", 1040 | 'X': "/input delete_previous_char", 1041 | 'dd': "/input delete_line", 1042 | 'D': "/input delete_end_of_line", 1043 | 'cc': key_cc, 1044 | 'S': key_cc, 1045 | 'C': key_C, 1046 | 'i': key_i, 1047 | 'a': key_a, 1048 | 'A': key_A, 1049 | 'I': key_I, 1050 | 'yy': key_yy, 1051 | 'p': key_p, 1052 | 'gt': "/buffer -1", 1053 | 'K': "/buffer -1", 1054 | 'H': "/buffer -1", 1055 | 'gT': "/buffer +1", 1056 | 'J': "/buffer +1", 1057 | 'L': "/buffer +1", 1058 | 'r': key_r, 1059 | 'R': key_R, 1060 | '~': key_tilda, 1061 | 'nt': "/bar scroll nicklist * -100%", 1062 | 'nT': "/bar scroll nicklist * +100%", 1063 | '\x01[[A': "/input history_previous", 1064 | '\x01[[B': "/input history_next", 1065 | '\x01[[C': "/input move_next_char", 1066 | '\x01[[D': "/input move_previous_char", 1067 | '\x01[[H': "/input move_beginning_of_line", 1068 | '\x01[[F': "/input move_end_of_line", 1069 | '\x01[[5~': "/window page_up", 1070 | '\x01[[6~': "/window page_down", 1071 | '\x01[[3~': "/input delete_next_char", 1072 | '\x01[[2~': key_i, 1073 | '\x01m': "/input return", 1074 | '\x01?': "/input move_previous_char", 1075 | ' ': "/input move_next_char", 1076 | '\x01[j': key_alt_j, 1077 | '\x01[1': "/buffer *1", 1078 | '\x01[2': "/buffer *2", 1079 | '\x01[3': "/buffer *3", 1080 | '\x01[4': "/buffer *4", 1081 | '\x01[5': "/buffer *5", 1082 | '\x01[6': "/buffer *6", 1083 | '\x01[7': "/buffer *7", 1084 | '\x01[8': "/buffer *8", 1085 | '\x01[9': "/buffer *9", 1086 | '\x01[0': "/buffer *10", 1087 | '\x01^': "/input jump_last_buffer_displayed", 1088 | '\x01f': "/window page_down", 1089 | '\x01b': "/window page_up", 1090 | '\x01d': "/window scroll_down", 1091 | '\x01u': "/window scroll_up", 1092 | '\x01e': "/window scroll +1", 1093 | '\x01y': "/window scroll -1", 1094 | 'j': "/window scroll +1", 1095 | 'k': "/window scroll -1", 1096 | '\x01wh': "/window left", 1097 | '\x01wj': "/window down", 1098 | '\x01wk': "/window up", 1099 | '\x01wl': "/window right", 1100 | '\x01w=': "/window balance", 1101 | '\x01wx': "/window swap", 1102 | '\x01ws': "/window splith", 1103 | '\x01wv': "/window splitv", 1104 | '\x01wq': "/window merge", 1105 | ';': key_semicolon, 1106 | ',': key_comma, 1107 | 'u': key_u, 1108 | '\x01r': key_ctrl_r} 1109 | 1110 | # Add alt-j bindings. 1111 | for i in range(10, 99): 1112 | VI_DEFAULT_KEYS['\x01[j%s' % i] = "/buffer %s" % i 1113 | 1114 | # VI_DEFAULT_KEYS are kept in a separate data structure to ensure 1115 | # that they can not be permenantly deleted by the `:nunmap` command. 1116 | VI_KEYS = VI_DEFAULT_KEYS.copy() 1117 | 1118 | class UMParser: 1119 | """User Mapping Parser 1120 | 1121 | Handles parsing for UserMapping class. 1122 | """ 1123 | __metaclass__ = ABCMeta 1124 | 1125 | @abstractproperty 1126 | def count(self): 1127 | """Required Attribute""" 1128 | 1129 | @abstractproperty 1130 | def noremap(self): 1131 | """Required Attribute""" 1132 | 1133 | def parse(self, vi_keys): 1134 | """Vi_Keys parser that generates callable actions. 1135 | 1136 | Yields: 1137 | Callable object: action(buf, input_line, cur, count) 1138 | """ 1139 | old_style_cmd_conditions = [ 1140 | vi_keys[0] == '/', 1141 | re.search('', vi_keys.lower()) is None, 1142 | ] 1143 | 1144 | # >>> OLD-STYLE USER MAPPING 1145 | if all(old_style_cmd_conditions): 1146 | yield functools.partial(do_command, vi_keys) 1147 | # >>> NEW-STYLE USER MAPPING 1148 | else: 1149 | for action in self.new_style(vi_keys): 1150 | yield action 1151 | 1152 | def new_style(self, vi_keys): 1153 | """Parse New-Style User Mapping 1154 | 1155 | Yields: 1156 | Callable object: action(buf, input_line, cur, count) 1157 | """ 1158 | index = 0 1159 | while index < len(vi_keys): 1160 | # >>> COUNT 1161 | match = re.match('^[1-9][0-9]*', vi_keys[index:]) 1162 | if match: 1163 | end = match.end() + index 1164 | self.count += int(vi_keys[index:end]) 1165 | index += match.end() 1166 | 1167 | # >>> ACTION SPECIFIER 1168 | action, i = self.action_spec(vi_keys[index:]) 1169 | index += i 1170 | if action is None: 1171 | continue 1172 | else: 1173 | yield action 1174 | 1175 | def action_spec(self, vi_keys): 1176 | """Parse Action Specifier 1177 | 1178 | Returns: 1179 | 2-tuple: (Callable_Action, Index_Where_Parsing_Stoped) 1180 | """ 1181 | # >>> INSERT MODE SEQUENCE 1182 | if mode == 'INSERT': 1183 | match = re.search('<(cr|esc)>', vi_keys.lower()) 1184 | enter = False 1185 | 1186 | if match: 1187 | set_mode('NORMAL') 1188 | index = match.end() 1189 | if match.group() == '': 1190 | enter = True 1191 | else: 1192 | index = start = len(vi_keys) 1193 | 1194 | start = match.start() if match else len(vi_keys) 1195 | return self.imode_capture(vi_keys[:start], enter=enter), index 1196 | 1197 | # >>> VI_KEY 1198 | key_map = VI_DEFAULT_KEYS if self.noremap else VI_KEYS 1199 | for keys, command in key_map.items(): 1200 | if vi_keys.startswith(keys): 1201 | if isinstance(command, str): 1202 | return functools.partial(do_command, command), len(keys) 1203 | else: 1204 | return command, len(keys) 1205 | 1206 | # >>> VI_MOTION 1207 | for motion in VI_MOTIONS: 1208 | if vi_keys.startswith(motion): 1209 | return functools.partial(do_motion, motion), len(motion) 1210 | 1211 | # >>> VI_OPERATOR 1212 | if len(vi_keys) > 1 and vi_keys[0] in VI_OPERATORS: 1213 | for motion in VI_MOTIONS: 1214 | if vi_keys[1:].startswith(motion): 1215 | action = functools.partial(do_operator, 1216 | vi_keys[:len(motion) + 1]) 1217 | return action, len(motion) + 1 1218 | 1219 | # >>> WEECHAT COMMAND 1220 | match = re.search('^[:/](.*?)<(CR|cr)>', vi_keys) 1221 | if match: 1222 | end = match.end() 1223 | group = match.groups()[0] 1224 | cmd_list = group.split(None, 1) 1225 | cmd = cmd_list[0] 1226 | args = cmd_list[1] if len(cmd_list) == 2 else '' 1227 | 1228 | if re.match('b[1-9][0-9]*', cmd): 1229 | args = '{} {}'.format(cmd[1:], args) 1230 | cmd = cmd[0] 1231 | 1232 | if cmd in VI_COMMANDS: 1233 | if isinstance(VI_COMMANDS[cmd], str): 1234 | full_cmd = '{} {}'.format(VI_COMMANDS[cmd], args) 1235 | action = functools.partial(do_command, full_cmd) 1236 | else: 1237 | action = self.vi_cmd_action(cmd, args) 1238 | else: 1239 | action = functools.partial(do_command, 1240 | '/{}'.format(vi_keys[1:end - 4])) 1241 | return action, end 1242 | 1243 | # >>> PARSING ERROR 1244 | if vi_keys[0] in (':', '/'): 1245 | self.bad_sequence += vi_keys 1246 | return None, len(vi_keys) 1247 | else: 1248 | self.bad_sequence += vi_keys[0] 1249 | return None, 1 1250 | 1251 | def vi_cmd_action(self, cmd, args): 1252 | """Factory for VI_COMMAND Action""" 1253 | def action(buf, input_line, cur, count): 1254 | VI_COMMANDS[cmd](args) 1255 | return action 1256 | 1257 | def imode_capture(self, new_input, enter=False): 1258 | """Factory for Action that Captures Input and Sends it to Command-Line 1259 | 1260 | This is expected when the mappings previous actions have set 1261 | INSERT mode. 1262 | """ 1263 | def action(buf, input_line, cur, count): 1264 | for _ in range(max(int(count), 1)): 1265 | p = int(cur) 1266 | final_input = '{}{}{}'.format(input_line[:p], 1267 | new_input, 1268 | input_line[p:]) 1269 | weechat.buffer_set(buf, "input", final_input) 1270 | new_pos = str(len(new_input) + p) 1271 | weechat.buffer_set(buf, "input_pos", new_pos) 1272 | 1273 | input_line = weechat.buffer_get_string(buf, "input") 1274 | cur = weechat.buffer_get_integer(buf, "input_pos") 1275 | if enter: 1276 | do_command('/input return', buf, input_line, cur, 0) 1277 | return action 1278 | 1279 | class UserMapping(UMParser): 1280 | """Wraps User Mapping Defined by :nmap Command""" 1281 | count = 0 1282 | locked = False 1283 | noremap = False 1284 | 1285 | def __init__(self, lhs, rhs, noremap=False): 1286 | self.lhs = lhs 1287 | self.rhs = rhs 1288 | self.noremap = noremap 1289 | 1290 | def __call__(self, buf, input_line, cur, count): 1291 | if self.locked: 1292 | error_fmt = ("Somthing's not right. The following user mapping " 1293 | "is recursing on itself: (\"{}\", \"{}\").") 1294 | print_warning(error_fmt.format(self.lhs, self.rhs)) 1295 | return 1296 | 1297 | rhs, count = self.process_count(count) 1298 | self.bad_sequence = "" 1299 | with self.lock(): 1300 | for _ in range(count): 1301 | bad_seq_list = [] 1302 | for action in self.parse(rhs): 1303 | if self.bad_sequence: 1304 | bad_seq_list.append(self.bad_sequence) 1305 | 1306 | action(buf, input_line, cur, self.count) 1307 | 1308 | # Reset count unless last key triggers 1309 | # INSERT mode ('i', 'a', 'I', 'A', ...). 1310 | if mode != 'INSERT': 1311 | self.count = 0 1312 | 1313 | self.bad_sequence = "" 1314 | 1315 | buf = weechat.current_buffer() 1316 | input_line = weechat.buffer_get_string(buf, "input") 1317 | cur = weechat.buffer_get_integer(buf, "input_pos") 1318 | 1319 | self.count = 0 1320 | if self.bad_sequence: 1321 | bad_seq_list.append(self.bad_sequence) 1322 | self.bad_sequence = "" 1323 | 1324 | self.report_errors(bad_seq_list) 1325 | 1326 | @contextmanager 1327 | def lock(self): 1328 | """ Access Lock 1329 | 1330 | Protects against infinite recursion which could be triggered by 1331 | defining a mapping in terms of itself, for example. 1332 | """ 1333 | try: 1334 | self.locked = True 1335 | yield 1336 | finally: 1337 | self.locked = False 1338 | 1339 | def process_count(self, count): 1340 | """Checks for a special count tag of the form #{N} where N is some integer. 1341 | 1342 | If a count tag is found, consume the count by substituting it in place 1343 | of the tag. 1344 | """ 1345 | if re.search(r'#{\d+}', self.rhs) is not None: 1346 | if count: 1347 | rhs = re.sub(r'#{\d+}', str(count), self.rhs) 1348 | else: 1349 | rhs = re.sub(r'#{(\d+)}', r'\1', self.rhs) 1350 | new_count = 1 1351 | else: 1352 | rhs = self.rhs 1353 | new_count = max(count, 1) 1354 | return rhs, new_count 1355 | 1356 | def report_errors(self, bad_seq_list): 1357 | """Alert user about any parsing errors that occurred.""" 1358 | for bad_seq in bad_seq_list: 1359 | error_msg = 'Failed to parse "{}" sequence ' \ 1360 | 'in the following user mapping: ' \ 1361 | '("{}", "{}").'.format(bad_seq, self.lhs, self.rhs) 1362 | print_warning(error_msg) 1363 | 1364 | 1365 | # Key handling. 1366 | # ============= 1367 | 1368 | def normalize_keys(signal_data): 1369 | """Translate upper case ctrl sequences to lower case ones""" 1370 | return re.sub("\x01[A-Z]", lambda match: match.group(0).lower(), signal_data) 1371 | 1372 | def cb_key_pressed(data, signal, signal_data): 1373 | """Detect potential Esc presses. 1374 | 1375 | Alt and Esc are detected as the same key in most terminals. The difference 1376 | is that Alt signal is sent just before the other pressed key's signal. 1377 | We therefore use a timeout (50ms) to detect whether Alt or Esc was pressed. 1378 | """ 1379 | global last_signal_time 1380 | keys = normalize_keys(signal_data) 1381 | last_signal_time = time.time() 1382 | if keys == "\x01[": 1383 | # In 50ms, check if any other keys were pressed. If not, it's Esc! 1384 | weechat.hook_timer(50, 0, 1, "cb_check_esc", 1385 | "{:f}".format(last_signal_time)) 1386 | return weechat.WEECHAT_RC_OK 1387 | 1388 | def cb_check_esc(data, remaining_calls): 1389 | """Check if the Esc key was pressed and change the mode accordingly.""" 1390 | global esc_pressed, vi_buffer, catching_keys_data 1391 | # Not perfect, would be better to use direct comparison (==) but that only 1392 | # works for py2 and not for py3. 1393 | if abs(last_signal_time - float(data)) <= 0.000001: 1394 | esc_pressed += 1 1395 | if mode == "SEARCH" or mode == "COMMAND": 1396 | weechat.command("", "/input search_stop_here") 1397 | set_mode("NORMAL") 1398 | # Cancel any current partial commands. 1399 | vi_buffer = "" 1400 | catching_keys_data = {'amount': 0} 1401 | weechat.bar_item_update("vi_buffer") 1402 | return weechat.WEECHAT_RC_OK 1403 | 1404 | def cb_key_combo_default(data, signal, signal_data): 1405 | """Eat and handle key events when in Normal mode, if needed. 1406 | 1407 | The key_combo_default signal is sent when a key combo is pressed. For 1408 | example, alt-k will send the "\x01[k" signal. 1409 | 1410 | Esc is handled a bit differently to avoid delays, see `cb_key_pressed()`. 1411 | """ 1412 | global esc_pressed, vi_buffer, cmd_compl_text, cmd_text_orig, \ 1413 | cmd_compl_pos, cmd_history_index 1414 | 1415 | # If Esc was pressed, strip the Esc part from the pressed keys. 1416 | # Example: user presses Esc followed by i. This is detected as "\x01[i", 1417 | # but we only want to handle "i". 1418 | keys = normalize_keys(signal_data) 1419 | if esc_pressed or esc_pressed == -2: 1420 | if keys.startswith("\x01[" * esc_pressed): 1421 | # Multiples of 3 seem to "cancel" themselves, 1422 | # e.g. Esc-Esc-Esc-Alt-j-11 is detected as "\x01[\x01[\x01" 1423 | # followed by "\x01[j11" (two different signals). 1424 | if signal_data == "\x01[" * 3: 1425 | esc_pressed = -1 # `cb_check_esc()` will increment it to 0. 1426 | else: 1427 | esc_pressed = 0 1428 | # This can happen if a valid combination is started but interrupted 1429 | # with Esc, such as Ctrl-W→Esc→w which would send two signals: 1430 | # "\x01w\x01[" then "\x01w\x01[w". 1431 | # In that case, we still need to handle the next signal ("\x01w\x01[w") 1432 | # so we use the special value "-2". 1433 | else: 1434 | esc_pressed = -2 1435 | keys = keys.split("\x01[")[-1] # Remove the "Esc" part(s). 1436 | # Ctrl-Space. 1437 | elif keys == "\x01@": 1438 | set_mode("NORMAL") 1439 | return weechat.WEECHAT_RC_OK_EAT 1440 | 1441 | # Clear the undo history for this buffer on . 1442 | if keys == "\x01m": 1443 | buf = weechat.current_buffer() 1444 | clear_undo_history(buf) 1445 | 1446 | # Detect imap_esc presses if any. 1447 | if mode == "INSERT": 1448 | imap_esc = vimode_settings['imap_esc'] 1449 | if not imap_esc: 1450 | return weechat.WEECHAT_RC_OK 1451 | if (imap_esc.startswith(vi_buffer) and 1452 | imap_esc[len(vi_buffer):len(vi_buffer) + 1] == keys): 1453 | vi_buffer += keys 1454 | weechat.bar_item_update("vi_buffer") 1455 | weechat.hook_timer(int(vimode_settings['imap_esc_timeout']), 0, 1, 1456 | "cb_check_imap_esc", vi_buffer) 1457 | elif (vi_buffer and imap_esc.startswith(vi_buffer) and 1458 | imap_esc[len(vi_buffer):len(vi_buffer) + 1] != keys): 1459 | vi_buffer = "" 1460 | weechat.bar_item_update("vi_buffer") 1461 | # imap_esc sequence detected -- remove the sequence keys from the 1462 | # Weechat input bar and enter Normal mode. 1463 | if imap_esc == vi_buffer: 1464 | buf = weechat.current_buffer() 1465 | input_line = weechat.buffer_get_string(buf, "input") 1466 | cur = weechat.buffer_get_integer(buf, "input_pos") 1467 | input_line = (input_line[:cur - len(imap_esc) + 1] + 1468 | input_line[cur:]) 1469 | weechat.buffer_set(buf, "input", input_line) 1470 | set_cur(buf, input_line, cur - len(imap_esc) + 1, False) 1471 | set_mode("NORMAL") 1472 | vi_buffer = "" 1473 | weechat.bar_item_update("vi_buffer") 1474 | return weechat.WEECHAT_RC_OK_EAT 1475 | return weechat.WEECHAT_RC_OK 1476 | 1477 | # We're in Replace mode — allow "normal" key presses (e.g. "a") and 1478 | # overwrite the next character with them, but let the other key presses 1479 | # pass normally (e.g. backspace, arrow keys, etc). 1480 | if mode == "REPLACE": 1481 | if len(keys) == 1: 1482 | weechat.command("", "/input delete_next_char") 1483 | elif keys == "\x01?": 1484 | weechat.command("", "/input move_previous_char") 1485 | return weechat.WEECHAT_RC_OK_EAT 1486 | return weechat.WEECHAT_RC_OK 1487 | 1488 | # We're in command-line mode. 1489 | if mode == "COMMAND": 1490 | buf = weechat.current_buffer() 1491 | cmd_text = weechat.buffer_get_string(buf, "input") 1492 | weechat.hook_timer(1, 0, 1, "cb_check_cmd_mode", "") 1493 | # Return key. 1494 | if keys == "\x01m": 1495 | weechat.hook_timer(1, 0, 1, "cb_exec_cmd", cmd_text) 1496 | if len(cmd_text) > 1 and (not cmd_history or 1497 | cmd_history[-1] != cmd_text): 1498 | cmd_history.append(cmd_text) 1499 | cmd_history_index = 0 1500 | set_mode("NORMAL") 1501 | buf = weechat.current_buffer() 1502 | input_line = input_line_backup[buf]['input_line'] 1503 | weechat.buffer_set(buf, "input", input_line) 1504 | set_cur(buf, input_line, input_line_backup[buf]['cur'], False) 1505 | # Up arrow. 1506 | elif keys == "\x01[[A": 1507 | if cmd_history_index > -len(cmd_history): 1508 | cmd_history_index -= 1 1509 | cmd_text = cmd_history[cmd_history_index] 1510 | weechat.buffer_set(buf, "input", cmd_text) 1511 | set_cur(buf, cmd_text, len(cmd_text), False) 1512 | # Down arrow. 1513 | elif keys == "\x01[[B": 1514 | if cmd_history_index < -1: 1515 | cmd_history_index += 1 1516 | cmd_text = cmd_history[cmd_history_index] 1517 | else: 1518 | cmd_history_index = 0 1519 | cmd_text = ":" 1520 | weechat.buffer_set(buf, "input", cmd_text) 1521 | set_cur(buf, cmd_text, len(cmd_text), False) 1522 | # Tab key. No completion when searching ("/"). 1523 | elif keys == "\x01i" and cmd_text[0] == ":": 1524 | if cmd_text_orig is None: 1525 | input_ = list(cmd_text) 1526 | del input_[0] 1527 | cmd_text_orig = "".join(input_) 1528 | cmd_compl_list = [] 1529 | for cmd in VI_COMMANDS.keys(): 1530 | if cmd.startswith(cmd_text_orig): 1531 | cmd_compl_list.append(cmd) 1532 | if cmd_compl_list: 1533 | curr_suggestion = cmd_compl_list[cmd_compl_pos] 1534 | cmd_text = ":%s" % curr_suggestion 1535 | cmd_compl_list[cmd_compl_pos] = weechat.string_eval_expression( 1536 | "${color:bold}%s${color:-bold}" % curr_suggestion, 1537 | {}, {}, {}) 1538 | cmd_compl_text = ", ".join(cmd_compl_list) 1539 | cmd_compl_pos = (cmd_compl_pos + 1) % len(cmd_compl_list) 1540 | weechat.buffer_set(buf, "input", cmd_text) 1541 | set_cur(buf, cmd_text, len(cmd_text), False) 1542 | # Input. 1543 | else: 1544 | cmd_compl_text = "" 1545 | cmd_text_orig = None 1546 | cmd_compl_pos = 0 1547 | weechat.bar_item_update("cmd_completion") 1548 | if keys in ["\x01m", "\x01[[A", "\x01[[B"]: 1549 | cmd_compl_text = "" 1550 | return weechat.WEECHAT_RC_OK_EAT 1551 | else: 1552 | return weechat.WEECHAT_RC_OK 1553 | # Enter command mode. 1554 | elif keys in [vimode_settings['user_command_mapping'], "/"]: 1555 | if keys == "/": 1556 | weechat.command("", "/input search_text_here") 1557 | if not weechat.config_string_to_boolean( 1558 | vimode_settings['search_vim']): 1559 | return weechat.WEECHAT_RC_OK 1560 | else: 1561 | buf = weechat.current_buffer() 1562 | cur = weechat.buffer_get_integer(buf, "input_pos") 1563 | input_line = weechat.buffer_get_string(buf, "input") 1564 | input_line_backup[buf] = {'input_line': input_line, 'cur': cur} 1565 | input_line = ":" 1566 | weechat.buffer_set(buf, "input", input_line) 1567 | set_cur(buf, input_line, 1, False) 1568 | set_mode("COMMAND") 1569 | cmd_compl_text = "" 1570 | cmd_text_orig = None 1571 | cmd_compl_pos = 0 1572 | return weechat.WEECHAT_RC_OK_EAT 1573 | 1574 | # Add key to the buffer. 1575 | vi_buffer += keys 1576 | weechat.bar_item_update("vi_buffer") 1577 | if not vi_buffer: 1578 | return weechat.WEECHAT_RC_OK 1579 | 1580 | # Check if the keys have a (partial or full) match. If so, also get the 1581 | # keys without the count. (These are the actual keys we should handle.) 1582 | # After that, `vi_buffer` is only used for display purposes — only 1583 | # `vi_keys` is checked for all the handling. 1584 | # If no matches are found, the keys buffer is cleared. 1585 | matched, vi_keys, count = get_keys_and_count(vi_buffer) 1586 | if not matched and not catching_keys_data['amount']: 1587 | vi_buffer = "" 1588 | return weechat.WEECHAT_RC_OK_EAT 1589 | # Check if it's a command (user defined key mapped to a :cmd). 1590 | if vi_keys.startswith(":"): 1591 | weechat.hook_timer(1, 0, 1, "cb_exec_cmd", "{} {}".format(vi_keys, 1592 | count)) 1593 | vi_buffer = "" 1594 | return weechat.WEECHAT_RC_OK_EAT 1595 | # It's a WeeChat command (user defined key mapped to a /cmd). 1596 | if vi_keys.startswith("/"): 1597 | weechat.command("", vi_keys) 1598 | vi_buffer = "" 1599 | return weechat.WEECHAT_RC_OK_EAT 1600 | 1601 | buf = weechat.current_buffer() 1602 | input_line = weechat.buffer_get_string(buf, "input") 1603 | cur = weechat.buffer_get_integer(buf, "input_pos") 1604 | 1605 | # Check if we should catch keys, but don't do anything yet (in case the 1606 | # user remapped this combo, and we shouldn't be calling the callback). 1607 | catching_keys = False 1608 | if catching_keys_data['amount']: 1609 | catching_keys = True 1610 | catching_keys_data['keys'] += keys 1611 | catching_keys_data['amount'] -= 1 1612 | 1613 | # It's a default mapping. If the corresponding value is a string, we assume 1614 | # it's a WeeChat command. Otherwise, it's a method we'll call. 1615 | if vi_keys in VI_KEYS: 1616 | if vi_keys not in ['u', '\x01r']: 1617 | add_undo_history(buf, input_line) 1618 | if isinstance(VI_KEYS[vi_keys], str): 1619 | do_command(VI_KEYS[vi_keys], buf, input_line, cur, count) 1620 | else: 1621 | VI_KEYS[vi_keys](buf, input_line, cur, count) 1622 | # It's a motion (e.g. "w") — call `motion_X()` where X is the motion, then 1623 | # set the cursor's position to what that function returned. 1624 | elif vi_keys in VI_MOTIONS: 1625 | do_motion(vi_keys, buf, input_line, cur, count) 1626 | # It's an operator + motion (e.g. "dw") — call `motion_X()` (where X is 1627 | # the motion), then we call `operator_Y()` (where Y is the operator) 1628 | # with the position `motion_X()` returned. `operator_Y()` should then 1629 | # handle changing the input line. 1630 | elif (len(vi_keys) > 1 and 1631 | vi_keys[0] in VI_OPERATORS and 1632 | vi_keys[1:] in VI_MOTIONS): 1633 | do_operator(vi_keys, buf, input_line, cur, count) 1634 | # Done catching keys, execute the callback. 1635 | elif catching_keys and catching_keys_data['amount'] == 0: 1636 | catching_keys_data['amount'] = -1 1637 | vi_buffer = vi_buffer[:-len(keys)] 1638 | globals()[catching_keys_data['callback']]() 1639 | vi_buffer = "" 1640 | weechat.bar_item_update("vi_buffer") 1641 | else: 1642 | return weechat.WEECHAT_RC_OK_EAT 1643 | 1644 | # We've already handled the key combo, so clear the keys buffer. 1645 | if catching_keys_data['amount'] <= 0: 1646 | catching_keys_data['amount'] = 0 1647 | vi_buffer = "" 1648 | weechat.bar_item_update("vi_buffer") 1649 | return weechat.WEECHAT_RC_OK_EAT 1650 | 1651 | def cb_check_imap_esc(data, remaining_calls): 1652 | """Clear the imap_esc sequence after some time if nothing was pressed.""" 1653 | global vi_buffer 1654 | if vi_buffer == data: 1655 | vi_buffer = "" 1656 | weechat.bar_item_update("vi_buffer") 1657 | return weechat.WEECHAT_RC_OK 1658 | 1659 | def cb_key_combo_search(data, signal, signal_data): 1660 | """Handle keys while search mode is active (if search_vim is enabled).""" 1661 | keys = normalize_keys(signal_data) 1662 | if not weechat.config_string_to_boolean(vimode_settings['search_vim']): 1663 | return weechat.WEECHAT_RC_OK 1664 | if mode == "COMMAND": 1665 | if keys == "\x01m": 1666 | set_mode("SEARCH") 1667 | return weechat.WEECHAT_RC_OK_EAT 1668 | elif mode == "SEARCH": 1669 | if keys == "\x01m": 1670 | set_mode("NORMAL") 1671 | else: 1672 | if keys == "n": 1673 | weechat.command("", "/input search_next") 1674 | elif keys == "N": 1675 | weechat.command("", "/input search_previous") 1676 | # Start a new search. 1677 | elif keys == "/": 1678 | weechat.command("", "/input search_stop_here") 1679 | set_mode("NORMAL") 1680 | weechat.command("", "/input search_text_here") 1681 | return weechat.WEECHAT_RC_OK_EAT 1682 | return weechat.WEECHAT_RC_OK 1683 | 1684 | # Callbacks. 1685 | # ========== 1686 | 1687 | # Bar items. 1688 | # ---------- 1689 | 1690 | def cb_vi_buffer(data, item, window): 1691 | """Return the content of the vi buffer (pressed keys on hold).""" 1692 | return vi_buffer 1693 | 1694 | def cb_cmd_completion(data, item, window): 1695 | """Return the text of the command line.""" 1696 | return cmd_compl_text 1697 | 1698 | def cb_mode_indicator(data, item, window): 1699 | """Return the current mode (INSERT/NORMAL/REPLACE/...).""" 1700 | return "{}{}{}{}{}".format( 1701 | weechat.color(mode_colors[mode]), 1702 | vimode_settings['mode_indicator_prefix'], mode, 1703 | vimode_settings['mode_indicator_suffix'], weechat.color("reset")) 1704 | 1705 | def cb_line_numbers(data, item, window): 1706 | """Fill the line numbers bar item.""" 1707 | bar_height = weechat.window_get_integer(window, "win_chat_height") 1708 | content = "" 1709 | for i in range(1, bar_height + 1): 1710 | content += "{}{:2}{}\n".format(vimode_settings['line_number_prefix'], 1711 | i, 1712 | vimode_settings['line_number_suffix']) 1713 | return content 1714 | 1715 | # Callbacks for the line numbers bar. 1716 | # ................................... 1717 | 1718 | def cb_update_line_numbers(data, signal, signal_data): 1719 | """Call `cb_timer_update_line_numbers()` when switching buffers. 1720 | 1721 | A timer is required because the bar item is refreshed before the new buffer 1722 | is actually displayed, so ``win_chat_height`` would refer to the old 1723 | buffer. Using a timer refreshes the item after the new buffer is displayed. 1724 | """ 1725 | weechat.hook_timer(10, 0, 1, "cb_timer_update_line_numbers", "") 1726 | return weechat.WEECHAT_RC_OK 1727 | 1728 | def cb_timer_update_line_numbers(data, remaining_calls): 1729 | """Update the line numbers bar item.""" 1730 | weechat.bar_item_update("line_numbers") 1731 | return weechat.WEECHAT_RC_OK 1732 | 1733 | 1734 | # Config. 1735 | # ------- 1736 | 1737 | def cb_config(data, option, value): 1738 | """Script option changed, update our copy.""" 1739 | option_name = option.split(".")[-1] 1740 | if option_name in vimode_settings: 1741 | vimode_settings[option_name] = value 1742 | if option_name.startswith('user_mappings'): 1743 | load_user_mappings() 1744 | if "_color" in option_name: 1745 | load_mode_colors() 1746 | if option_name == 'is_keyword': 1747 | load_is_keyword_regexes() 1748 | return weechat.WEECHAT_RC_OK 1749 | 1750 | def load_mode_colors(): 1751 | mode_colors.update({ 1752 | 'NORMAL': "{},{}".format( 1753 | vimode_settings['mode_indicator_normal_color'], 1754 | vimode_settings['mode_indicator_normal_color_bg']), 1755 | 'INSERT': "{},{}".format( 1756 | vimode_settings['mode_indicator_insert_color'], 1757 | vimode_settings['mode_indicator_insert_color_bg']), 1758 | 'REPLACE': "{},{}".format( 1759 | vimode_settings['mode_indicator_replace_color'], 1760 | vimode_settings['mode_indicator_replace_color_bg']), 1761 | 'COMMAND': "{},{}".format( 1762 | vimode_settings['mode_indicator_cmd_color'], 1763 | vimode_settings['mode_indicator_cmd_color_bg']), 1764 | 'SEARCH': "{},{}".format( 1765 | vimode_settings['mode_indicator_search_color'], 1766 | vimode_settings['mode_indicator_search_color_bg']) 1767 | }) 1768 | 1769 | def load_user_mappings(): 1770 | """Load user-defined mappings.""" 1771 | for key in ['user_mappings', 'user_mappings_noremap']: 1772 | noremap = key.endswith('noremap') 1773 | mappings = {} 1774 | if vimode_settings[key]: 1775 | if isinstance(vimode_settings[key], dict): 1776 | continue 1777 | mappings.update(json.loads(vimode_settings[key])) 1778 | vimode_settings[key] = mappings 1779 | for k, v in mappings.items(): 1780 | key = normalize_keys(k) 1781 | VI_KEYS[key] = UserMapping(key, v, noremap=noremap) 1782 | 1783 | def load_is_keyword_regexes(): 1784 | is_keyword = vimode_settings['is_keyword'] 1785 | vimode_settings['is_keyword'] = re.compile(is_keyword) 1786 | keyword_regexes['w'] = re.compile( 1787 | r"(?<=[^{0}])[{0}]|(?) 1858 | weechat.command("", "/wait 1ms /{} {}".format(cmd, args)) 1859 | return weechat.WEECHAT_RC_OK 1860 | 1861 | def cb_vimode_go_to_normal(data, buf, args): 1862 | set_mode("NORMAL") 1863 | return weechat.WEECHAT_RC_OK 1864 | 1865 | # Script commands. 1866 | # ---------------- 1867 | 1868 | def cb_vimode_cmd(data, buf, args): 1869 | """Handle script commands (``/vimode ``).""" 1870 | # ``/vimode`` or ``/vimode help`` 1871 | if not args or args == "help": 1872 | weechat.prnt("", "[vimode.py] %s" % README_URL) 1873 | # ``/vimode bind_keys`` or ``/vimode bind_keys --list`` 1874 | elif args.startswith("bind_keys"): 1875 | infolist = weechat.infolist_get("key", "", "default") 1876 | weechat.infolist_reset_item_cursor(infolist) 1877 | commands = ["/key unbind ctrl-W", 1878 | "/key bind ctrl-W /input delete_previous_word", 1879 | "/key bind ctrl-^ /input jump_last_buffer_displayed", 1880 | "/key bind ctrl-Wh /window left", 1881 | "/key bind ctrl-Wj /window down", 1882 | "/key bind ctrl-Wk /window up", 1883 | "/key bind ctrl-Wl /window right", 1884 | "/key bind ctrl-W= /window balance", 1885 | "/key bind ctrl-Wx /window swap", 1886 | "/key bind ctrl-Ws /window splith", 1887 | "/key bind ctrl-Wv /window splitv", 1888 | "/key bind ctrl-Wq /window merge"] 1889 | while weechat.infolist_next(infolist): 1890 | key = weechat.infolist_string(infolist, "key") 1891 | if re.match(REGEX_PROBLEMATIC_KEYBINDINGS, key): 1892 | commands.append("/key unbind %s" % key) 1893 | weechat.infolist_free(infolist) 1894 | if args == "bind_keys": 1895 | weechat.prnt("", "Running commands:") 1896 | for command in commands: 1897 | weechat.command("", command) 1898 | weechat.prnt("", "Done.") 1899 | elif args == "bind_keys --list": 1900 | weechat.prnt("", "Listing commands we'll run:") 1901 | for command in commands: 1902 | weechat.prnt("", " %s" % command) 1903 | weechat.prnt("", "Done.") 1904 | return weechat.WEECHAT_RC_OK 1905 | 1906 | 1907 | # Helpers. 1908 | # ======== 1909 | 1910 | # Motions/keys helpers. 1911 | # --------------------- 1912 | def do_command(cmd, buf, input_line, cur, count): 1913 | """Execute WeeChat Command""" 1914 | for _ in range(max(count, 1)): 1915 | weechat.command("", cmd) 1916 | current_cur = weechat.buffer_get_integer(buf, "input_pos") 1917 | set_cur(buf, input_line, current_cur) 1918 | 1919 | def do_motion(keys, buf, input_line, cur, count): 1920 | """Perform Vim-like Motion""" 1921 | if keys in SPECIAL_CHARS: 1922 | func = "motion_%s" % SPECIAL_CHARS[keys] 1923 | else: 1924 | func = "motion_%s" % keys 1925 | _, end, _, _ = globals()[func](input_line, cur, count) 1926 | set_cur(buf, input_line, end) 1927 | 1928 | def do_operator(keys, buf, input_line, cur, count): 1929 | add_undo_history(buf, input_line) 1930 | if keys[1:] in SPECIAL_CHARS: 1931 | func = "motion_%s" % SPECIAL_CHARS[keys[1:]] 1932 | else: 1933 | func = "motion_%s" % keys[1:] 1934 | pos1, pos2, overwrite, catching = globals()[func](input_line, cur, count) 1935 | # See vim's "Special case" in :help cw 1936 | is_keyword = vimode_settings['is_keyword'] 1937 | if keys in ["cw", "cW"] and is_keyword.match(input_line[cur]): 1938 | pos2 -= 1 1939 | # If it's a catching motion, we don't want to call the operator just 1940 | # yet -- this code will run again when the motion is complete, at which 1941 | # point we will. 1942 | if not catching: 1943 | oper = "operator_%s" % keys[0] 1944 | globals()[oper](buf, input_line, pos1, pos2, overwrite) 1945 | 1946 | def get_pos(data, regex, cur, ignore_cur=False, count=0): 1947 | """Return the position of `regex` match in `data`, starting at `cur`. 1948 | 1949 | Args: 1950 | data (str): the data to search in. 1951 | regex (pattern): regex pattern to search for. 1952 | cur (int): where to start the search. 1953 | ignore_cur (bool, optional): should the first match be ignored if it's 1954 | also the character at `cur`? 1955 | Defaults to False. 1956 | count (int, optional): the index of the match to return. Defaults to 0. 1957 | 1958 | Returns: 1959 | int: position of the match. -1 if no matches are found. 1960 | """ 1961 | # List of the *positions* of the found patterns. 1962 | matches = [m.start() for m in re.finditer(regex, data[cur:])] 1963 | pos = -1 1964 | if count: 1965 | if len(matches) > count - 1: 1966 | if ignore_cur and matches[0] == 0: 1967 | if len(matches) > count: 1968 | pos = matches[count] 1969 | else: 1970 | pos = matches[count - 1] 1971 | elif matches: 1972 | if ignore_cur and matches[0] == 0: 1973 | if len(matches) > 1: 1974 | pos = matches[1] 1975 | else: 1976 | pos = matches[0] 1977 | return pos 1978 | 1979 | def set_cur(buf, input_line, pos, cap=True): 1980 | """Set the cursor's position. 1981 | 1982 | Args: 1983 | buf (str): pointer to the current WeeChat buffer. 1984 | input_line (str): the content of the input line. 1985 | pos (int): the position to set the cursor to. 1986 | cap (bool, optional): if True, the `pos` will shortened to the length 1987 | of `input_line` if it's too long. Defaults to True. 1988 | """ 1989 | if cap: 1990 | pos = min(pos, len(input_line) - 1) 1991 | weechat.buffer_set(buf, "input_pos", str(pos)) 1992 | 1993 | def start_catching_keys(amount, callback, input_line, cur, count, buf=None): 1994 | """Start catching keys. Used for special commands (e.g. "f", "r"). 1995 | 1996 | amount (int): amount of keys to catch. 1997 | callback (str): name of method to call once all keys are caught. 1998 | input_line (str): input line's content. 1999 | cur (int): cursor's position. 2000 | count (int): count, e.g. "2" for "2fs". 2001 | buf (str, optional): pointer to the current WeeChat buffer. 2002 | Defaults to None. 2003 | 2004 | `catching_keys_data` is a dict with the above arguments, as well as: 2005 | keys (str): pressed keys will be added under this key. 2006 | new_cur (int): the new cursor's position, set in the callback. 2007 | 2008 | When catching keys is active, normal pressed keys (e.g. "a" but not arrows) 2009 | will get added to `catching_keys_data` under the key "keys", and will not 2010 | be handled any further. 2011 | Once all keys are caught, the method defined in the "callback" key is 2012 | called, and can use the data in `catching_keys_data` to perform its action. 2013 | """ 2014 | global catching_keys_data 2015 | if "new_cur" in catching_keys_data: 2016 | new_cur = catching_keys_data['new_cur'] 2017 | catching_keys_data = {'amount': 0} 2018 | return cur, new_cur, True, False 2019 | catching_keys_data = ({'amount': amount, 2020 | 'callback': callback, 2021 | 'input_line': input_line, 2022 | 'cur': cur, 2023 | 'keys': "", 2024 | 'count': count, 2025 | 'new_cur': 0, 2026 | 'buf': buf}) 2027 | return cur, cur, False, True 2028 | 2029 | def get_keys_and_count(combo): 2030 | """Check if `combo` is a valid combo and extract keys/counts if so. 2031 | 2032 | Args: 2033 | combo (str): pressed keys combo. 2034 | 2035 | Returns: 2036 | matched (bool): True if the combo has a (partial or full) match, False 2037 | otherwise. 2038 | combo (str): `combo` with the count removed. These are the actual keys 2039 | we should handle. User mappings are also expanded. 2040 | count (int): count for `combo`. 2041 | """ 2042 | # Look for a potential match (e.g. "d" might become "dw" or "dd" so we 2043 | # accept it, but "d9" is invalid). 2044 | matched = False 2045 | # Digits are allowed at the beginning (counts or "0"). 2046 | count = 0 2047 | if combo.isdigit(): 2048 | matched = True 2049 | elif combo and combo[0].isdigit(): 2050 | count = "" 2051 | for char in combo: 2052 | if char.isdigit(): 2053 | count += char 2054 | else: 2055 | break 2056 | combo = combo.replace(count, "", 1) 2057 | count = int(count) 2058 | # It's a WeeChat command. 2059 | if not matched and combo.startswith("/"): 2060 | matched = True 2061 | # Check against defined keys. 2062 | if not matched: 2063 | for key in VI_KEYS: 2064 | if key.startswith(combo): 2065 | matched = True 2066 | break 2067 | # Check against defined motions. 2068 | if not matched: 2069 | for motion in VI_MOTIONS: 2070 | if motion.startswith(combo): 2071 | matched = True 2072 | break 2073 | # Check against defined operators + motions. 2074 | if not matched: 2075 | for operator in VI_OPERATORS: 2076 | if combo.startswith(operator): 2077 | # Check for counts before the motion (but after the operator). 2078 | vi_keys_no_op = combo[len(operator):] 2079 | # There's no motion yet. 2080 | if vi_keys_no_op.isdigit(): 2081 | matched = True 2082 | break 2083 | # Get the motion count, then multiply the operator count by 2084 | # it, similar to vim's behavior. 2085 | elif vi_keys_no_op and vi_keys_no_op[0].isdigit(): 2086 | motion_count = "" 2087 | for char in vi_keys_no_op: 2088 | if char.isdigit(): 2089 | motion_count += char 2090 | else: 2091 | break 2092 | # Remove counts from `vi_keys_no_op`. 2093 | combo = combo.replace(motion_count, "", 1) 2094 | motion_count = int(motion_count) 2095 | count = max(count, 1) * motion_count 2096 | # Check against defined motions. 2097 | for motion in VI_MOTIONS: 2098 | if motion.startswith(combo[1:]): 2099 | matched = True 2100 | break 2101 | return matched, combo, count 2102 | 2103 | 2104 | # Other helpers. 2105 | # -------------- 2106 | def set_mode(arg): 2107 | """Set the current mode and update the bar mode indicator.""" 2108 | global mode 2109 | buf = weechat.current_buffer() 2110 | input_line = weechat.buffer_get_string(buf, "input") 2111 | if mode == "INSERT" and arg == "NORMAL": 2112 | add_undo_history(buf, input_line) 2113 | mode = arg 2114 | # If we're going to Normal mode, the cursor must move one character to the 2115 | # left. 2116 | if mode == "NORMAL": 2117 | cur = weechat.buffer_get_integer(buf, "input_pos") 2118 | set_cur(buf, input_line, cur - 1, False) 2119 | weechat.bar_item_update("mode_indicator") 2120 | 2121 | def cb_check_cmd_mode(data, remaining_calls): 2122 | """Exit command mode if user erases the leading ':' character.""" 2123 | buf = weechat.current_buffer() 2124 | cmd_text = weechat.buffer_get_string(buf, "input") 2125 | if not cmd_text: 2126 | set_mode("NORMAL") 2127 | return weechat.WEECHAT_RC_OK 2128 | 2129 | def add_undo_history(buf, input_line): 2130 | """Add an item to the per-buffer undo history.""" 2131 | if buf in undo_history: 2132 | if not undo_history[buf] or undo_history[buf][-1] != input_line: 2133 | undo_history[buf].append(input_line) 2134 | undo_history_index[buf] = -1 2135 | else: 2136 | undo_history[buf] = ['', input_line] 2137 | undo_history_index[buf] = -1 2138 | 2139 | def clear_undo_history(buf): 2140 | """Clear the undo history for a given buffer.""" 2141 | undo_history[buf] = [''] 2142 | undo_history_index[buf] = -1 2143 | 2144 | def print_warning(text): 2145 | """Print warning, in red, to the current buffer.""" 2146 | buf = weechat.current_buffer() 2147 | weechat.prnt(buf, ("%s[vimode.py] %s" % (weechat.color("red"), text))) 2148 | 2149 | def check_warnings(): 2150 | """Warn the user about problematic key bindings and tmux/screen.""" 2151 | user_warned = False 2152 | # Warn the user about problematic key bindings that may conflict with 2153 | # vimode. 2154 | # The solution is to remove these key bindings, but that's up to the user. 2155 | infolist = weechat.infolist_get("key", "", "default") 2156 | problematic_keybindings = [] 2157 | while weechat.infolist_next(infolist): 2158 | key = weechat.infolist_string(infolist, "key") 2159 | command = weechat.infolist_string(infolist, "command") 2160 | if re.match(REGEX_PROBLEMATIC_KEYBINDINGS, key): 2161 | problematic_keybindings.append("%s -> %s" % (key, command)) 2162 | weechat.infolist_free(infolist) 2163 | if problematic_keybindings: 2164 | user_warned = True 2165 | print_warning("Problematic keybindings detected:") 2166 | for keybinding in problematic_keybindings: 2167 | print_warning(" %s" % keybinding) 2168 | print_warning("These keybindings may conflict with vimode.") 2169 | print_warning("You can remove problematic key bindings and add" 2170 | " recommended ones by using /vimode bind_keys, or only" 2171 | " list them with /vimode bind_keys --list") 2172 | print_warning("For help, see: %s" % FAQ_KEYBINDINGS) 2173 | del problematic_keybindings 2174 | # Warn tmux/screen users about possible Esc detection delays. 2175 | if "STY" in os.environ or "TMUX" in os.environ: 2176 | if user_warned: 2177 | weechat.prnt("", "") 2178 | user_warned = True 2179 | print_warning("tmux/screen users, see: %s" % FAQ_ESC) 2180 | if (user_warned and not 2181 | weechat.config_string_to_boolean(vimode_settings['no_warn'])): 2182 | if user_warned: 2183 | weechat.prnt("", "") 2184 | print_warning("To force disable warnings, you can set" 2185 | " plugins.var.python.vimode.no_warn to 'on'") 2186 | 2187 | 2188 | # Main script. 2189 | # ============ 2190 | 2191 | if __name__ == "__main__": 2192 | weechat.register(SCRIPT_NAME, SCRIPT_AUTHOR, SCRIPT_VERSION, 2193 | SCRIPT_LICENSE, SCRIPT_DESC, "", "") 2194 | # Warn the user if he's using an unsupported WeeChat version. 2195 | VERSION = weechat.info_get("version_number", "") 2196 | if int(VERSION) < 0x01000000: 2197 | print_warning("Please upgrade to WeeChat ≥ 1.0.0. Previous versions" 2198 | " are not supported.") 2199 | # Set up script options. 2200 | for option, value in list(vimode_settings.items()): 2201 | if weechat.config_is_set_plugin(option): 2202 | vimode_settings[option] = weechat.config_get_plugin(option) 2203 | else: 2204 | weechat.config_set_plugin(option, value[0]) 2205 | vimode_settings[option] = value[0] 2206 | weechat.config_set_desc_plugin(option, 2207 | "%s (default: \"%s\")" % (value[1], 2208 | value[0])) 2209 | load_user_mappings() 2210 | load_mode_colors() 2211 | load_is_keyword_regexes() 2212 | # Warn the user about possible problems if necessary. 2213 | if not weechat.config_string_to_boolean(vimode_settings['no_warn']): 2214 | check_warnings() 2215 | # Create bar items and setup hooks. 2216 | weechat.bar_item_new("mode_indicator", "cb_mode_indicator", "") 2217 | weechat.bar_item_new("cmd_completion", "cb_cmd_completion", "") 2218 | weechat.bar_item_new("vi_buffer", "cb_vi_buffer", "") 2219 | weechat.bar_item_new("line_numbers", "cb_line_numbers", "") 2220 | if int(VERSION) >= 0x02090000: 2221 | weechat.bar_new("vi_line_numbers", "on", "0", "window", "", "left", 2222 | "vertical", "vertical", "0", "0", "default", "default", 2223 | "default", "default", "0", "line_numbers") 2224 | else: 2225 | weechat.bar_new("vi_line_numbers", "on", "0", "window", "", "left", 2226 | "vertical", "vertical", "0", "0", "default", "default", 2227 | "default", "0", "line_numbers") 2228 | weechat.hook_config("plugins.var.python.%s.*" % SCRIPT_NAME, "cb_config", 2229 | "") 2230 | weechat.hook_signal("key_pressed", "cb_key_pressed", "") 2231 | weechat.hook_signal("key_combo_default", "cb_key_combo_default", "") 2232 | weechat.hook_signal("key_combo_search", "cb_key_combo_search", "") 2233 | weechat.hook_signal("buffer_switch", "cb_update_line_numbers", "") 2234 | weechat.hook_command("vimode", SCRIPT_DESC, "[help | bind_keys [--list]]", 2235 | " help: show help\n" 2236 | "bind_keys: unbind problematic keys, and bind" 2237 | " recommended keys to use in WeeChat\n" 2238 | " --list: only list changes", 2239 | "help || bind_keys |--list", 2240 | "cb_vimode_cmd", "") 2241 | weechat.hook_command("vimode_go_to_normal", 2242 | ("This command can be used for key bindings to go to " 2243 | "normal mode."), 2244 | "", "", "", "cb_vimode_go_to_normal", "") 2245 | # Remove obsolete bar. 2246 | vi_cmd_bar = weechat.bar_search("vi_cmd") 2247 | weechat.bar_remove(vi_cmd_bar) 2248 | --------------------------------------------------------------------------------