├── .gitignore ├── Makefile ├── README.md ├── LICENSE └── vi.c /.gitignore: -------------------------------------------------------------------------------- 1 | vi 2 | .o 3 | 4 | -------------------------------------------------------------------------------- /Makefile: -------------------------------------------------------------------------------- 1 | 2 | # CC = gcc 3 | # Set CC to your target's 'C' compiler to build for it 4 | # Example: 5 | # make CC=/arm/bin/gcc clean vi 6 | #DEBUG = -DCONFIG_FEATURE_VI_CRASHME 7 | CPPFLAGS = -DSTANDALONE $(DEBUG) 8 | CFLAGS = -Wall -Os -s 9 | 10 | # LD = gcc 11 | LDFLAGS = $(DEBUG) 12 | LDLIBS = 13 | 14 | vi : vi.c Makefile 15 | $(CC) $(CPPFLAGS) $(CFLAGS) vi.c -o vi 16 | 17 | clean: 18 | rm -f vi 19 | 20 | distclean: clean 21 | 22 | realclean: distclean 23 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | viless: A tiny vi text editor clone with enough features to be truly useful 2 | 3 | 4 | Adapted to run on bare metal: https://raymii.org/s/blog/Bare_Metal_Boot_to_Vi.html 5 | 6 | ~30 Kbyte executable size (32-bit ARM Linux gcc) 7 | 8 | Copyright (C) 2000, 2001 Sterling Huxley 9 | 10 | Revised: 5/18/20 by Brent Roman 11 | 12 | Licensed under the GPL v2 or later 13 | 14 |
15 | Lifted from BusyBox 1.21
16 | Modified to build stand-alone, fix bugs, improve status line display
17 | 30 Kb executable size on ARM with all features enabled
18 | Lacks support for regular expressions
19 | Implements only the most commonly used : commands
20 | 
21 | These features are available:
22 | 	Pattern searches with / and ?
23 | 	Last command repeat with '.'
24 | 	Line marking with 'x
25 | 	Named buffers with "x
26 | 	Readonly with -R command line arg
27 | 	Some colon mode commands with ':'
28 | 	Settable options with ":set"
29 | 	Signal catching- ^C
30 | 	Job suspend and resume with ^Z
31 | 	Adapt to window re-sizes
32 | 
33 | Things To Do:
34 | 	EXINIT
35 | 	$HOME/.exrc  and  ./.exrc
36 | 	add magic to search	/foo.*bar
37 | 	add :help command
38 | 	:map macros
39 | 	if mark[] values were line numbers rather than pointers
40 | 	   it would be easier to change the mark when add/delete lines
41 | 	More intelligence in refresh()
42 | 	":r !cmd"  and  "!cmd"  to filter text through an external command
43 | 	A true "undo" facility
44 | 	An "ex" line oriented mode- maybe using "cmdedit"
45 | 
46 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 2, June 1991 3 | 4 | Copyright (C) 1989, 1991 Free Software Foundation, Inc., 5 | 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA 6 | Everyone is permitted to copy and distribute verbatim copies 7 | of this license document, but changing it is not allowed. 8 | 9 | Preamble 10 | 11 | The licenses for most software are designed to take away your 12 | freedom to share and change it. By contrast, the GNU General Public 13 | License is intended to guarantee your freedom to share and change free 14 | software--to make sure the software is free for all its users. This 15 | General Public License applies to most of the Free Software 16 | Foundation's software and to any other program whose authors commit to 17 | using it. (Some other Free Software Foundation software is covered by 18 | the GNU Lesser General Public License instead.) You can apply it to 19 | your programs, too. 20 | 21 | When we speak of free software, we are referring to freedom, not 22 | price. Our General Public Licenses are designed to make sure that you 23 | have the freedom to distribute copies of free software (and charge for 24 | this service if you wish), that you receive source code or can get it 25 | if you want it, that you can change the software or use pieces of it 26 | in new free programs; and that you know you can do these things. 27 | 28 | To protect your rights, we need to make restrictions that forbid 29 | anyone to deny you these rights or to ask you to surrender the rights. 30 | These restrictions translate to certain responsibilities for you if you 31 | distribute copies of the software, or if you modify it. 32 | 33 | For example, if you distribute copies of such a program, whether 34 | gratis or for a fee, you must give the recipients all the rights that 35 | you have. You must make sure that they, too, receive or can get the 36 | source code. And you must show them these terms so they know their 37 | rights. 38 | 39 | We protect your rights with two steps: (1) copyright the software, and 40 | (2) offer you this license which gives you legal permission to copy, 41 | distribute and/or modify the software. 42 | 43 | Also, for each author's protection and ours, we want to make certain 44 | that everyone understands that there is no warranty for this free 45 | software. If the software is modified by someone else and passed on, we 46 | want its recipients to know that what they have is not the original, so 47 | that any problems introduced by others will not reflect on the original 48 | authors' reputations. 49 | 50 | Finally, any free program is threatened constantly by software 51 | patents. We wish to avoid the danger that redistributors of a free 52 | program will individually obtain patent licenses, in effect making the 53 | program proprietary. To prevent this, we have made it clear that any 54 | patent must be licensed for everyone's free use or not licensed at all. 55 | 56 | The precise terms and conditions for copying, distribution and 57 | modification follow. 58 | 59 | GNU GENERAL PUBLIC LICENSE 60 | TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 61 | 62 | 0. This License applies to any program or other work which contains 63 | a notice placed by the copyright holder saying it may be distributed 64 | under the terms of this General Public License. The "Program", below, 65 | refers to any such program or work, and a "work based on the Program" 66 | means either the Program or any derivative work under copyright law: 67 | that is to say, a work containing the Program or a portion of it, 68 | either verbatim or with modifications and/or translated into another 69 | language. (Hereinafter, translation is included without limitation in 70 | the term "modification".) Each licensee is addressed as "you". 71 | 72 | Activities other than copying, distribution and modification are not 73 | covered by this License; they are outside its scope. The act of 74 | running the Program is not restricted, and the output from the Program 75 | is covered only if its contents constitute a work based on the 76 | Program (independent of having been made by running the Program). 77 | Whether that is true depends on what the Program does. 78 | 79 | 1. You may copy and distribute verbatim copies of the Program's 80 | source code as you receive it, in any medium, provided that you 81 | conspicuously and appropriately publish on each copy an appropriate 82 | copyright notice and disclaimer of warranty; keep intact all the 83 | notices that refer to this License and to the absence of any warranty; 84 | and give any other recipients of the Program a copy of this License 85 | along with the Program. 86 | 87 | You may charge a fee for the physical act of transferring a copy, and 88 | you may at your option offer warranty protection in exchange for a fee. 89 | 90 | 2. You may modify your copy or copies of the Program or any portion 91 | of it, thus forming a work based on the Program, and copy and 92 | distribute such modifications or work under the terms of Section 1 93 | above, provided that you also meet all of these conditions: 94 | 95 | a) You must cause the modified files to carry prominent notices 96 | stating that you changed the files and the date of any change. 97 | 98 | b) You must cause any work that you distribute or publish, that in 99 | whole or in part contains or is derived from the Program or any 100 | part thereof, to be licensed as a whole at no charge to all third 101 | parties under the terms of this License. 102 | 103 | c) If the modified program normally reads commands interactively 104 | when run, you must cause it, when started running for such 105 | interactive use in the most ordinary way, to print or display an 106 | announcement including an appropriate copyright notice and a 107 | notice that there is no warranty (or else, saying that you provide 108 | a warranty) and that users may redistribute the program under 109 | these conditions, and telling the user how to view a copy of this 110 | License. (Exception: if the Program itself is interactive but 111 | does not normally print such an announcement, your work based on 112 | the Program is not required to print an announcement.) 113 | 114 | These requirements apply to the modified work as a whole. If 115 | identifiable sections of that work are not derived from the Program, 116 | and can be reasonably considered independent and separate works in 117 | themselves, then this License, and its terms, do not apply to those 118 | sections when you distribute them as separate works. But when you 119 | distribute the same sections as part of a whole which is a work based 120 | on the Program, the distribution of the whole must be on the terms of 121 | this License, whose permissions for other licensees extend to the 122 | entire whole, and thus to each and every part regardless of who wrote it. 123 | 124 | Thus, it is not the intent of this section to claim rights or contest 125 | your rights to work written entirely by you; rather, the intent is to 126 | exercise the right to control the distribution of derivative or 127 | collective works based on the Program. 128 | 129 | In addition, mere aggregation of another work not based on the Program 130 | with the Program (or with a work based on the Program) on a volume of 131 | a storage or distribution medium does not bring the other work under 132 | the scope of this License. 133 | 134 | 3. You may copy and distribute the Program (or a work based on it, 135 | under Section 2) in object code or executable form under the terms of 136 | Sections 1 and 2 above provided that you also do one of the following: 137 | 138 | a) Accompany it with the complete corresponding machine-readable 139 | source code, which must be distributed under the terms of Sections 140 | 1 and 2 above on a medium customarily used for software interchange; or, 141 | 142 | b) Accompany it with a written offer, valid for at least three 143 | years, to give any third party, for a charge no more than your 144 | cost of physically performing source distribution, a complete 145 | machine-readable copy of the corresponding source code, to be 146 | distributed under the terms of Sections 1 and 2 above on a medium 147 | customarily used for software interchange; or, 148 | 149 | c) Accompany it with the information you received as to the offer 150 | to distribute corresponding source code. (This alternative is 151 | allowed only for noncommercial distribution and only if you 152 | received the program in object code or executable form with such 153 | an offer, in accord with Subsection b above.) 154 | 155 | The source code for a work means the preferred form of the work for 156 | making modifications to it. For an executable work, complete source 157 | code means all the source code for all modules it contains, plus any 158 | associated interface definition files, plus the scripts used to 159 | control compilation and installation of the executable. However, as a 160 | special exception, the source code distributed need not include 161 | anything that is normally distributed (in either source or binary 162 | form) with the major components (compiler, kernel, and so on) of the 163 | operating system on which the executable runs, unless that component 164 | itself accompanies the executable. 165 | 166 | If distribution of executable or object code is made by offering 167 | access to copy from a designated place, then offering equivalent 168 | access to copy the source code from the same place counts as 169 | distribution of the source code, even though third parties are not 170 | compelled to copy the source along with the object code. 171 | 172 | 4. You may not copy, modify, sublicense, or distribute the Program 173 | except as expressly provided under this License. Any attempt 174 | otherwise to copy, modify, sublicense or distribute the Program is 175 | void, and will automatically terminate your rights under this License. 176 | However, parties who have received copies, or rights, from you under 177 | this License will not have their licenses terminated so long as such 178 | parties remain in full compliance. 179 | 180 | 5. You are not required to accept this License, since you have not 181 | signed it. However, nothing else grants you permission to modify or 182 | distribute the Program or its derivative works. These actions are 183 | prohibited by law if you do not accept this License. Therefore, by 184 | modifying or distributing the Program (or any work based on the 185 | Program), you indicate your acceptance of this License to do so, and 186 | all its terms and conditions for copying, distributing or modifying 187 | the Program or works based on it. 188 | 189 | 6. Each time you redistribute the Program (or any work based on the 190 | Program), the recipient automatically receives a license from the 191 | original licensor to copy, distribute or modify the Program subject to 192 | these terms and conditions. You may not impose any further 193 | restrictions on the recipients' exercise of the rights granted herein. 194 | You are not responsible for enforcing compliance by third parties to 195 | this License. 196 | 197 | 7. If, as a consequence of a court judgment or allegation of patent 198 | infringement or for any other reason (not limited to patent issues), 199 | conditions are imposed on you (whether by court order, agreement or 200 | otherwise) that contradict the conditions of this License, they do not 201 | excuse you from the conditions of this License. If you cannot 202 | distribute so as to satisfy simultaneously your obligations under this 203 | License and any other pertinent obligations, then as a consequence you 204 | may not distribute the Program at all. For example, if a patent 205 | license would not permit royalty-free redistribution of the Program by 206 | all those who receive copies directly or indirectly through you, then 207 | the only way you could satisfy both it and this License would be to 208 | refrain entirely from distribution of the Program. 209 | 210 | If any portion of this section is held invalid or unenforceable under 211 | any particular circumstance, the balance of the section is intended to 212 | apply and the section as a whole is intended to apply in other 213 | circumstances. 214 | 215 | It is not the purpose of this section to induce you to infringe any 216 | patents or other property right claims or to contest validity of any 217 | such claims; this section has the sole purpose of protecting the 218 | integrity of the free software distribution system, which is 219 | implemented by public license practices. Many people have made 220 | generous contributions to the wide range of software distributed 221 | through that system in reliance on consistent application of that 222 | system; it is up to the author/donor to decide if he or she is willing 223 | to distribute software through any other system and a licensee cannot 224 | impose that choice. 225 | 226 | This section is intended to make thoroughly clear what is believed to 227 | be a consequence of the rest of this License. 228 | 229 | 8. If the distribution and/or use of the Program is restricted in 230 | certain countries either by patents or by copyrighted interfaces, the 231 | original copyright holder who places the Program under this License 232 | may add an explicit geographical distribution limitation excluding 233 | those countries, so that distribution is permitted only in or among 234 | countries not thus excluded. In such case, this License incorporates 235 | the limitation as if written in the body of this License. 236 | 237 | 9. The Free Software Foundation may publish revised and/or new versions 238 | of the General Public License from time to time. Such new versions will 239 | be similar in spirit to the present version, but may differ in detail to 240 | address new problems or concerns. 241 | 242 | Each version is given a distinguishing version number. If the Program 243 | specifies a version number of this License which applies to it and "any 244 | later version", you have the option of following the terms and conditions 245 | either of that version or of any later version published by the Free 246 | Software Foundation. If the Program does not specify a version number of 247 | this License, you may choose any version ever published by the Free Software 248 | Foundation. 249 | 250 | 10. If you wish to incorporate parts of the Program into other free 251 | programs whose distribution conditions are different, write to the author 252 | to ask for permission. For software which is copyrighted by the Free 253 | Software Foundation, write to the Free Software Foundation; we sometimes 254 | make exceptions for this. Our decision will be guided by the two goals 255 | of preserving the free status of all derivatives of our free software and 256 | of promoting the sharing and reuse of software generally. 257 | 258 | NO WARRANTY 259 | 260 | 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY 261 | FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN 262 | OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES 263 | PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED 264 | OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF 265 | MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS 266 | TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE 267 | PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, 268 | REPAIR OR CORRECTION. 269 | 270 | 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 271 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR 272 | REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, 273 | INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING 274 | OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED 275 | TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY 276 | YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER 277 | PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE 278 | POSSIBILITY OF SUCH DAMAGES. 279 | 280 | END OF TERMS AND CONDITIONS 281 | 282 | How to Apply These Terms to Your New Programs 283 | 284 | If you develop a new program, and you want it to be of the greatest 285 | possible use to the public, the best way to achieve this is to make it 286 | free software which everyone can redistribute and change under these terms. 287 | 288 | To do so, attach the following notices to the program. It is safest 289 | to attach them to the start of each source file to most effectively 290 | convey the exclusion of warranty; and each file should have at least 291 | the "copyright" line and a pointer to where the full notice is found. 292 | 293 | 294 | Copyright (C) 295 | 296 | This program is free software; you can redistribute it and/or modify 297 | it under the terms of the GNU General Public License as published by 298 | the Free Software Foundation; either version 2 of the License, or 299 | (at your option) any later version. 300 | 301 | This program is distributed in the hope that it will be useful, 302 | but WITHOUT ANY WARRANTY; without even the implied warranty of 303 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 304 | GNU General Public License for more details. 305 | 306 | You should have received a copy of the GNU General Public License along 307 | with this program; if not, write to the Free Software Foundation, Inc., 308 | 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. 309 | 310 | Also add information on how to contact you by electronic and paper mail. 311 | 312 | If the program is interactive, make it output a short notice like this 313 | when it starts in an interactive mode: 314 | 315 | Gnomovision version 69, Copyright (C) year name of author 316 | Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 317 | This is free software, and you are welcome to redistribute it 318 | under certain conditions; type `show c' for details. 319 | 320 | The hypothetical commands `show w' and `show c' should show the appropriate 321 | parts of the General Public License. Of course, the commands you use may 322 | be called something other than `show w' and `show c'; they could even be 323 | mouse-clicks or menu items--whatever suits your program. 324 | 325 | You should also get your employer (if you work as a programmer) or your 326 | school, if any, to sign a "copyright disclaimer" for the program, if 327 | necessary. Here is a sample; alter the names: 328 | 329 | Yoyodyne, Inc., hereby disclaims all copyright interest in the program 330 | `Gnomovision' (which makes passes at compilers) written by James Hacker. 331 | 332 | , 1 April 1989 333 | Ty Coon, President of Vice 334 | 335 | This General Public License does not permit incorporating your program into 336 | proprietary programs. If your program is a subroutine library, you may 337 | consider it more useful to permit linking proprietary applications with the 338 | library. If this is what you want to do, use the GNU Lesser General 339 | Public License instead of this License. 340 | -------------------------------------------------------------------------------- /vi.c: -------------------------------------------------------------------------------- 1 | /* vi: set sw=4 ts=4: */ 2 | /* 3 | * tiny vi.c: A small 'vi' clone 4 | * Copyright (C) 2000, 2001 Sterling Huxley 5 | * 6 | * Licensed under the GPL v2 or later, see the file LICENSE in this tarball. 7 | * Revised: 4/23/20 brent@mbari.org -- NULL ptr deref on missing previous regex 8 | * Revised: 5/21/20 brent@mbari.org -- extensive rework 9 | */ 10 | 11 | /* 12 | * Things To Do: 13 | * EXINIT 14 | * $HOME/.exrc and ./.exrc 15 | * add magic to search /foo.*bar 16 | * add :help command 17 | * :map macros 18 | * if mark[] values were line numbers rather than pointers 19 | * it would be easier to change the mark when add/delete lines 20 | * More intelligence in refresh() 21 | * ":r !cmd" and "!cmd" to filter text through an external command 22 | * A true "undo" facility 23 | * An "ex" line oriented mode- maybe using "cmdedit" 24 | */ 25 | 26 | #define STANDALONE 27 | 28 | 29 | 30 | #ifdef STANDALONE 31 | #define BB_VER "version 2.62" 32 | #define BB_BT "brent@mbari.org" 33 | 34 | #define _GNU_SOURCE 35 | 36 | #define vi_main main 37 | #define CONFIG_FEATURE_VI_MAX_LEN 4096 38 | #define ENABLE_FEATURE_VI_COLON 1 39 | #define ENABLE_FEATURE_VI_YANKMARK 1 40 | #define ENABLE_FEATURE_VI_SEARCH 1 41 | #define ENABLE_FEATURE_VI_USE_SIGNALS 1 42 | #define ENABLE_FEATURE_VI_DOT_CMD 1 43 | #define ENABLE_FEATURE_VI_READONLY 1 44 | #define ENABLE_FEATURE_VI_SETOPTS 1 45 | #define ENABLE_FEATURE_VI_SET 1 46 | #define ENABLE_FEATURE_VI_WIN_RESIZE 1 47 | #define ENABLE_LOCALE_SUPPORT 1 48 | #define ENABLE_FEATURE_VI_8BIT 1 49 | #define ENABLE_FEATURE_VI_YANKMARK 1 50 | #define ENABLE_FEATURE_VI_SEARCH 1 51 | #define ENABLE_FEATURE_ALLOW_EXEC 1 52 | #undef ENABLE_FEATURE_VI_OPTIMIZE_CURSOR 53 | 54 | #define USE_FEATURE_VI_COLON(...) __VA_ARGS__ 55 | #define USE_FEATURE_VI_READONLY(...) __VA_ARGS__ 56 | #define USE_FEATURE_VI_YANKMARK(...) __VA_ARGS__ 57 | #define USE_FEATURE_VI_SEARCH(...) __VA_ARGS__ 58 | 59 | #define ALIGN1 60 | #define FALSE 0 61 | #define TRUE 1 62 | #define MAIN_EXTERNALLY_VISIBLE 63 | #define ATTRIBUTE_UNUSED __attribute__ ((__unused__)) 64 | 65 | #undef isdigit 66 | #define isdigit(a) ((unsigned)((a) - '0') <= 9) 67 | 68 | #define ARRAY_SIZE(x) ((unsigned)(sizeof(x) / sizeof((x)[0]))) 69 | 70 | #define INIT_G() 71 | struct globals G; 72 | 73 | typedef signed char smallint; 74 | 75 | #define bb_show_usage() 76 | #define bb_perror_msg(msg) perror(msg) 77 | 78 | // To test editor using CRASHME: 79 | // vi -C filename 80 | // To stop testing, wait until all to text[] is deleted, or 81 | // Ctrl-Z and kill -9 %1 82 | // while in the editor Ctrl-T will toggle the crashme function on and off. 83 | //#define CONFIG_FEATURE_VI_CRASHME // randomly pick commands to execute 84 | 85 | #else //in busybox 86 | 87 | #include "libbb.h" 88 | #define G (*ptr_to_globals) 89 | #define INIT_G() do { \ 90 | SET_PTR_TO_GLOBALS(xzalloc(sizeof(G))); \ 91 | last_file_modified = -1; \ 92 | } while (0) 93 | 94 | #endif 95 | 96 | /* the CRASHME code is unmaintained, and doesn't currently build */ 97 | #define ENABLE_FEATURE_VI_CRASHME 0 98 | 99 | 100 | #if ENABLE_LOCALE_SUPPORT 101 | 102 | #if ENABLE_FEATURE_VI_8BIT 103 | #define Isprint(c) isprint(c) 104 | #else 105 | #define Isprint(c) (isprint(c) && (unsigned char)(c) < 0x7f) 106 | #endif 107 | 108 | #else 109 | 110 | /* 0x9b is Meta-ESC */ 111 | #if ENABLE_FEATURE_VI_8BIT 112 | #define Isprint(c) ((unsigned char)(c) >= ' ' && (c) != 0x7f && (unsigned char)(c) != 0x9b) 113 | #else 114 | #define Isprint(c) ((unsigned char)(c) >= ' ' && (unsigned char)(c) < 0x7f) 115 | #endif 116 | 117 | #endif 118 | 119 | #if ENABLE_FEATURE_VI_READONLY 120 | #define EDIT_STATUS "%s: %s%s%s line %d/%d %d%%" 121 | #else 122 | #define EDIT_STATUS "%s: %s%s line %d/%d %d%%" 123 | #endif 124 | 125 | enum { 126 | MAX_TABSTOP = 32, // sanity limit 127 | // User input len. Need not be extra big. 128 | // Lines in file being edited *can* be bigger than this. 129 | MAX_INPUT_LEN = 128, 130 | // Sanity limits. We have only one buffer of this size. 131 | MAX_SCR_COLS = CONFIG_FEATURE_VI_MAX_LEN, 132 | MAX_SCR_ROWS = CONFIG_FEATURE_VI_MAX_LEN, 133 | }; 134 | 135 | // Misc. non-Ascii keys that report an escape sequence 136 | #define VI_K_UP (char)128 // cursor key Up 137 | #define VI_K_DOWN (char)129 // cursor key Down 138 | #define VI_K_RIGHT (char)130 // Cursor Key Right 139 | #define VI_K_LEFT (char)131 // cursor key Left 140 | #define VI_K_HOME (char)132 // Cursor Key Home 141 | #define VI_K_END (char)133 // Cursor Key End 142 | #define VI_K_INSERT (char)134 // Cursor Key Insert 143 | #define VI_K_DELETE (char)135 // Cursor Key Insert 144 | #define VI_K_PAGEUP (char)136 // Cursor Key Page Up 145 | #define VI_K_PAGEDOWN (char)137 // Cursor Key Page Down 146 | #define VI_K_FUN1 (char)138 // Function Key F1 147 | #define VI_K_FUN2 (char)139 // Function Key F2 148 | #define VI_K_FUN3 (char)140 // Function Key F3 149 | #define VI_K_FUN4 (char)141 // Function Key F4 150 | #define VI_K_FUN5 (char)142 // Function Key F5 151 | #define VI_K_FUN6 (char)143 // Function Key F6 152 | #define VI_K_FUN7 (char)144 // Function Key F7 153 | #define VI_K_FUN8 (char)145 // Function Key F8 154 | #define VI_K_FUN9 (char)146 // Function Key F9 155 | #define VI_K_FUN10 (char)147 // Function Key F10 156 | #define VI_K_FUN11 (char)148 // Function Key F11 157 | #define VI_K_FUN12 (char)149 // Function Key F12 158 | 159 | /* vt102 typical ESC sequence */ 160 | /* terminal standout start/normal ESC sequence */ 161 | #define SOlen (4) //length of SO escape sequence 162 | static const char SOs[] ALIGN1 = "\033[7m"; 163 | static const char SOn[] ALIGN1 = "\033[0m"; 164 | /* terminal bell sequence */ 165 | static const char bell[] ALIGN1 = "\007"; 166 | /* Clear-end-of-line and Clear-end-of-screen ESC sequence */ 167 | static const char Ceol[] ALIGN1 = "\033[0K"; 168 | static const char Ceos[] ALIGN1 = "\033[0J"; 169 | /* Cursor motion arbitrary destination ESC sequence */ 170 | static const char CMrc[] ALIGN1 = "\033[%d;%dH"; 171 | #if ENABLE_FEATURE_VI_WIN_RESIZE 172 | /* Report cursor positon */ 173 | static const char CtextAreaQuery[] ALIGN1 = "\033[r\033[999;999H\033[6n"; 174 | #endif 175 | #ifdef ENABLE_FEATURE_VI_OPTIMIZE_CURSOR 176 | /* Cursor motion up and down ESC sequence */ 177 | static const char CMup[] ALIGN1 = "\033[A"; 178 | static const char CMdown[] ALIGN1 = "\n"; 179 | #endif 180 | 181 | 182 | enum { 183 | YANKONLY = FALSE, 184 | YANKDEL = TRUE, 185 | FORWARD = 1, // code depends on "1" for array index 186 | BACK = -1, // code depends on "-1" for array index 187 | LIMITED = 0, // how much of text[] in char_search 188 | FULL = 1, // how much of text[] in char_search 189 | 190 | S_BEFORE_WS = 1, // used in skip_thing() for moving "dot" 191 | S_TO_WS = 2, // used in skip_thing() for moving "dot" 192 | S_OVER_WS = 3, // used in skip_thing() for moving "dot" 193 | S_END_PUNCT = 4, // used in skip_thing() for moving "dot" 194 | S_END_ALNUM = 5, // used in skip_thing() for moving "dot" 195 | }; 196 | 197 | enum { //cmd_modes 198 | CMODE_COMMAND, 199 | CMODE_INSERT, 200 | CMODE_REPLACE, 201 | CMODES, 202 | CMODE_LINE_INPUT = 1<<4 203 | }; 204 | 205 | static const char *cmd_mode_indicator[] = 206 | {"COMMAND", "INSERT", "REPLACE", "?!?" }; 207 | 208 | /* vi.c expects chars to be unsigned. */ 209 | /* busybox build system provides that, but it's better */ 210 | /* to audit and fix the source */ 211 | 212 | struct globals { 213 | /* many references - keep near the top of globals */ 214 | char *text, *end; // pointers to the user data in memory 215 | char *dot; // where all the action takes place 216 | int text_size; // size of the allocated buffer 217 | 218 | /* the rest */ 219 | smallint vi_setops; 220 | #define VI_AUTOINDENT 1 221 | #define VI_SHOWMATCH 2 222 | #define VI_IGNORECASE 4 223 | #define VI_ERR_METHOD 8 224 | #define autoindent (vi_setops & VI_AUTOINDENT) 225 | #define showmatch (vi_setops & VI_SHOWMATCH ) 226 | #define ignorecase (vi_setops & VI_IGNORECASE) 227 | /* indicate error with beep or flash */ 228 | #define err_method (vi_setops & VI_ERR_METHOD) 229 | 230 | #if ENABLE_FEATURE_VI_READONLY 231 | smallint readonly_mode; 232 | #define SET_READONLY_FILE(flags) ((flags) |= 0x01) 233 | #define SET_READONLY_MODE(flags) ((flags) |= 0x02) 234 | #define UNSET_READONLY_FILE(flags) ((flags) &= 0xfe) 235 | #else 236 | #define SET_READONLY_FILE(flags) ((void)0) 237 | #define SET_READONLY_MODE(flags) ((void)0) 238 | #define UNSET_READONLY_FILE(flags) ((void)0) 239 | #endif 240 | 241 | smallint editing; // >0 while we are editing a file 242 | // [code audit says "can be 0 or 1 only"] 243 | smallint cmd_mode; // 0=command 1=insert 2=replace 244 | int file_modified; // buffer contents changed (counter, not flag!) 245 | int last_file_modified; // = -1; 246 | int fn_start; // index of first cmd line file name 247 | int save_argc; // how many file names on cmd line 248 | int cmdcnt; // repetition count 249 | unsigned rows, columns; // the terminal screen is this size 250 | int crow, ccol; // cursor is on Crow x Ccol 251 | int offset; // chars scrolled off the screen to the left 252 | char *current_filename; 253 | char *screenbegin; // index into text[], of top line on the screen 254 | char *screen; // pointer to the virtual screen buffer 255 | int screensize; // and its size 256 | int tabstop; 257 | char erase_char; // the users erase character 258 | char last_input_char; // last char read from user 259 | char last_forward_char; // last char searched for with 'f' 260 | 261 | #if ENABLE_FEATURE_VI_DOT_CMD 262 | smallint adding2q; // are we currently adding user input to q 263 | int lmc_len; // length of last_modifying_cmd 264 | char *ioq, *ioq_start; // pointer to string for get_one_char to "read" 265 | #endif 266 | #if ENABLE_FEATURE_VI_OPTIMIZE_CURSOR 267 | int last_row; // where the cursor was last moved to 268 | #endif 269 | #if ENABLE_FEATURE_VI_USE_SIGNALS || ENABLE_FEATURE_VI_CRASHME 270 | int my_pid; 271 | #endif 272 | #if ENABLE_FEATURE_VI_DOT_CMD || ENABLE_FEATURE_VI_YANKMARK 273 | char *modifying_cmds; // cmds that modify text[] 274 | #endif 275 | #if ENABLE_FEATURE_VI_SEARCH 276 | char *last_search_pattern; // last pattern from a '/' or '?' search 277 | #endif 278 | int chars_to_parse; 279 | /* former statics */ 280 | #if ENABLE_FEATURE_VI_YANKMARK 281 | char *edit_file__cur_line; 282 | #endif 283 | int refresh__old_offset; 284 | int format_edit_status__tot; 285 | 286 | /* a few references only */ 287 | #if ENABLE_FEATURE_VI_YANKMARK 288 | int YDreg, Ureg; // default delete register and orig line for "U" 289 | char *reg[28]; // named register a-z, "D", and "U" 0-25,26,27 290 | char *mark[28]; // user marks points somewhere in text[]- a-z and previous context '' 291 | char *context_start, *context_end; 292 | #endif 293 | #if ENABLE_FEATURE_VI_USE_SIGNALS 294 | sigjmp_buf restart; // catch_sig() 295 | #endif 296 | struct termios term_orig, term_vi; // remember what the cooked mode was 297 | unsigned ticsPerChar; //# of 100hz tics per character received 298 | #if ENABLE_FEATURE_VI_COLON 299 | char *initial_cmds[3]; // currently 2 entries, NULL terminated 300 | #endif 301 | // Should be just enough to hold a key sequence, 302 | // but CRASME mode uses it as generated command buffer too 303 | char readbuffer[128]; 304 | #define STATUS_BUFFER_LEN 200 305 | char status_buffer[STATUS_BUFFER_LEN]; // messages to the user 306 | char displayed_buffer[STATUS_BUFFER_LEN]; // displayed status 307 | #if ENABLE_FEATURE_VI_DOT_CMD 308 | char last_modifying_cmd[MAX_INPUT_LEN]; // last modifying cmd for "." 309 | #endif 310 | char get_input_line__buf[MAX_INPUT_LEN]; /* former static */ 311 | 312 | char scr_out_buf[MAX_SCR_COLS + MAX_TABSTOP * 2]; 313 | }; 314 | #define text (G.text ) 315 | #define text_size (G.text_size ) 316 | #define end (G.end ) 317 | #define dot (G.dot ) 318 | #define reg (G.reg ) 319 | 320 | #define vi_setops (G.vi_setops ) 321 | #define editing (G.editing ) 322 | #define cmd_mode (G.cmd_mode ) 323 | #define file_modified (G.file_modified ) 324 | #define last_file_modified (G.last_file_modified ) 325 | #define fn_start (G.fn_start ) 326 | #define save_argc (G.save_argc ) 327 | #define cmdcnt (G.cmdcnt ) 328 | #define rows (G.rows ) 329 | #define columns (G.columns ) 330 | #define crow (G.crow ) 331 | #define ccol (G.ccol ) 332 | #define offset (G.offset ) 333 | #define status_buffer (G.status_buffer ) 334 | #define displayed_buffer (G.displayed_buffer ) 335 | #define current_filename (G.current_filename ) 336 | #define screen (G.screen ) 337 | #define screensize (G.screensize ) 338 | #define screenbegin (G.screenbegin ) 339 | #define tabstop (G.tabstop ) 340 | #define erase_char (G.erase_char ) 341 | #define last_input_char (G.last_input_char ) 342 | #define last_forward_char (G.last_forward_char ) 343 | #if ENABLE_FEATURE_VI_READONLY 344 | #define readonly_mode (G.readonly_mode ) 345 | #else 346 | #define readonly_mode 0 347 | #endif 348 | #define adding2q (G.adding2q ) 349 | #define lmc_len (G.lmc_len ) 350 | #define ioq (G.ioq ) 351 | #define ioq_start (G.ioq_start ) 352 | #define last_row (G.last_row ) 353 | #define my_pid (G.my_pid ) 354 | #define modifying_cmds (G.modifying_cmds ) 355 | #define last_search_pattern (G.last_search_pattern) 356 | #define chars_to_parse (G.chars_to_parse ) 357 | 358 | #define edit_file__cur_line (G.edit_file__cur_line) 359 | #define refresh__old_offset (G.refresh__old_offset) 360 | #define format_edit_status__tot (G.format_edit_status__tot) 361 | 362 | #define YDreg (G.YDreg ) 363 | #define Ureg (G.Ureg ) 364 | #define mark (G.mark ) 365 | #define context_start (G.context_start ) 366 | #define context_end (G.context_end ) 367 | #define restart (G.restart ) 368 | #define term_orig (G.term_orig ) 369 | #define ticsPerChar (G.ticsPerChar ) 370 | #define term_vi (G.term_vi ) 371 | #define initial_cmds (G.initial_cmds ) 372 | #define readbuffer (G.readbuffer ) 373 | #define scr_out_buf (G.scr_out_buf ) 374 | #define last_modifying_cmd (G.last_modifying_cmd ) 375 | #define get_input_line__buf (G.get_input_line__buf) 376 | 377 | static int init_text_buffer(char *); // init from file or create new 378 | static void edit_file(char *); // edit one file 379 | static void do_cmd(char); // execute a command 380 | static int next_tabstop(int); 381 | static void sync_cursor(char *, int *, int *); // synchronize the screen cursor to dot 382 | static char *begin_line(char *); // return pointer to cur line B-o-l 383 | static char *end_line(char *); // return pointer to cur line E-o-l 384 | static char *prev_line(char *); // return pointer to prev line B-o-l 385 | static char *next_line(char *); // return pointer to next line B-o-l 386 | static char *end_screen(void); // get pointer to last char on screen 387 | static int count_lines(char *, char *); // count line from start to stop 388 | static char *find_line(int); // find begining of line #li 389 | static char *move_to_col(char *, int); // move "p" to column l 390 | static void dot_left(void); // move dot left- dont leave line 391 | static void dot_right(void); // move dot right- dont leave line 392 | static void dot_begin(void); // move dot to B-o-l 393 | static void dot_end(void); // move dot to E-o-l 394 | static void dot_next(void); // move dot to next line B-o-l 395 | static void dot_prev(void); // move dot to prev line B-o-l 396 | static void dot_scroll(int, int); // move the screen up or down 397 | static void dot_skip_over_ws(void); // move dot pat WS 398 | static void dot_delete(void); // delete the char at 'dot' 399 | static char *bound_dot(char *); // make sure text[0] <= P < "end" 400 | static char *new_screen(int, int); // malloc virtual screen memory 401 | static char *char_insert(char *, char); // insert the char c at 'p' 402 | static char *stupid_insert(char *, char); // stupidly insert the char c at 'p' 403 | static int find_range(char **, char **, char); // return pointers for an object 404 | static int st_test(char *, int, int, char *); // helper for skip_thing() 405 | static char *skip_thing(char *, int, int, int); // skip some object 406 | static char *find_pair(char *, char); // find matching pair () [] {} 407 | static char *text_hole_delete(char *, char *); // at "p", delete a 'size' byte hole 408 | static char *text_hole_make(char *, int); // at "p", make a 'size' byte hole 409 | static char *yank_delete(char *, char *, int, int); // yank text[] into register then delete 410 | static void show_help(void); // display some help info 411 | static int rawmode(void); // set "raw" mode on tty 412 | static void cookmode(void); // return to "cooked" mode on tty 413 | static int awaitInput(int); //for specified number of 1/100th seconds 414 | static char readit(void); // read (maybe cursor) key from stdin 415 | static char get_one_char(void); // read 1 char from stdin 416 | static int file_size(const char *); // what is the byte size of "fn" 417 | #if ENABLE_FEATURE_VI_READONLY 418 | static int file_insert(const char *, char *, int); 419 | #else 420 | static int file_insert(const char *, char *); 421 | #endif 422 | static int file_write(char *, char *, char *); 423 | #if !ENABLE_FEATURE_VI_OPTIMIZE_CURSOR 424 | #define place_cursor(a, b, optimize) place_cursor(a, b) 425 | #endif 426 | static void place_cursor(int, int, int); 427 | static void screen_erase(void); 428 | static void clear_to_eol(void); 429 | static void clear_to_eos(void); 430 | static void standout_start(void); // send "start reverse video" sequence 431 | static void standout_end(void); // send "end reverse video" sequence 432 | static void flash(int); // flash the terminal screen 433 | static void show_status_line(void); // put a message on the bottom line 434 | static void status_line(const char *, ...); // print to status buf 435 | static void status_line_bold(const char *, ...); 436 | static void not_implemented(const char *); // display "Not implemented" message 437 | static int format_edit_status(const char *fmt); //file status on status line 438 | static void redraw(void); // force a full screen refresh 439 | static char* format_line(char* /*, int*/); 440 | static void refresh(void); // update the terminal from screen[] 441 | 442 | static void Indicate_Error(void); // use flash or beep to indicate error 443 | #define indicate_error(c) Indicate_Error() 444 | static void Hit_Return(void); 445 | 446 | #if ENABLE_FEATURE_VI_SEARCH 447 | static char *char_search(char *, const char *, int, int); // search for pattern starting at p 448 | static int mycmp(const char *, const char *, int); // string cmp based in "ignorecase" 449 | #endif 450 | #if ENABLE_FEATURE_VI_COLON 451 | static char *get_one_address(char *, int *); // get colon addr, if present 452 | static char *get_address(char *, int *, int *); // get two colon addrs, if present 453 | static void colon(char *); // execute the "colon" mode cmds 454 | #endif 455 | #if ENABLE_FEATURE_VI_USE_SIGNALS 456 | static void winch_sig(int); // catch window size changes 457 | static void suspend_sig(int); // catch ctrl-Z 458 | static void catch_sig(int); // catch ctrl-C and alarm time-outs 459 | static void quit_sig(int); // catch QUIT, TERM, PIPE, or HUP 460 | #endif 461 | #if ENABLE_FEATURE_VI_DOT_CMD 462 | static void start_new_cmd_q(char); // new queue for command 463 | static void end_cmd_q(void); // stop saving input chars 464 | #else 465 | #define end_cmd_q() ((void)0) 466 | #endif 467 | #if ENABLE_FEATURE_VI_SETOPTS 468 | static void showmatching(char *); // show the matching pair () [] {} 469 | #endif 470 | #if ENABLE_FEATURE_VI_YANKMARK || (ENABLE_FEATURE_VI_COLON && ENABLE_FEATURE_VI_SEARCH) || ENABLE_FEATURE_VI_CRASHME 471 | static char *string_insert(char *, char *); // insert the string at 'p' 472 | #endif 473 | #if ENABLE_FEATURE_VI_YANKMARK 474 | static char *text_yank(char *, char *, int); // save copy of "p" into a register 475 | static char what_reg(void); // what is letter of current YDreg 476 | static void check_context(char); // remember context for '' command 477 | #endif 478 | #if ENABLE_FEATURE_VI_CRASHME 479 | static void crash_dummy(); 480 | static void crash_test(); 481 | static int crashme = 0; 482 | #endif 483 | 484 | 485 | #ifdef STANDALONE 486 | void *xmalloc(size_t size) 487 | { 488 | void *ptr = malloc(size); 489 | if (ptr) return ptr; 490 | perror("malloc"); 491 | exit(65); 492 | } 493 | 494 | void *xzalloc(size_t size) 495 | { 496 | return memset(xmalloc(size), 0, size); 497 | } 498 | 499 | void *xrealloc(void *old, size_t size) 500 | { 501 | void *ptr = realloc(old, size); 502 | if (ptr) return ptr; 503 | perror("realloc"); 504 | exit(68); 505 | } 506 | 507 | /* Find out if the last character of a string matches the one given. 508 | * Don't underrun the buffer if the string length is 0. 509 | */ 510 | char* last_char_is(const char *s, int c) 511 | { 512 | if (s && *s) { 513 | size_t sz = strlen(s) - 1; 514 | s += sz; 515 | if ( (unsigned char)*s == c) 516 | return (char*)s; 517 | } 518 | return NULL; 519 | } 520 | 521 | int bb_putchar(int ch) 522 | { 523 | return putc(ch, stdout); 524 | } 525 | 526 | /* Wrapper which restarts poll on EINTR or ENOMEM. 527 | * On other errors does perror("poll") and returns. 528 | * Warning! May take longer than timeout_ms to return! */ 529 | int safe_poll(struct pollfd *ufds, nfds_t nfds, int timeout) 530 | { 531 | while (1) { 532 | int n = poll(ufds, nfds, timeout); 533 | if (n >= 0) 534 | return n; 535 | /* Make sure we inch towards completion */ 536 | if (timeout > 0) 537 | timeout--; 538 | /* E.g. strace causes poll to return this */ 539 | if (errno == EINTR) 540 | continue; 541 | /* Kernel is very low on memory. Retry. */ 542 | /* I doubt many callers would handle this correctly! */ 543 | if (errno == ENOMEM) 544 | continue; 545 | bb_perror_msg("poll"); 546 | return n; 547 | } 548 | } 549 | 550 | ssize_t safe_read(int fd, void *buf, size_t count) 551 | { 552 | ssize_t n; 553 | 554 | do { 555 | n = read(fd, buf, count); 556 | } while (n < 0 && errno == EINTR); 557 | 558 | return n; 559 | } 560 | 561 | ssize_t safe_write(int fd, const void *buf, size_t count) 562 | { 563 | ssize_t n; 564 | 565 | do { 566 | n = write(fd, buf, count); 567 | } while (n < 0 && errno == EINTR); 568 | 569 | return n; 570 | } 571 | 572 | ssize_t full_write(int fd, const void *buf, size_t len) 573 | { 574 | ssize_t cc; 575 | ssize_t total; 576 | 577 | total = 0; 578 | 579 | while (len) { 580 | cc = safe_write(fd, buf, len); 581 | 582 | if (cc < 0) { 583 | if (total) { 584 | /* we already wrote some! */ 585 | /* user can do another write to know the error code */ 586 | return total; 587 | } 588 | return cc; /* write() returns -1 on failure. */ 589 | } 590 | 591 | total += cc; 592 | buf = ((const char *)buf) + cc; 593 | len -= cc; 594 | } 595 | 596 | return total; 597 | } 598 | #endif 599 | 600 | static void write1(const char *out) 601 | { 602 | fputs(out, stdout); 603 | } 604 | 605 | static void clear_screen(void) 606 | { 607 | place_cursor(0, 0, FALSE); // put cursor in correct place 608 | clear_to_eos(); // tell terminal to erase display 609 | } 610 | 611 | static void gracefulExit(void) 612 | { 613 | cookmode(); 614 | place_cursor(rows-1, 0, FALSE); // go to bottom of screen 615 | clear_to_eol(); // Erase to end of line 616 | fflush(stdout); 617 | } 618 | 619 | void clampScreenSize(void) 620 | { 621 | if (rows < 2) 622 | rows = 2; 623 | else if (rows > MAX_SCR_ROWS) 624 | rows = MAX_SCR_ROWS; 625 | if (columns < 2) 626 | columns = 2; 627 | else if (columns > MAX_SCR_COLS) 628 | columns = MAX_SCR_COLS; 629 | } 630 | 631 | #if ENABLE_FEATURE_VI_WIN_RESIZE 632 | static const char *snchr(const char *s, int c, size_t n) 633 | { 634 | while (n--) 635 | if (*s++ == c) return --s; 636 | return NULL; 637 | } 638 | 639 | static ssize_t 640 | readResponse(char *buf, size_t bufSize, int endByte) 641 | //read response from STDIN into buf until timeout or endByte received 642 | { 643 | size_t cursor = 0; 644 | while (cursor < bufSize) { 645 | if (!awaitInput(ticsPerChar+9)) 646 | return -ETIME; 647 | int r = safe_read(STDIN_FILENO, buf + cursor, bufSize - cursor); 648 | if (r <= 0) 649 | return r < 0 ? r : -EIO; 650 | if (snchr(buf+cursor, endByte, r)) 651 | return cursor + r; 652 | cursor += r; 653 | } 654 | return -E2BIG; 655 | } 656 | 657 | static void queueAnyInput(void) 658 | //add any pending user input to readbuffer 659 | { 660 | if (awaitInput(0)) { 661 | char *s = readbuffer + chars_to_parse; 662 | int r = safe_read(STDIN_FILENO, s, readbuffer+sizeof(readbuffer) - s); 663 | if (r > 0) 664 | chars_to_parse += r; 665 | } 666 | } 667 | 668 | void getScreenSize(void) 669 | // assigns width and height to best guess as to actual screen size 670 | // LINES and COLUMNS env vars take priority 671 | // If either missing, query the terminal using VT100 escape codes 672 | // If that fails, fall back to rows/cols info in the termios struct 673 | // rows and columns retain their previous values if all methods fail 674 | { 675 | struct winsize win = { 0, 0, 0, 0 }; 676 | const char *lines = getenv("LINES"); 677 | const char *cols = getenv("COLUMNS"); 678 | if (!lines || !cols) { //if either missing in the environment 679 | queueAnyInput(); 680 | if (!awaitInput(0)) { //can't query term if there's pending user input 681 | write1(CtextAreaQuery); 682 | char buf[16]; 683 | int rspLen = readResponse(buf, sizeof(buf)-1, 'R'); 684 | if (rspLen > 5 && buf[0]==27 && buf[1]=='[') { 685 | buf[rspLen]=0; //terminate response string 686 | char *term; 687 | unsigned long ul = strtoul(buf+2, &term, 10); 688 | if (*term == ';') { 689 | win.ws_row = ul; 690 | ul = strtoul(term+1, &term, 10); 691 | if (*term == 'R') { 692 | win.ws_col = ul; 693 | } 694 | } 695 | } 696 | } 697 | if (!win.ws_row || !win.ws_col) //try termios if textAreaQuery failed 698 | ioctl(STDIN_FILENO, TIOCGWINSZ, &win); 699 | } 700 | //environment variables trump all 701 | if (lines) 702 | rows = atoi(lines); 703 | else if (win.ws_row) 704 | rows = win.ws_row; 705 | if (cols) 706 | columns = atoi(cols); 707 | else if (win.ws_col) 708 | columns = win.ws_col; 709 | } 710 | #endif 711 | 712 | 713 | static void createScreen(void) 714 | { 715 | #if ENABLE_FEATURE_VI_WIN_RESIZE 716 | getScreenSize(); 717 | clampScreenSize(); 718 | #endif 719 | new_screen(rows, columns); // get memory for virtual screen 720 | } 721 | 722 | 723 | int vi_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE; 724 | int vi_main(int argc, char **argv) 725 | { 726 | int c; 727 | 728 | INIT_G(); 729 | rows = 24; 730 | columns = 80; 731 | #if !ENABLE_FEATURE_VI_WIN_RESIZE 732 | { //try to get terminal dimensions from environment 733 | char *txt = getenv("LINES"); 734 | if (txt) 735 | rows = atoi(txt); 736 | txt = getenv("COLUMNS"); 737 | if (txt) 738 | columns = atoi(txt); 739 | clampScreenSize(); 740 | } 741 | #endif 742 | 743 | #if ENABLE_FEATURE_VI_USE_SIGNALS || ENABLE_FEATURE_VI_CRASHME 744 | my_pid = getpid(); 745 | #endif 746 | #if ENABLE_FEATURE_VI_CRASHME 747 | srand((long) my_pid); 748 | #endif 749 | #ifdef NO_SUCH_APPLET_YET 750 | /* If we aren't "vi", we are "view" */ 751 | if (ENABLE_FEATURE_VI_READONLY && applet_name[2]) { 752 | SET_READONLY_MODE(readonly_mode); 753 | } 754 | #endif 755 | 756 | vi_setops = VI_AUTOINDENT | VI_SHOWMATCH | VI_IGNORECASE; 757 | #if ENABLE_FEATURE_VI_DOT_CMD || ENABLE_FEATURE_VI_YANKMARK 758 | modifying_cmds = "aAcCdDiIJoOpPrRsxX<>~"; // cmds modifying text[] 759 | #endif 760 | 761 | // 1- process $HOME/.exrc file (not inplemented yet) 762 | // 2- process EXINIT variable from environment 763 | // 3- process command line args 764 | #if ENABLE_FEATURE_VI_COLON 765 | { 766 | char *p = getenv("EXINIT"); 767 | if (p && *p) 768 | initial_cmds[0] = xstrndup(p, MAX_INPUT_LEN); 769 | } 770 | #endif 771 | while ((c = getopt(argc, argv, "hCRH-" USE_FEATURE_VI_COLON("c:"))) != -1) { 772 | switch (c) { 773 | #if ENABLE_FEATURE_VI_CRASHME 774 | case 'C': 775 | crashme = 1; 776 | break; 777 | #endif 778 | #if ENABLE_FEATURE_VI_READONLY 779 | case 'R': // Read-only flag 780 | SET_READONLY_MODE(readonly_mode); 781 | break; 782 | #endif 783 | #if ENABLE_FEATURE_VI_COLON 784 | case 'c': // cmd line vi command 785 | if (*optarg) 786 | initial_cmds[initial_cmds[0] != 0] = xstrndup(optarg, MAX_INPUT_LEN); 787 | break; 788 | #endif 789 | case 'H': 790 | case '-': 791 | show_help(); 792 | /* fall through */ 793 | default: 794 | bb_show_usage(); 795 | return 1; 796 | } 797 | } 798 | 799 | // The argv array can be used by the ":next" and ":rewind" commands 800 | // save optind. 801 | fn_start = optind; // remember first file name for :next and :rew 802 | save_argc = argc; 803 | 804 | //----- This is the main file handling loop -------------- 805 | if (optind >= argc) { 806 | edit_file(0); 807 | } else { 808 | for (; optind < argc; optind++) { 809 | edit_file(argv[optind]); 810 | } 811 | } 812 | //----------------------------------------------------------- 813 | 814 | return 0; 815 | } 816 | 817 | /* read text from file or create an empty buf */ 818 | /* will also update current_filename */ 819 | static int init_text_buffer(char *fn) 820 | { 821 | int rc; 822 | int size = file_size(fn); // file size. -1 means does not exist. 823 | 824 | /* allocate/reallocate text buffer */ 825 | free(text); 826 | text_size = size + 10240; 827 | screenbegin = dot = end = text = xzalloc(text_size); 828 | 829 | if (fn != current_filename) { 830 | free(current_filename); 831 | current_filename = xstrdup(fn); 832 | } 833 | if (size < 0) { 834 | // file dont exist. Start empty buf with dummy line 835 | char_insert(text, '\n'); 836 | rc = 0; 837 | } else { 838 | rc = file_insert(fn, text 839 | USE_FEATURE_VI_READONLY(, 1)); 840 | } 841 | file_modified = 0; 842 | last_file_modified = -1; 843 | #if ENABLE_FEATURE_VI_YANKMARK 844 | /* init the marks. */ 845 | memset(mark, 0, sizeof(mark)); 846 | #endif 847 | return rc; 848 | } 849 | 850 | static void edit_file(char *fn) 851 | { 852 | #if ENABLE_FEATURE_VI_YANKMARK 853 | #define cur_line edit_file__cur_line 854 | #endif 855 | char c; 856 | editing = 1; // 0 = exit, 1 = one file, 2 = multiple files 857 | if (rawmode()) { 858 | perror("vi"); 859 | exit(5); 860 | } 861 | createScreen(); 862 | init_text_buffer(fn); 863 | 864 | #if ENABLE_FEATURE_VI_YANKMARK 865 | YDreg = 26; // default Yank/Delete reg 866 | Ureg = 27; // hold orig line for "U" cmd 867 | mark[26] = mark[27] = text; // init "previous context" 868 | #endif 869 | 870 | last_forward_char = last_input_char = '\0'; 871 | crow = 0; 872 | ccol = 0; 873 | tabstop = 8; 874 | offset = 0; // no horizontal offset 875 | clear_screen(); 876 | 877 | #if ENABLE_FEATURE_VI_USE_SIGNALS 878 | catch_sig(0); 879 | sigsetjmp(restart, 1); 880 | signal(SIGWINCH, winch_sig); 881 | signal(SIGTSTP, suspend_sig); 882 | signal(SIGQUIT, quit_sig); 883 | signal(SIGTERM, quit_sig); 884 | signal(SIGPIPE, quit_sig); 885 | signal(SIGHUP, quit_sig); 886 | signal(SIGILL, quit_sig); 887 | signal(SIGSEGV, quit_sig); 888 | signal(SIGBUS, quit_sig); 889 | signal(SIGABRT, quit_sig); 890 | #endif 891 | 892 | cmd_mode = CMODE_COMMAND; 893 | cmdcnt = 0; 894 | c = '\0'; 895 | #if ENABLE_FEATURE_VI_DOT_CMD 896 | free(ioq_start); 897 | ioq = ioq_start = NULL; 898 | lmc_len = 0; 899 | adding2q = 0; 900 | #endif 901 | 902 | #if ENABLE_FEATURE_VI_COLON 903 | { 904 | char *p, *q; 905 | int n = 0; 906 | 907 | while ((p = initial_cmds[n])) { 908 | do { 909 | q = p; 910 | p = strchr(q, '\n'); 911 | if (p) 912 | while (*p == '\n') 913 | *p++ = '\0'; 914 | if (*q) 915 | colon(q); 916 | } while (p); 917 | free(initial_cmds[n]); 918 | initial_cmds[n] = NULL; 919 | n++; 920 | } 921 | } 922 | #endif 923 | 924 | //------This is the main Vi cmd handling loop ----------------------- 925 | while (editing > 0) { 926 | refresh(); 927 | #if ENABLE_FEATURE_VI_CRASHME 928 | if (crashme > 0) { 929 | if ((end - text) > 1) { 930 | crash_dummy(); // generate a random command 931 | } else { 932 | crashme = 0; 933 | dot = string_insert(text, // insert the string 934 | "\n\n##### Ran out of text to work on. #####\n\n"); 935 | } 936 | } 937 | #endif 938 | last_input_char = c = get_one_char(); // get a cmd from user 939 | *status_buffer=0; 940 | #if ENABLE_FEATURE_VI_YANKMARK 941 | // save a copy of the current line- for the 'U" command 942 | if (begin_line(dot) != cur_line) { 943 | cur_line = begin_line(dot); 944 | text_yank(begin_line(dot), end_line(dot), Ureg); 945 | } 946 | #endif 947 | #if ENABLE_FEATURE_VI_DOT_CMD 948 | // These are commands that change text[]. 949 | // Remember the input for the "." command 950 | if (!adding2q && ioq_start == NULL 951 | && strchr(modifying_cmds, c) 952 | ) { 953 | start_new_cmd_q(c); 954 | } 955 | #endif 956 | do_cmd(c); // execute the user command 957 | #if ENABLE_FEATURE_VI_CRASHME 958 | if (crashme > 0) 959 | crash_test(); // test editor variables 960 | #endif 961 | } 962 | //------------------------------------------------------------------- 963 | refresh(); 964 | gracefulExit(); 965 | #undef cur_line 966 | } 967 | 968 | //----- The Colon commands ------------------------------------- 969 | #if ENABLE_FEATURE_VI_COLON 970 | static char *get_one_address(char *p, int *addr) // get colon addr, if present 971 | { 972 | int st; 973 | char *q; 974 | USE_FEATURE_VI_YANKMARK(char c;) 975 | USE_FEATURE_VI_SEARCH(char *pat;) 976 | 977 | *addr = -1; // assume no addr 978 | if (*p == '.') { // the current line 979 | p++; 980 | q = begin_line(dot); 981 | *addr = count_lines(text, q); 982 | } 983 | #if ENABLE_FEATURE_VI_YANKMARK 984 | else if (*p == '\'') { // is this a mark addr 985 | p++; 986 | c = tolower(*p); 987 | p++; 988 | if (c >= 'a' && c <= 'z') { 989 | // we have a mark 990 | c = c - 'a'; 991 | q = mark[(unsigned char) c]; 992 | if (q != NULL) { // is mark valid 993 | *addr = count_lines(text, q); // count lines 994 | } 995 | } 996 | } 997 | #endif 998 | #if ENABLE_FEATURE_VI_SEARCH 999 | else if (*p == '/') { // a search pattern 1000 | q = strchrnul(++p, '/'); 1001 | pat = xstrndup(p, q - p); // save copy of pattern 1002 | p = q; 1003 | if (*p == '/') 1004 | p++; 1005 | q = char_search(dot, pat, FORWARD, FULL); 1006 | if (q != NULL) { 1007 | *addr = count_lines(text, q); 1008 | } 1009 | free(pat); 1010 | } 1011 | #endif 1012 | else if (*p == '$') { // the last line in file 1013 | p++; 1014 | q = begin_line(end - 1); 1015 | *addr = count_lines(text, q); 1016 | } else if (isdigit(*p)) { // specific line number 1017 | sscanf(p, "%d%n", addr, &st); 1018 | p += st; 1019 | } else { 1020 | // unrecognised address - assume -1 1021 | *addr = -1; 1022 | } 1023 | return p; 1024 | } 1025 | 1026 | static char *get_address(char *p, int *b, int *e) // get two colon addrs, if present 1027 | { 1028 | //----- get the address' i.e., 1,3 'a,'b ----- 1029 | // get FIRST addr, if present 1030 | while (isblank(*p)) 1031 | p++; // skip over leading spaces 1032 | if (*p == '%') { // alias for 1,$ 1033 | p++; 1034 | *b = 1; 1035 | *e = count_lines(text, end-1); 1036 | goto ga0; 1037 | } 1038 | p = get_one_address(p, b); 1039 | while (isblank(*p)) 1040 | p++; 1041 | if (*p == ',') { // is there a address separator 1042 | p++; 1043 | while (isblank(*p)) 1044 | p++; 1045 | // get SECOND addr, if present 1046 | p = get_one_address(p, e); 1047 | } 1048 | ga0: 1049 | while (isblank(*p)) 1050 | p++; // skip over trailing spaces 1051 | return p; 1052 | } 1053 | 1054 | #if ENABLE_FEATURE_VI_SET && ENABLE_FEATURE_VI_SETOPTS 1055 | static void setops(const char *args, const char *opname, int flg_no, 1056 | const char *short_opname, int opt) 1057 | { 1058 | const char *a = args + flg_no; 1059 | int l = strlen(opname) - 1; /* opname have + ' ' */ 1060 | 1061 | if (strncasecmp(a, opname, l) == 0 1062 | || strncasecmp(a, short_opname, 2) == 0 1063 | ) { 1064 | if (flg_no) 1065 | vi_setops &= ~opt; 1066 | else 1067 | vi_setops |= opt; 1068 | } 1069 | } 1070 | #endif 1071 | 1072 | #if ENABLE_FEATURE_VI_SETOPTS 1073 | // show the matching char of a pair, () [] {} 1074 | static void showmatching(char *p) 1075 | { 1076 | char *q, *save_dot; 1077 | 1078 | // we found half of a pair 1079 | q = find_pair(p, *p); // get loc of matching char 1080 | if (q == NULL) { 1081 | indicate_error('3'); // no matching char 1082 | } else { 1083 | // "q" now points to matching pair 1084 | save_dot = dot; // remember where we are 1085 | dot = q; // go to new loc 1086 | refresh(); // let the user see it 1087 | awaitInput(40); // give user some time 1088 | dot = save_dot; // go back to old loc 1089 | refresh(); 1090 | } 1091 | } 1092 | 1093 | static char *stpcopy(char *dest, const char *src) 1094 | { 1095 | while(*src) *dest++ = *src++; 1096 | *dest = 0; 1097 | return dest; 1098 | } 1099 | #endif /* FEATURE_VI_SETOPTS */ 1100 | 1101 | // buf must be no longer than MAX_INPUT_LEN! 1102 | static void colon(char *buf) 1103 | { 1104 | char c, *orig_buf, *buf1, *q, *r; 1105 | char *fn, cmd[MAX_INPUT_LEN], args[MAX_INPUT_LEN]; 1106 | int i, l, li, ch, b, e; 1107 | int useforce, forced = FALSE; 1108 | 1109 | // :3154 // if (-e line 3154) goto it else stay put 1110 | // :4,33w! foo // write a portion of buffer to file "foo" 1111 | // :w // write all of buffer to current file 1112 | // :q // quit 1113 | // :q! // quit- dont care about modified file 1114 | // :'a,'z!sort -u // filter block through sort 1115 | // :'f // goto mark "f" 1116 | // :'fl // list literal the mark "f" line 1117 | // :.r bar // read file "bar" into buffer before dot 1118 | // :/123/,/abc/d // delete lines from "123" line to "abc" line 1119 | // :/xyz/ // goto the "xyz" line 1120 | // :s/find/replace/ // substitute pattern "find" with "replace" 1121 | // :! // run then return 1122 | // 1123 | 1124 | if (!buf[0]) 1125 | goto vc1; 1126 | if (*buf == ':') 1127 | buf++; // move past the ':' 1128 | 1129 | li = ch = i = 0; 1130 | b = e = -1; 1131 | q = text; // assume 1,$ for the range 1132 | r = end - 1; 1133 | li = count_lines(text, end - 1); 1134 | fn = current_filename; 1135 | 1136 | // look for optional address(es) :. :1 :1,9 :'q,'a :% 1137 | buf = get_address(buf, &b, &e); 1138 | 1139 | // remember orig command line 1140 | orig_buf = buf; 1141 | 1142 | // get the COMMAND into cmd[] 1143 | buf1 = cmd; 1144 | while (*buf != '\0') { 1145 | if (isspace(*buf)) 1146 | break; 1147 | *buf1++ = *buf++; 1148 | } 1149 | *buf1 = '\0'; 1150 | // get any ARGuments 1151 | while (isblank(*buf)) 1152 | buf++; 1153 | strcpy(args, buf); 1154 | useforce = FALSE; 1155 | buf1 = last_char_is(cmd, '!'); 1156 | if (buf1) { 1157 | useforce = TRUE; 1158 | *buf1 = '\0'; // get rid of ! 1159 | } 1160 | if (b >= 0) { 1161 | // if there is only one addr, then the addr 1162 | // is the line number of the single line the 1163 | // user wants. So, reset the end 1164 | // pointer to point at end of the "b" line 1165 | q = find_line(b); // what line is #b 1166 | r = end_line(q); 1167 | li = 1; 1168 | } 1169 | if (e >= 0) { 1170 | // we were given two addrs. change the 1171 | // end pointer to the addr given by user. 1172 | r = find_line(e); // what line is #e 1173 | r = end_line(r); 1174 | li = e - b + 1; 1175 | } 1176 | // ------------ now look for the command ------------ 1177 | i = strlen(cmd); 1178 | if (i == 0) { // :123CR goto line #123 1179 | if (b >= 0) { 1180 | dot = find_line(b); // what line is #b 1181 | dot_skip_over_ws(); 1182 | } 1183 | } 1184 | #if ENABLE_FEATURE_ALLOW_EXEC 1185 | else if (strncmp(cmd, "!", 1) == 0) { // run a cmd 1186 | int retcode; 1187 | // :!ls run the 1188 | clear_screen(); 1189 | standout_start(); 1190 | write1(status_buffer+2); 1191 | standout_end(); 1192 | cookmode(); 1193 | write1("\n"); 1194 | retcode = system(orig_buf + 1) >> 8; // run the cmd 1195 | if (retcode) 1196 | printf("\nshell returned %i\n\n", retcode); 1197 | rawmode(); 1198 | Hit_Return(); // let user see results 1199 | } 1200 | #endif 1201 | else if (strncmp(cmd, "=", i) == 0) { // where is the address 1202 | if (b < 0) { // no addr given- use defaults 1203 | b = e = count_lines(text, dot); 1204 | } 1205 | status_line("%d", b); 1206 | } else if (strncasecmp(cmd, "delete", i) == 0) { // delete lines 1207 | if (b < 0) { // no addr given- use defaults 1208 | q = begin_line(dot); // assume .,. for the range 1209 | r = end_line(dot); 1210 | } 1211 | dot = yank_delete(q, r, 1, YANKDEL); // save, then delete lines 1212 | dot_skip_over_ws(); 1213 | } else if (strncasecmp(cmd, "edit", i) == 0) { // Edit a file 1214 | // don't edit, if the current file has been modified 1215 | if (file_modified && !useforce) { 1216 | status_line_bold("No write since last change (:edit! overrides)"); 1217 | goto vc1; 1218 | } 1219 | if (args[0]) { 1220 | // the user supplied a file name 1221 | fn = args; 1222 | } else if (current_filename && current_filename[0]) { 1223 | // no user supplied name- use the current filename 1224 | // fn = current_filename; was set by default 1225 | } else { 1226 | // no user file name, no current name- punt 1227 | status_line_bold("No current filename"); 1228 | goto vc1; 1229 | } 1230 | 1231 | if (init_text_buffer(fn) < 0) 1232 | goto vc1; 1233 | 1234 | #if ENABLE_FEATURE_VI_YANKMARK 1235 | if (Ureg >= 0 && Ureg < 28 && reg[Ureg] != 0) { 1236 | free(reg[Ureg]); // free orig line reg- for 'U' 1237 | reg[Ureg]= 0; 1238 | } 1239 | if (YDreg >= 0 && YDreg < 28 && reg[YDreg] != 0) { 1240 | free(reg[YDreg]); // free default yank/delete register 1241 | reg[YDreg]= 0; 1242 | } 1243 | #endif 1244 | // how many lines in text[]? 1245 | li = count_lines(text, end - 1); 1246 | status_line("\"%s\"%s" 1247 | USE_FEATURE_VI_READONLY("%s") 1248 | " %dL, %dC", current_filename, 1249 | (file_size(fn) < 0 ? " [New file]" : ""), 1250 | USE_FEATURE_VI_READONLY( 1251 | ((readonly_mode) ? " [Readonly]" : ""), 1252 | ) 1253 | li, ch); 1254 | } else if (strncasecmp(cmd, "file", i) == 0) { // what File is this 1255 | if (b != -1 || e != -1) { 1256 | not_implemented("No address allowed on this command"); 1257 | goto vc1; 1258 | } 1259 | if (args[0]) { 1260 | // user wants a new filename 1261 | free(current_filename); 1262 | current_filename = xstrdup(args); 1263 | } 1264 | } else if (strncasecmp(cmd, "features", i) == 0) { // what features are available 1265 | // print out values of all features 1266 | place_cursor(rows - 1, 0, FALSE); // go to Status line, bottom of screen 1267 | clear_to_eol(); // clear the line 1268 | cookmode(); 1269 | show_help(); 1270 | rawmode(); 1271 | Hit_Return(); 1272 | } else if (strncasecmp(cmd, "list", i) == 0) { // literal print line 1273 | if (b < 0) { // no addr given- use defaults 1274 | q = begin_line(dot); // assume .,. for the range 1275 | r = end_line(dot); 1276 | } 1277 | place_cursor(rows - 1, 0, FALSE); // go to Status line, bottom of screen 1278 | clear_to_eol(); // clear the line 1279 | puts("\r"); 1280 | for (; q <= r; q++) { 1281 | int c_is_no_print; 1282 | 1283 | c = *q; 1284 | c_is_no_print = (c & 0x80) && !Isprint(c); 1285 | if (c_is_no_print) { 1286 | c = '.'; 1287 | standout_start(); 1288 | } 1289 | if (c == '\n') { 1290 | write1("$\r"); 1291 | } else if (c < ' ' || c == 127) { 1292 | bb_putchar('^'); 1293 | if (c == 127) 1294 | c = '?'; 1295 | else 1296 | c += '@'; 1297 | } 1298 | bb_putchar(c); 1299 | if (c_is_no_print) 1300 | standout_end(); 1301 | } 1302 | Hit_Return(); 1303 | } else if (strncasecmp(cmd, "quit", i) == 0 // Quit 1304 | || strncasecmp(cmd, "next", i) == 0 // edit next file 1305 | ) { 1306 | if (useforce) { 1307 | // force end of argv list 1308 | if (*cmd == 'q') { 1309 | optind = save_argc; 1310 | } 1311 | editing = 0; 1312 | goto vc1; 1313 | } 1314 | // don't exit if the file been modified 1315 | if (file_modified) { 1316 | status_line_bold("No write since last change (:%s! overrides)", 1317 | (*cmd == 'q' ? "quit" : "next")); 1318 | goto vc1; 1319 | } 1320 | // are there other file to edit 1321 | if (*cmd == 'q' && optind < save_argc - 1) { 1322 | status_line_bold("%d more file to edit", (save_argc - optind - 1)); 1323 | goto vc1; 1324 | } 1325 | if (*cmd == 'n' && optind >= save_argc - 1) { 1326 | status_line_bold("No more files to edit"); 1327 | goto vc1; 1328 | } 1329 | editing = 0; 1330 | } else if (strncasecmp(cmd, "read", i) == 0) { // read file into text[] 1331 | fn = args; 1332 | if (!fn[0]) { 1333 | status_line_bold("No filename given"); 1334 | goto vc1; 1335 | } 1336 | if (b < 0) { // no addr given- use defaults 1337 | q = begin_line(dot); // assume "dot" 1338 | } 1339 | // read after current line- unless user said ":0r foo" 1340 | if (b != 0) 1341 | q = next_line(q); 1342 | ch = file_insert(fn, q USE_FEATURE_VI_READONLY(, 0)); 1343 | if (ch < 0) 1344 | goto vc1; // nothing was inserted 1345 | // how many lines in text[]? 1346 | li = count_lines(q, q + ch - 1); 1347 | status_line("\"%s\"" 1348 | USE_FEATURE_VI_READONLY("%s") 1349 | " %dL, %dC", fn, 1350 | USE_FEATURE_VI_READONLY((readonly_mode ? " [Readonly]" : ""),) 1351 | li, ch); 1352 | if (ch > 0) { 1353 | // if the insert is before "dot" then we need to update 1354 | if (q <= dot) 1355 | dot += ch; 1356 | file_modified++; 1357 | } 1358 | } else if (strncasecmp(cmd, "rewind", i) == 0) { // rewind cmd line args 1359 | if (file_modified && !useforce) { 1360 | status_line_bold("No write since last change (:rewind! overrides)"); 1361 | } else { 1362 | // reset the filenames to edit 1363 | optind = fn_start - 1; 1364 | editing = 0; 1365 | } 1366 | #if ENABLE_FEATURE_VI_SET 1367 | } else if (strncasecmp(cmd, "set", i) == 0) { // set or clear features 1368 | #if ENABLE_FEATURE_VI_SETOPTS 1369 | char *argp = args; 1370 | while (*argp) { 1371 | i = 0; // offset into args 1372 | if (strncasecmp(argp, "no", 2) == 0) 1373 | i = 2; // ":set noautoindent" 1374 | setops(argp, "autoindent ", i, "ai", VI_AUTOINDENT); 1375 | setops(argp, "flash ", i, "fl", VI_ERR_METHOD); 1376 | setops(argp, "ignorecase ", i, "ic", VI_IGNORECASE); 1377 | setops(argp, "showmatch ", i, "sm", VI_SHOWMATCH); 1378 | /* tabstopXXXX */ 1379 | if (strncasecmp(argp + i, "tabstop=%d ", 7) == 0) { 1380 | sscanf(strchr(argp + i, '='), "tabstop=%d" + 7, &ch); 1381 | if (ch > 0 && ch <= MAX_TABSTOP) 1382 | tabstop = ch; 1383 | } 1384 | while (*argp && *argp != ' ') 1385 | argp++; // skip to arg delimiter (i.e. blank) 1386 | while (*argp && *argp == ' ') 1387 | argp++; // skip all delimiting blanks 1388 | } 1389 | // display values of all options in status line 1390 | char *cursor = status_buffer; 1391 | *cursor = 0; 1392 | if (!autoindent) 1393 | cursor = stpcopy(cursor,"no"); 1394 | cursor = stpcopy(cursor,"autoindent "); 1395 | if (!err_method) 1396 | cursor = stpcopy(cursor,"no"); 1397 | cursor = stpcopy(cursor,"flash "); 1398 | if (!ignorecase) 1399 | cursor = stpcopy(cursor,"no"); 1400 | cursor = stpcopy(cursor,"ignorecase "); 1401 | if (!showmatch) 1402 | cursor = stpcopy(cursor,"no"); 1403 | cursor = stpcopy(cursor,"showmatch "); 1404 | cursor += printf(cursor,"tabstop=%d ", tabstop); 1405 | #endif /* FEATURE_VI_SETOPTS */ 1406 | #endif /* FEATURE_VI_SET */ 1407 | #if ENABLE_FEATURE_VI_SEARCH 1408 | } else if (strncasecmp(cmd, "s", 1) == 0) { // substitute a pattern with a replacement pattern 1409 | char *ls, *F, *R; 1410 | int gflag; 1411 | 1412 | // F points to the "find" pattern 1413 | // R points to the "replace" pattern 1414 | // replace the cmd line delimiters "/" with NULLs 1415 | gflag = 0; // global replace flag 1416 | c = orig_buf[1]; // what is the delimiter 1417 | F = orig_buf + 2; // start of "find" 1418 | R = strchr(F, c); // middle delimiter 1419 | if (!R) goto colon_s_fail; 1420 | if (R == F) { // use previous search pattern if no find pattern given 1421 | if (!(F = last_search_pattern)) 1422 | goto colon_no_regex; 1423 | F++; //ignore search direction 1424 | } 1425 | *R++ = '\0'; // terminate "find" 1426 | buf1 = strchr(R, c); 1427 | if (buf1) { //accept :s/foo/bar 1428 | *buf1++ = '\0'; // terminate "replace" 1429 | if (*buf1 == 'g') { // :s/foo/bar/g 1430 | buf1++; 1431 | gflag++; // turn on gflag 1432 | } 1433 | } 1434 | q = begin_line(q); 1435 | if (b < 0) { // maybe :s/foo/bar/ 1436 | q = begin_line(dot); // start with cur line 1437 | b = count_lines(text, q); // cur line number 1438 | } 1439 | if (e < 0) 1440 | e = b; // maybe :.s/foo/bar/ 1441 | for (i = b; i <= e; i++) { // so, :20,23 s \0 find \0 replace \0 1442 | ls = q; // orig line start 1443 | vc4: 1444 | buf1 = char_search(q, F, FORWARD, LIMITED); // search cur line only for "find" 1445 | if (buf1) { 1446 | // we found the "find" pattern - delete it 1447 | text_hole_delete(buf1, buf1 + strlen(F) - 1); 1448 | // inset the "replace" patern 1449 | string_insert(buf1, R); // insert the string 1450 | // check for "global" :s/foo/bar/g 1451 | if (gflag == 1) { 1452 | if ((buf1 + strlen(R)) < end_line(ls)) { 1453 | q = buf1 + strlen(R); 1454 | goto vc4; // don't let q move past cur line 1455 | } 1456 | } 1457 | } 1458 | q = next_line(ls); 1459 | } 1460 | #endif /* FEATURE_VI_SEARCH */ 1461 | } else if (strncasecmp(cmd, "version", i) == 0) { // show software version 1462 | status_line(BB_VER " " BB_BT); 1463 | } else if (strncasecmp(cmd, "write", i) == 0 // write text to file 1464 | || strncasecmp(cmd, "wq", i) == 0 1465 | || strncasecmp(cmd, "wn", i) == 0 1466 | || strncasecmp(cmd, "x", i) == 0 1467 | ) { 1468 | // is there a file name to write to? 1469 | if (args[0]) { 1470 | fn = args; 1471 | } 1472 | #if ENABLE_FEATURE_VI_READONLY 1473 | if (readonly_mode && !useforce) { 1474 | status_line_bold("\"%s\" File is read only", fn); 1475 | goto vc3; 1476 | } 1477 | #endif 1478 | // how many lines in text[]? 1479 | li = count_lines(q, r); 1480 | ch = r - q + 1; 1481 | // see if file exists- if not, its just a new file request 1482 | if (useforce) { 1483 | // if "fn" is not write-able, chmod u+w 1484 | // sprintf(syscmd, "chmod u+w %s", fn); 1485 | // system(syscmd); 1486 | forced = TRUE; 1487 | } 1488 | l = file_write(fn, q, r); 1489 | if (useforce && forced) { 1490 | // chmod u-w 1491 | // sprintf(syscmd, "chmod u-w %s", fn); 1492 | // system(syscmd); 1493 | forced = FALSE; 1494 | } 1495 | if (l < 0) { 1496 | if (l == -1) 1497 | status_line_bold("\"%s\" %s", fn, strerror(errno)); 1498 | } else { 1499 | status_line("\"%s\" %dL, %dC", fn, li, l); 1500 | if (q == text && r == end - 1 && l == ch) { 1501 | file_modified = 0; 1502 | last_file_modified = -1; 1503 | } 1504 | if ((cmd[0] == 'x' || cmd[1] == 'q' || cmd[1] == 'n' || 1505 | cmd[0] == 'X' || cmd[1] == 'Q' || cmd[1] == 'N') 1506 | && l == ch) { 1507 | editing = 0; 1508 | } 1509 | } 1510 | #if ENABLE_FEATURE_VI_READONLY 1511 | vc3:; 1512 | #endif 1513 | #if ENABLE_FEATURE_VI_YANKMARK 1514 | } else if (strncasecmp(cmd, "yank", i) == 0) { // yank lines 1515 | if (b < 0) { // no addr given- use defaults 1516 | q = begin_line(dot); // assume .,. for the range 1517 | r = end_line(dot); 1518 | } 1519 | text_yank(q, r, YDreg); 1520 | li = count_lines(q, r); 1521 | status_line("Yank %d lines (%d chars) into [%c]", 1522 | li, strlen(reg[YDreg]), what_reg()); 1523 | #endif 1524 | } else { 1525 | // cmd unknown 1526 | not_implemented(cmd); 1527 | } 1528 | vc1: 1529 | dot = bound_dot(dot); // make sure "dot" is valid 1530 | return; 1531 | #if ENABLE_FEATURE_VI_SEARCH 1532 | colon_s_fail: 1533 | status_line_bold(":s expression missing delimiters"); 1534 | return; 1535 | colon_no_regex: 1536 | status_line_bold ("No previous regular expression"); 1537 | #endif 1538 | } 1539 | 1540 | #endif /* FEATURE_VI_COLON */ 1541 | 1542 | static void Hit_Return(void) 1543 | { 1544 | char c; 1545 | 1546 | standout_start(); 1547 | write1("[Hit return to continue]"); 1548 | standout_end(); 1549 | while ((c = get_one_char()) != '\n' && c != '\r' && c != 27) 1550 | continue; 1551 | redraw(); 1552 | } 1553 | 1554 | static int next_tabstop(int col) 1555 | { 1556 | return col + ((tabstop - 1) - (col % tabstop)); 1557 | } 1558 | 1559 | //----- Synchronize the cursor to Dot -------------------------- 1560 | static void sync_cursor(char *d, int *row, int *col) 1561 | { 1562 | char *beg_cur; // begin and end of "d" line 1563 | char *tp; 1564 | int cnt, ro, co; 1565 | 1566 | beg_cur = begin_line(d); // first char of cur line 1567 | 1568 | if (beg_cur < screenbegin) { 1569 | // "d" is before top line on screen 1570 | // how many lines do we have to move 1571 | cnt = count_lines(beg_cur, screenbegin); 1572 | sc1: 1573 | screenbegin = beg_cur; 1574 | if (cnt > (rows - 1) / 2) { 1575 | // we moved too many lines. put "dot" in middle of screen 1576 | for (cnt = 0; cnt < (rows - 1) / 2; cnt++) { 1577 | screenbegin = prev_line(screenbegin); 1578 | } 1579 | } 1580 | } else { 1581 | char *end_scr; // begin and end of screen 1582 | end_scr = end_screen(); // last char of screen 1583 | if (beg_cur > end_scr) { 1584 | // "d" is after bottom line on screen 1585 | // how many lines do we have to move 1586 | cnt = count_lines(end_scr, beg_cur); 1587 | if (cnt > (rows - 1) / 2) 1588 | goto sc1; // too many lines 1589 | for (ro = 0; ro < cnt - 1; ro++) { 1590 | // move screen begin the same amount 1591 | screenbegin = next_line(screenbegin); 1592 | // now, move the end of screen 1593 | end_scr = next_line(end_scr); 1594 | end_scr = end_line(end_scr); 1595 | } 1596 | } 1597 | } 1598 | // "d" is on screen- find out which row 1599 | tp = screenbegin; 1600 | for (ro = 0; ro < rows - 1; ro++) { // drive "ro" to correct row 1601 | if (tp == beg_cur) 1602 | break; 1603 | tp = next_line(tp); 1604 | } 1605 | 1606 | // find out what col "d" is on 1607 | co = 0; 1608 | while (tp < d) { // drive "co" to correct column 1609 | if (*tp == '\n') //vda || *tp == '\0') 1610 | break; 1611 | if (*tp == '\t') { 1612 | // handle tabs like real vi 1613 | if (d == tp && (cmd_mode & CMODES) != CMODE_COMMAND) { 1614 | break; 1615 | } 1616 | co = next_tabstop(co); 1617 | } else if ((unsigned char)*tp < ' ' || *tp == 0x7f) { 1618 | co++; // display as ^X, use 2 columns 1619 | } 1620 | co++; 1621 | tp++; 1622 | } 1623 | 1624 | // "co" is the column where "dot" is. 1625 | // The screen has "columns" columns. 1626 | // The currently displayed columns are 0+offset -- columns+ofset 1627 | // |-------------------------------------------------------------| 1628 | // ^ ^ ^ 1629 | // offset | |------- columns ----------------| 1630 | // 1631 | // If "co" is already in this range then we do not have to adjust offset 1632 | // but, we do have to subtract the "offset" bias from "co". 1633 | // If "co" is outside this range then we have to change "offset". 1634 | // If the first char of a line is a tab the cursor will try to stay 1635 | // in column 7, but we have to set offset to 0. 1636 | 1637 | if (co < 0 + offset) { 1638 | offset = co; 1639 | } 1640 | if (co >= columns + offset) { 1641 | offset = co - columns + 1; 1642 | } 1643 | // if the first char of the line is a tab, and "dot" is sitting on it 1644 | // force offset to 0. 1645 | if (d == beg_cur && *d == '\t') { 1646 | offset = 0; 1647 | } 1648 | co -= offset; 1649 | 1650 | *row = ro; 1651 | *col = co; 1652 | } 1653 | 1654 | //----- Text Movement Routines --------------------------------- 1655 | static char *begin_line(char *p) // return pointer to first char cur line 1656 | { 1657 | if (p > text) { 1658 | p = memrchr(text, '\n', p - text); 1659 | if (!p) 1660 | return text; 1661 | return p + 1; 1662 | } 1663 | return p; 1664 | } 1665 | 1666 | static char *end_line(char *p) // return pointer to NL of cur line 1667 | { 1668 | if (p < end - 1) { 1669 | p = memchr(p, '\n', end - p - 1); 1670 | if (!p) 1671 | return end - 1; 1672 | } 1673 | return p; 1674 | } 1675 | 1676 | static char *dollar_line(char *p) // return pointer to just before NL line 1677 | { 1678 | p = end_line(p); 1679 | // Try to stay off of the Newline 1680 | if (*p == '\n' && (p - begin_line(p)) > 0) 1681 | p--; 1682 | return p; 1683 | } 1684 | 1685 | static char *prev_line(char *p) // return pointer first char prev line 1686 | { 1687 | p = begin_line(p); // goto begining of cur line 1688 | if (p > text && p[-1] == '\n') 1689 | p--; // step to prev line 1690 | p = begin_line(p); // goto begining of prev line 1691 | return p; 1692 | } 1693 | 1694 | static char *next_line(char *p) // return pointer first char next line 1695 | { 1696 | p = end_line(p); 1697 | if (p < end - 1 && *p == '\n') 1698 | p++; // step to next line 1699 | return p; 1700 | } 1701 | 1702 | //----- Text Information Routines ------------------------------ 1703 | static char *end_screen(void) 1704 | { 1705 | char *q; 1706 | int cnt; 1707 | 1708 | // find new bottom line 1709 | q = screenbegin; 1710 | for (cnt = 0; cnt < rows - 2; cnt++) 1711 | q = next_line(q); 1712 | q = end_line(q); 1713 | return q; 1714 | } 1715 | 1716 | // count line from start to stop 1717 | static int count_lines(char *start, char *stop) 1718 | { 1719 | char *q; 1720 | int cnt; 1721 | 1722 | if (stop < start) { // start and stop are backwards- reverse them 1723 | q = start; 1724 | start = stop; 1725 | stop = q; 1726 | } 1727 | cnt = 0; 1728 | stop = end_line(stop); 1729 | while (start <= stop && start <= end - 1) { 1730 | start = end_line(start); 1731 | if (*start == '\n') 1732 | cnt++; 1733 | start++; 1734 | } 1735 | return cnt; 1736 | } 1737 | 1738 | static char *find_line(int li) // find begining of line #li 1739 | { 1740 | char *q; 1741 | 1742 | for (q = text; li > 1; li--) { 1743 | q = next_line(q); 1744 | } 1745 | return q; 1746 | } 1747 | 1748 | //----- Dot Movement Routines ---------------------------------- 1749 | static void dot_left(void) 1750 | { 1751 | if (dot > text && dot[-1] != '\n') 1752 | dot--; 1753 | } 1754 | 1755 | static void dot_right(void) 1756 | { 1757 | if (dot < end - 1 && *dot != '\n') 1758 | dot++; 1759 | } 1760 | 1761 | static void dot_begin(void) 1762 | { 1763 | dot = begin_line(dot); // return pointer to first char cur line 1764 | } 1765 | 1766 | static void dot_end(void) 1767 | { 1768 | dot = end_line(dot); // return pointer to last char cur line 1769 | } 1770 | 1771 | static char *move_to_col(char *p, int l) 1772 | { 1773 | int co; 1774 | 1775 | p = begin_line(p); 1776 | co = 0; 1777 | while (co < l && p < end) { 1778 | if (*p == '\n') //vda || *p == '\0') 1779 | break; 1780 | if (*p == '\t') { 1781 | co = next_tabstop(co); 1782 | } else if (*p < ' ' || *p == 127) { 1783 | co++; // display as ^X, use 2 columns 1784 | } 1785 | co++; 1786 | p++; 1787 | } 1788 | return p; 1789 | } 1790 | 1791 | static void dot_next(void) 1792 | { 1793 | dot = next_line(dot); 1794 | } 1795 | 1796 | static void dot_prev(void) 1797 | { 1798 | dot = prev_line(dot); 1799 | } 1800 | 1801 | static void dot_scroll(int cnt, int dir) 1802 | { 1803 | char *q; 1804 | 1805 | for (; cnt > 0; cnt--) { 1806 | if (dir < 0) { 1807 | // scroll Backwards 1808 | // ctrl-Y scroll up one line 1809 | screenbegin = prev_line(screenbegin); 1810 | } else { 1811 | // scroll Forwards 1812 | // ctrl-E scroll down one line 1813 | screenbegin = next_line(screenbegin); 1814 | } 1815 | } 1816 | // make sure "dot" stays on the screen so we dont scroll off 1817 | if (dot < screenbegin) 1818 | dot = screenbegin; 1819 | q = end_screen(); // find new bottom line 1820 | if (dot > q) 1821 | dot = begin_line(q); // is dot is below bottom line? 1822 | dot_skip_over_ws(); 1823 | } 1824 | 1825 | static void dot_skip_over_ws(void) 1826 | { 1827 | // skip WS 1828 | while (isspace(*dot) && *dot != '\n' && dot < end - 1) 1829 | dot++; 1830 | } 1831 | 1832 | static void dot_delete(void) // delete the char at 'dot' 1833 | { 1834 | text_hole_delete(dot, dot); 1835 | } 1836 | 1837 | static char *bound_dot(char *p) // make sure text[0] <= P < "end" 1838 | { 1839 | if (p >= end && end > text) { 1840 | p = end - 1; 1841 | indicate_error('1'); 1842 | } 1843 | if (p < text) { 1844 | p = text; 1845 | indicate_error('2'); 1846 | } 1847 | return p; 1848 | } 1849 | 1850 | //----- Helper Utility Routines -------------------------------- 1851 | 1852 | //---------------------------------------------------------------- 1853 | //----- Char Routines -------------------------------------------- 1854 | /* Chars that are part of a word- 1855 | * 0123456789_ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz 1856 | * Chars that are Not part of a word (stoppers) 1857 | * !"#$%&'()*+,-./:;<=>?@[\]^`{|}~ 1858 | * Chars that are WhiteSpace 1859 | * TAB NEWLINE VT FF RETURN SPACE 1860 | * DO NOT COUNT NEWLINE AS WHITESPACE 1861 | */ 1862 | 1863 | static char *new_screen(int ro, int co) 1864 | { 1865 | free(screen); 1866 | screensize = ro * co + 8; 1867 | screen = xmalloc(screensize); 1868 | screen_erase(); 1869 | return screen; 1870 | } 1871 | 1872 | #if ENABLE_FEATURE_VI_SEARCH 1873 | static int mycmp(const char *s1, const char *s2, int len) 1874 | { 1875 | int i; 1876 | 1877 | i = strncmp(s1, s2, len); 1878 | if (ENABLE_FEATURE_VI_SETOPTS && ignorecase) { 1879 | i = strncasecmp(s1, s2, len); 1880 | } 1881 | return i; 1882 | } 1883 | 1884 | // search for pattern starting at p 1885 | static char *char_search(char *p, const char *pat, int dir, int range) 1886 | { 1887 | #ifndef REGEX_SEARCH 1888 | char *start, *stop; 1889 | int len; 1890 | 1891 | len = strlen(pat); 1892 | if (dir == FORWARD) { 1893 | stop = end - 1; // assume range is p - end-1 1894 | if (range == LIMITED) 1895 | stop = next_line(p); // range is to next line 1896 | for (start = p; start < stop; start++) { 1897 | if (mycmp(start, pat, len) == 0) { 1898 | return start; 1899 | } 1900 | } 1901 | } else if (dir == BACK) { 1902 | stop = text; // assume range is text - p 1903 | if (range == LIMITED) 1904 | stop = prev_line(p); // range is to prev line 1905 | for (start = p - len; start >= stop; start--) { 1906 | if (mycmp(start, pat, len) == 0) { 1907 | return start; 1908 | } 1909 | } 1910 | } 1911 | // pattern not found 1912 | return NULL; 1913 | #else /* REGEX_SEARCH */ 1914 | char *q; 1915 | struct re_pattern_buffer preg; 1916 | int i; 1917 | int size, range; 1918 | 1919 | re_syntax_options = RE_SYNTAX_POSIX_EXTENDED; 1920 | preg.translate = 0; 1921 | preg.fastmap = 0; 1922 | preg.buffer = 0; 1923 | preg.allocated = 0; 1924 | 1925 | // assume a LIMITED forward search 1926 | q = next_line(p); 1927 | q = end_line(q); 1928 | q = end - 1; 1929 | if (dir == BACK) { 1930 | q = prev_line(p); 1931 | q = text; 1932 | } 1933 | // count the number of chars to search over, forward or backward 1934 | size = q - p; 1935 | if (size < 0) 1936 | size = p - q; 1937 | // RANGE could be negative if we are searching backwards 1938 | range = q - p; 1939 | 1940 | q = re_compile_pattern(pat, strlen(pat), &preg); 1941 | if (q != 0) { 1942 | // The pattern was not compiled 1943 | status_line_bold("bad search pattern: \"%s\": %s", pat, q); 1944 | i = 0; // return p if pattern not compiled 1945 | goto cs1; 1946 | } 1947 | 1948 | q = p; 1949 | if (range < 0) { 1950 | q = p - size; 1951 | if (q < text) 1952 | q = text; 1953 | } 1954 | // search for the compiled pattern, preg, in p[] 1955 | // range < 0- search backward 1956 | // range > 0- search forward 1957 | // 0 < start < size 1958 | // re_search() < 0 not found or error 1959 | // re_search() > 0 index of found pattern 1960 | // struct pattern char int int int struct reg 1961 | // re_search (*pattern_buffer, *string, size, start, range, *regs) 1962 | i = re_search(&preg, q, size, 0, range, 0); 1963 | if (i == -1) { 1964 | p = 0; 1965 | i = 0; // return NULL if pattern not found 1966 | } 1967 | cs1: 1968 | if (dir == FORWARD) { 1969 | p = p + i; 1970 | } else { 1971 | p = p - i; 1972 | } 1973 | return p; 1974 | #endif /* REGEX_SEARCH */ 1975 | } 1976 | #endif /* FEATURE_VI_SEARCH */ 1977 | 1978 | static char *char_insert(char *p, char c) // insert the char c at 'p' 1979 | { 1980 | if (c == 22) { // Is this an ctrl-V? 1981 | p = stupid_insert(p, '^'); // use ^ to indicate literal next 1982 | p--; // backup onto ^ 1983 | refresh(); // show the ^ 1984 | c = get_one_char(); 1985 | *p = c; 1986 | p++; 1987 | file_modified++; 1988 | } else if (c == 27) { // Is this an ESC? 1989 | cmd_mode = CMODE_COMMAND; 1990 | cmdcnt = 0; 1991 | end_cmd_q(); // stop adding to q 1992 | if ((p[-1] != '\n') && (dot > text)) { 1993 | p--; 1994 | } 1995 | } else if (c == erase_char || c == 8 || c == 127) { // Is this a BS 1996 | // 123456789 1997 | if ((p[-1] != '\n') && (dot>text)) { 1998 | p--; 1999 | p = text_hole_delete(p, p); // shrink buffer 1 char 2000 | } 2001 | } else { 2002 | // insert a char into text[] 2003 | char *sp; // "save p" 2004 | 2005 | if (c == 13) 2006 | c = '\n'; // translate \r to \n 2007 | sp = p; // remember addr of insert 2008 | p = stupid_insert(p, c); // insert the char 2009 | #if ENABLE_FEATURE_VI_SETOPTS 2010 | if (showmatch && strchr(")]}", *sp) != NULL) { 2011 | showmatching(sp); 2012 | } 2013 | if (autoindent && c == '\n') { // auto indent the new line 2014 | char *q; 2015 | 2016 | q = prev_line(p); // use prev line as templet 2017 | for (; isblank(*q); q++) { 2018 | p = stupid_insert(p, *q); // insert the char 2019 | } 2020 | } 2021 | #endif 2022 | } 2023 | return p; 2024 | } 2025 | 2026 | static char *stupid_insert(char *p, char c) // stupidly insert the char c at 'p' 2027 | { 2028 | p = text_hole_make(p, 1); 2029 | *p = c; 2030 | //file_modified++; - done by text_hole_make() 2031 | return p + 1; 2032 | } 2033 | 2034 | static int find_range(char **start, char **stop, char c) 2035 | { 2036 | char *save_dot, *p, *q, *t; 2037 | int cnt, multiline = 0; 2038 | 2039 | save_dot = dot; 2040 | p = q = dot; 2041 | 2042 | if (strchr("cdy><", c)) { 2043 | // these cmds operate on whole lines 2044 | p = q = begin_line(p); 2045 | for (cnt = 1; cnt < cmdcnt; cnt++) { 2046 | q = next_line(q); 2047 | } 2048 | q = end_line(q); 2049 | } else if (strchr("^%$0bBeEfth\b\177", c)) { 2050 | // These cmds operate on char positions 2051 | do_cmd(c); // execute movement cmd 2052 | q = dot; 2053 | } else if (strchr("wW", c)) { 2054 | do_cmd(c); // execute movement cmd 2055 | // if we are at the next word's first char 2056 | // step back one char 2057 | // but check the possibilities when it is true 2058 | if (dot > text && ((isspace(dot[-1]) && !isspace(dot[0])) 2059 | || (ispunct(dot[-1]) && !ispunct(dot[0])) 2060 | || (isalnum(dot[-1]) && !isalnum(dot[0])))) 2061 | dot--; // move back off of next word 2062 | if (dot > text && *dot == '\n') 2063 | dot--; // stay off NL 2064 | q = dot; 2065 | } else if (strchr("H-k{", c)) { 2066 | // these operate on multi-lines backwards 2067 | q = end_line(dot); // find NL 2068 | do_cmd(c); // execute movement cmd 2069 | dot_begin(); 2070 | p = dot; 2071 | } else if (strchr("L+j}\r\n", c)) { 2072 | // these operate on multi-lines forwards 2073 | p = begin_line(dot); 2074 | do_cmd(c); // execute movement cmd 2075 | dot_end(); // find NL 2076 | q = dot; 2077 | } else { 2078 | // nothing -- this causes any other values of c to 2079 | // represent the one-character range under the 2080 | // cursor. this is correct for ' ' and 'l', but 2081 | // perhaps no others. 2082 | // 2083 | } 2084 | if (q < p) { 2085 | t = q; 2086 | q = p; 2087 | p = t; 2088 | } 2089 | 2090 | // backward char movements don't include start position 2091 | if (q > p && strchr("^0bBh\b\177", c)) q--; 2092 | 2093 | multiline = 0; 2094 | for (t = p; t <= q; t++) { 2095 | if (*t == '\n') { 2096 | multiline = 1; 2097 | break; 2098 | } 2099 | } 2100 | 2101 | *start = p; 2102 | *stop = q; 2103 | dot = save_dot; 2104 | return multiline; 2105 | } 2106 | 2107 | static int st_test(char *p, int type, int dir, char *tested) 2108 | { 2109 | char c, c0, ci; 2110 | int test, inc; 2111 | 2112 | inc = dir; 2113 | c = c0 = p[0]; 2114 | ci = p[inc]; 2115 | test = 0; 2116 | 2117 | if (type == S_BEFORE_WS) { 2118 | c = ci; 2119 | test = ((!isspace(c)) || c == '\n'); 2120 | } 2121 | if (type == S_TO_WS) { 2122 | c = c0; 2123 | test = ((!isspace(c)) || c == '\n'); 2124 | } 2125 | if (type == S_OVER_WS) { 2126 | c = c0; 2127 | test = ((isspace(c))); 2128 | } 2129 | if (type == S_END_PUNCT) { 2130 | c = ci; 2131 | test = ((ispunct(c))); 2132 | } 2133 | if (type == S_END_ALNUM) { 2134 | c = ci; 2135 | test = ((isalnum(c)) || c == '_'); 2136 | } 2137 | *tested = c; 2138 | return test; 2139 | } 2140 | 2141 | static char *skip_thing(char *p, int linecnt, int dir, int type) 2142 | { 2143 | char c; 2144 | 2145 | while (st_test(p, type, dir, &c)) { 2146 | // make sure we limit search to correct number of lines 2147 | if (c == '\n' && --linecnt < 1) 2148 | break; 2149 | if (dir >= 0 && p >= end - 1) 2150 | break; 2151 | if (dir < 0 && p <= text) 2152 | break; 2153 | p += dir; // move to next char 2154 | } 2155 | return p; 2156 | } 2157 | 2158 | // find matching char of pair () [] {} 2159 | static char *find_pair(char *p, const char c) 2160 | { 2161 | char match, *q; 2162 | int dir, level; 2163 | 2164 | match = ')'; 2165 | level = 1; 2166 | dir = 1; // assume forward 2167 | switch (c) { 2168 | case '(': match = ')'; break; 2169 | case '[': match = ']'; break; 2170 | case '{': match = '}'; break; 2171 | case ')': match = '('; dir = -1; break; 2172 | case ']': match = '['; dir = -1; break; 2173 | case '}': match = '{'; dir = -1; break; 2174 | } 2175 | for (q = p + dir; text <= q && q < end; q += dir) { 2176 | // look for match, count levels of pairs (( )) 2177 | if (*q == c) 2178 | level++; // increase pair levels 2179 | if (*q == match) 2180 | level--; // reduce pair level 2181 | if (level == 0) 2182 | break; // found matching pair 2183 | } 2184 | if (level != 0) 2185 | q = NULL; // indicate no match 2186 | return q; 2187 | } 2188 | 2189 | // open a hole in text[] 2190 | static char *text_hole_make(char *p, int size) // at "p", make a 'size' byte hole 2191 | { 2192 | if (size <= 0) 2193 | return p; 2194 | end += size; // adjust the new END 2195 | if (end >= (text + text_size)) { 2196 | char *new_text; 2197 | text_size += end - (text + text_size) + 10240; 2198 | new_text = xrealloc(text, text_size); 2199 | screenbegin = new_text + (screenbegin - text); 2200 | dot = new_text + (dot - text); 2201 | end = new_text + (end - text); 2202 | p = new_text + (p - text); 2203 | text = new_text; 2204 | } 2205 | memmove(p + size, p, end - size - p); 2206 | memset(p, ' ', size); // clear new hole 2207 | file_modified++; 2208 | return p; 2209 | } 2210 | 2211 | // close a hole in text[] 2212 | static char *text_hole_delete(char *p, char *q) // delete "p" through "q", inclusive 2213 | { 2214 | char *src, *dest; 2215 | int cnt, hole_size; 2216 | 2217 | // move forwards, from beginning 2218 | // assume p <= q 2219 | src = q + 1; 2220 | dest = p; 2221 | if (q < p) { // they are backward- swap them 2222 | src = p + 1; 2223 | dest = q; 2224 | } 2225 | hole_size = q - p + 1; 2226 | cnt = end - src; 2227 | if (src < text || src > end) 2228 | goto thd0; 2229 | if (dest < text || dest >= end) 2230 | goto thd0; 2231 | if (src >= end) 2232 | goto thd_atend; // just delete the end of the buffer 2233 | memmove(dest, src, cnt); 2234 | thd_atend: 2235 | end = end - hole_size; // adjust the new END 2236 | if (dest >= end) 2237 | dest = end - 1; // make sure dest in below end-1 2238 | if (end <= text) 2239 | dest = end = text; // keep pointers valid 2240 | file_modified++; 2241 | thd0: 2242 | return dest; 2243 | } 2244 | 2245 | // copy text into register, then delete text. 2246 | // if dist <= 0, do not include, or go past, a NewLine 2247 | // 2248 | static char *yank_delete(char *start, char *stop, int dist, int yf) 2249 | { 2250 | char *p; 2251 | 2252 | // make sure start <= stop 2253 | if (start > stop) { 2254 | // they are backwards, reverse them 2255 | p = start; 2256 | start = stop; 2257 | stop = p; 2258 | } 2259 | if (dist <= 0) { 2260 | // we cannot cross NL boundaries 2261 | p = start; 2262 | if (*p == '\n') 2263 | return p; 2264 | // dont go past a NewLine 2265 | for (; p + 1 <= stop; p++) { 2266 | if (p[1] == '\n') { 2267 | stop = p; // "stop" just before NewLine 2268 | break; 2269 | } 2270 | } 2271 | } 2272 | p = start; 2273 | #if ENABLE_FEATURE_VI_YANKMARK 2274 | text_yank(start, stop, YDreg); 2275 | #endif 2276 | if (yf == YANKDEL) { 2277 | p = text_hole_delete(start, stop); 2278 | } // delete lines 2279 | return p; 2280 | } 2281 | 2282 | static void show_help(void) 2283 | { 2284 | puts("These features are available:" 2285 | #if ENABLE_FEATURE_VI_SEARCH 2286 | "\n\tPattern searches with / and ?" 2287 | #endif 2288 | #if ENABLE_FEATURE_VI_DOT_CMD 2289 | "\n\tLast command repeat with \'.\'" 2290 | #endif 2291 | #if ENABLE_FEATURE_VI_YANKMARK 2292 | "\n\tLine marking with 'x" 2293 | "\n\tNamed buffers with \"x" 2294 | #endif 2295 | #if ENABLE_FEATURE_VI_READONLY 2296 | #ifdef NO_SUCH_APPLET_YET 2297 | "\n\tReadonly if vi is called as \"view\"" 2298 | #endif 2299 | "\n\tReadonly with -R command line arg" 2300 | #endif 2301 | #if ENABLE_FEATURE_VI_SET 2302 | "\n\tSome colon mode commands with \':\'" 2303 | #endif 2304 | #if ENABLE_FEATURE_VI_SETOPTS 2305 | "\n\tSettable options with \":set\"" 2306 | #endif 2307 | #if ENABLE_FEATURE_VI_USE_SIGNALS 2308 | "\n\tSignal catching- ^C" 2309 | "\n\tJob suspend and resume with ^Z" 2310 | #endif 2311 | "\n\tLINES and COLUMNS env vars determine window size" 2312 | #if ENABLE_FEATURE_VI_WIN_RESIZE 2313 | "\n\tAdapt to window re-sizes (if LINES and COLUMNS env vars unset!)" 2314 | #endif 2315 | ); 2316 | } 2317 | 2318 | #if ENABLE_FEATURE_VI_DOT_CMD 2319 | static void start_new_cmd_q(char c) 2320 | { 2321 | // get buffer for new cmd 2322 | // if there is a current cmd count put it in the buffer first 2323 | if (cmdcnt > 0) 2324 | lmc_len = sprintf(last_modifying_cmd, "%d%c", cmdcnt, c); 2325 | else { // just save char c onto queue 2326 | last_modifying_cmd[0] = c; 2327 | lmc_len = 1; 2328 | } 2329 | adding2q = 1; 2330 | } 2331 | 2332 | static void end_cmd_q(void) 2333 | { 2334 | #if ENABLE_FEATURE_VI_YANKMARK 2335 | YDreg = 26; // go back to default Yank/Delete reg 2336 | #endif 2337 | adding2q = 0; 2338 | } 2339 | #endif /* FEATURE_VI_DOT_CMD */ 2340 | 2341 | #if ENABLE_FEATURE_VI_YANKMARK \ 2342 | || (ENABLE_FEATURE_VI_COLON && ENABLE_FEATURE_VI_SEARCH) \ 2343 | || ENABLE_FEATURE_VI_CRASHME 2344 | static char *string_insert(char *p, char *s) // insert the string at 'p' 2345 | { 2346 | int cnt, i; 2347 | 2348 | i = strlen(s); 2349 | text_hole_make(p, i); 2350 | strncpy(p, s, i); 2351 | for (cnt = 0; *s != '\0'; s++) { 2352 | if (*s == '\n') 2353 | cnt++; 2354 | } 2355 | #if ENABLE_FEATURE_VI_YANKMARK 2356 | status_line("Put %d lines (%d chars) from [%c]", cnt, i, what_reg()); 2357 | #endif 2358 | return p; 2359 | } 2360 | #endif 2361 | 2362 | #if ENABLE_FEATURE_VI_YANKMARK 2363 | static char *text_yank(char *p, char *q, int dest) // copy text into a register 2364 | { 2365 | char *t; 2366 | int cnt; 2367 | 2368 | if (q < p) { // they are backwards- reverse them 2369 | t = q; 2370 | q = p; 2371 | p = t; 2372 | } 2373 | cnt = q - p + 1; 2374 | t = reg[dest]; 2375 | free(t); // if already a yank register, free it 2376 | t = xmalloc(cnt + 1); // get a new register 2377 | memset(t, '\0', cnt + 1); // clear new text[] 2378 | strncpy(t, p, cnt); // copy text[] into bufer 2379 | reg[dest] = t; 2380 | return p; 2381 | } 2382 | 2383 | static char what_reg(void) 2384 | { 2385 | char c; 2386 | 2387 | c = 'D'; // default to D-reg 2388 | if (0 <= YDreg && YDreg <= 25) 2389 | c = 'a' + (char) YDreg; 2390 | if (YDreg == 26) 2391 | c = 'D'; 2392 | if (YDreg == 27) 2393 | c = 'U'; 2394 | return c; 2395 | } 2396 | 2397 | static void check_context(char cmd) 2398 | { 2399 | // A context is defined to be "modifying text" 2400 | // Any modifying command establishes a new context. 2401 | 2402 | if (dot < context_start || dot > context_end) { 2403 | if (strchr(modifying_cmds, cmd) != NULL) { 2404 | // we are trying to modify text[]- make this the current context 2405 | mark[27] = mark[26]; // move cur to prev 2406 | mark[26] = dot; // move local to cur 2407 | context_start = prev_line(prev_line(dot)); 2408 | context_end = next_line(next_line(dot)); 2409 | //loiter= start_loiter= now; 2410 | } 2411 | } 2412 | } 2413 | 2414 | static char *swap_context(char *p) // goto new context for '' command make this the current context 2415 | { 2416 | char *tmp; 2417 | 2418 | // the current context is in mark[26] 2419 | // the previous context is in mark[27] 2420 | // only swap context if other context is valid 2421 | if (text <= mark[27] && mark[27] <= end - 1) { 2422 | tmp = mark[27]; 2423 | mark[27] = mark[26]; 2424 | mark[26] = tmp; 2425 | p = mark[26]; // where we are going- previous context 2426 | context_start = prev_line(prev_line(prev_line(p))); 2427 | context_end = next_line(next_line(next_line(p))); 2428 | } 2429 | return p; 2430 | } 2431 | #endif /* FEATURE_VI_YANKMARK */ 2432 | 2433 | //----- Set terminal attributes -------------------------------- 2434 | static int rawmode(void) 2435 | { 2436 | int err = tcgetattr(0, &term_orig); 2437 | if (err) 2438 | return err; 2439 | term_vi = term_orig; 2440 | term_vi.c_lflag &= (~ICANON & ~ECHO); // leave ISIG ON- allow intr's 2441 | term_vi.c_iflag &= (~IXON & ~ICRNL); 2442 | term_vi.c_oflag &= (~ONLCR); 2443 | term_vi.c_cc[VMIN] = 1; 2444 | term_vi.c_cc[VTIME] = 0; 2445 | erase_char = term_vi.c_cc[VERASE]; 2446 | tcsetattr(0, TCSANOW, &term_vi); 2447 | 2448 | unsigned tics = 1; 2449 | ticsPerChar = tics; 2450 | return 0; 2451 | } 2452 | 2453 | static void cookmode(void) 2454 | { 2455 | tcsetattr(0, TCSANOW, &term_orig); 2456 | } 2457 | 2458 | //----- Come here when we get a window resize signal --------- 2459 | #if ENABLE_FEATURE_VI_USE_SIGNALS 2460 | static void winch_sig(int sig ATTRIBUTE_UNUSED) 2461 | { 2462 | createScreen(); 2463 | redraw(); 2464 | fflush(stdout); 2465 | } 2466 | 2467 | //----- Come here on QUIT, PIPE, TERM, HUP ---------------------- 2468 | static void quit_sig(int sig) 2469 | { 2470 | gracefulExit(); 2471 | signal(sig, SIG_DFL); 2472 | kill(my_pid, sig); 2473 | } 2474 | 2475 | 2476 | //----- Come here when we get a continue signal ------------------- 2477 | static void cont_sig(int sig ATTRIBUTE_UNUSED) 2478 | { 2479 | rawmode(); // terminal to "raw" 2480 | *status_buffer=0; // force status update 2481 | redraw(); 2482 | fflush(stdout); 2483 | signal(SIGTSTP, suspend_sig); 2484 | signal(SIGCONT, SIG_DFL); 2485 | kill(my_pid, SIGCONT); 2486 | } 2487 | 2488 | //----- Come here when we get a Suspend signal ------------------- 2489 | static void suspend_sig(int sig ATTRIBUTE_UNUSED) 2490 | { 2491 | gracefulExit(); 2492 | signal(SIGCONT, cont_sig); 2493 | signal(SIGTSTP, SIG_DFL); 2494 | kill(my_pid, SIGTSTP); 2495 | } 2496 | 2497 | //----- Come here when we get a INT signal --------------------------- 2498 | static void catch_sig(int sig) 2499 | { 2500 | signal(SIGINT, catch_sig); 2501 | if (sig) 2502 | siglongjmp(restart, sig); 2503 | } 2504 | #endif /* FEATURE_VI_USE_SIGNALS */ 2505 | 2506 | static int awaitInput(int tics) 2507 | //returns true if input is becomes available within tics/100 seconds 2508 | { 2509 | fflush(stdout); 2510 | tcdrain(STDOUT_FILENO); 2511 | struct pollfd pfd[1]; 2512 | 2513 | pfd[0].fd = 0; 2514 | pfd[0].events = POLLIN; 2515 | return safe_poll(pfd, 1, tics*10) > 0; 2516 | } 2517 | 2518 | //----- IO Routines -------------------------------------------- 2519 | static char readit(void) // read (maybe cursor) key from stdin 2520 | { 2521 | char c; 2522 | size_t n; 2523 | struct esc_cmds { 2524 | const char seq[4]; 2525 | char val; 2526 | }; 2527 | 2528 | static const struct esc_cmds esccmds[] = { 2529 | {"OA" , VI_K_UP }, // cursor key Up 2530 | {"OB" , VI_K_DOWN }, // cursor key Down 2531 | {"OC" , VI_K_RIGHT }, // Cursor Key Right 2532 | {"OD" , VI_K_LEFT }, // cursor key Left 2533 | {"OH" , VI_K_HOME }, // Cursor Key Home 2534 | {"OF" , VI_K_END }, // Cursor Key End 2535 | {"[A" , VI_K_UP }, // cursor key Up 2536 | {"[B" , VI_K_DOWN }, // cursor key Down 2537 | {"[C" , VI_K_RIGHT }, // Cursor Key Right 2538 | {"[D" , VI_K_LEFT }, // cursor key Left 2539 | {"[H" , VI_K_HOME }, // Cursor Key Home 2540 | {"[F" , VI_K_END }, // Cursor Key End 2541 | {"[1~" , VI_K_HOME }, // Cursor Key Home 2542 | {"[2~" , VI_K_INSERT }, // Cursor Key Insert 2543 | {"[3~" , VI_K_DELETE }, // Cursor Key Delete 2544 | {"[4~" , VI_K_END }, // Cursor Key End 2545 | {"[5~" , VI_K_PAGEUP }, // Cursor Key Page Up 2546 | {"[6~" , VI_K_PAGEDOWN}, // Cursor Key Page Down 2547 | {"OP" , VI_K_FUN1 }, // Function Key F1 2548 | {"OQ" , VI_K_FUN2 }, // Function Key F2 2549 | {"OR" , VI_K_FUN3 }, // Function Key F3 2550 | {"OS" , VI_K_FUN4 }, // Function Key F4 2551 | // careful: these have no terminating NUL! 2552 | {"[11~", VI_K_FUN1 }, // Function Key F1 2553 | {"[12~", VI_K_FUN2 }, // Function Key F2 2554 | {"[13~", VI_K_FUN3 }, // Function Key F3 2555 | {"[14~", VI_K_FUN4 }, // Function Key F4 2556 | {"[15~", VI_K_FUN5 }, // Function Key F5 2557 | {"[17~", VI_K_FUN6 }, // Function Key F6 2558 | {"[18~", VI_K_FUN7 }, // Function Key F7 2559 | {"[19~", VI_K_FUN8 }, // Function Key F8 2560 | {"[20~", VI_K_FUN9 }, // Function Key F9 2561 | {"[21~", VI_K_FUN10 }, // Function Key F10 2562 | {"[23~", VI_K_FUN11 }, // Function Key F11 2563 | {"[24~", VI_K_FUN12 }, // Function Key F12 2564 | }; 2565 | enum { ESCCMDS_COUNT = ARRAY_SIZE(esccmds) }; 2566 | 2567 | n = chars_to_parse; 2568 | // get input from User- are there already input chars in Q? 2569 | if (n <= 0) { 2570 | // the Q is empty, wait for a typed char 2571 | fflush(stdout); 2572 | n = safe_read(STDIN_FILENO, readbuffer, sizeof(readbuffer)); 2573 | if (n < 0) { 2574 | if (errno == EBADF || errno == EFAULT || errno == EINVAL 2575 | || errno == EIO) 2576 | editing = 0; // want to exit 2577 | errno = 0; 2578 | } 2579 | if (n <= 0) 2580 | return 0; // error 2581 | if (readbuffer[0] == 27) { 2582 | // This is an ESC char. Is this Esc sequence? 2583 | // Could be bare Esc key. See if there are any 2584 | // more chars to read after the ESC. This would 2585 | // be a Function or Cursor Key sequence. 2586 | // keep reading while there are input chars and room in buffer 2587 | // for a complete ESC sequence (assuming 8 chars is enough) 2588 | while(awaitInput(ticsPerChar)) { 2589 | // read the rest of the ESC string 2590 | int r = safe_read(STDIN_FILENO, 2591 | readbuffer + n, sizeof(readbuffer) - n); 2592 | if (r <= 0) 2593 | break; 2594 | n += r; 2595 | if (n > sizeof(readbuffer)-8) 2596 | break; 2597 | } 2598 | } 2599 | chars_to_parse = n; 2600 | } 2601 | c = readbuffer[0]; 2602 | if (c == 27 && n > 1) { 2603 | // Maybe cursor or function key? 2604 | const struct esc_cmds *eindex; 2605 | 2606 | for (eindex = esccmds; eindex < &esccmds[ESCCMDS_COUNT]; eindex++) { 2607 | int cnt = strnlen(eindex->seq, 4); 2608 | if (n <= cnt) 2609 | continue; 2610 | if (strncmp(eindex->seq, readbuffer + 1, cnt) != 0) 2611 | continue; 2612 | c = eindex->val; // magic char value 2613 | n = cnt + 1; // squeeze out the ESC sequence 2614 | goto found; 2615 | } 2616 | // defined ESC sequence not found 2617 | } 2618 | n = 1; 2619 | found: 2620 | // remove key sequence from Q 2621 | chars_to_parse -= n; 2622 | memmove(readbuffer, readbuffer + n, sizeof(readbuffer) - n); 2623 | return c; 2624 | } 2625 | 2626 | //----- IO Routines -------------------------------------------- 2627 | static char get_one_char(void) 2628 | { 2629 | char c; 2630 | 2631 | #if ENABLE_FEATURE_VI_DOT_CMD 2632 | if (!adding2q) { 2633 | // we are not adding to the q. 2634 | // but, we may be reading from a q 2635 | if (ioq == 0) { 2636 | // there is no current q, read from STDIN 2637 | c = readit(); // get the users input 2638 | } else { 2639 | // there is a queue to get chars from first 2640 | c = *ioq++; 2641 | if (c == '\0') { 2642 | // the end of the q, read from STDIN 2643 | free(ioq_start); 2644 | ioq_start = ioq = 0; 2645 | c = readit(); // get the users input 2646 | } 2647 | } 2648 | } else { 2649 | // adding STDIN chars to q 2650 | c = readit(); // get the users input 2651 | if (lmc_len >= MAX_INPUT_LEN - 1) { 2652 | status_line_bold("last_modifying_cmd overrun"); 2653 | } else { 2654 | // add new char to q 2655 | last_modifying_cmd[lmc_len++] = c; 2656 | } 2657 | } 2658 | #else 2659 | c = readit(); // get the users input 2660 | #endif /* FEATURE_VI_DOT_CMD */ 2661 | return c; 2662 | } 2663 | 2664 | // Get input line (uses "status line" area) 2665 | static char *get_input_line(const char *prompt) 2666 | { 2667 | // char [MAX_INPUT_LEN] 2668 | #define buf status_buffer 2669 | 2670 | char c; 2671 | int i; 2672 | 2673 | *displayed_buffer = 0; // force status update 2674 | cmd_mode |= CMODE_LINE_INPUT; 2675 | strcpy(buf, prompt); 2676 | place_cursor(rows - 1, 0, FALSE); // go to Status line, bottom of screen 2677 | clear_to_eol(); // clear the line 2678 | write1(prompt); // write out the :, /, or ? prompt 2679 | 2680 | i = strlen(buf); 2681 | while (i < MAX_INPUT_LEN) { 2682 | c = get_one_char(); 2683 | if (c == '\n' || c == '\r' || c == 27) 2684 | break; // this is end of input 2685 | if (c == erase_char || c == 8 || c == 127) { 2686 | // user wants to erase prev char 2687 | buf[--i] = '\0'; 2688 | write1("\b \b"); // erase char on screen 2689 | if (i <= 0) // user backs up before b-o-l, exit 2690 | break; 2691 | } else { 2692 | buf[i] = c; 2693 | buf[++i] = '\0'; 2694 | bb_putchar(c); 2695 | } 2696 | } 2697 | cmd_mode &= ~CMODE_LINE_INPUT; 2698 | return strcpy(get_input_line__buf, buf); 2699 | #undef buf 2700 | } 2701 | 2702 | static int file_size(const char *fn) // what is the byte size of "fn" 2703 | { 2704 | struct stat st_buf; 2705 | int cnt; 2706 | 2707 | cnt = -1; 2708 | if (fn && fn[0] && stat(fn, &st_buf) == 0) // see if file exists 2709 | cnt = (int) st_buf.st_size; 2710 | return cnt; 2711 | } 2712 | 2713 | static int file_insert(const char *fn, char *p 2714 | USE_FEATURE_VI_READONLY(, int update_ro_status)) 2715 | { 2716 | int cnt = -1; 2717 | int fd, size; 2718 | struct stat statbuf; 2719 | 2720 | /* Validate file */ 2721 | if (stat(fn, &statbuf) < 0) { 2722 | status_line_bold("\"%s\" %s", fn, strerror(errno)); 2723 | goto fi0; 2724 | } 2725 | if (!S_ISREG(statbuf.st_mode)) { 2726 | // This is not a regular file 2727 | status_line_bold("\"%s\" Not a regular file", fn); 2728 | goto fi0; 2729 | } 2730 | if (p < text || p > end) { 2731 | status_line_bold("Trying to insert file outside of memory"); 2732 | goto fi0; 2733 | } 2734 | 2735 | // read file to buffer 2736 | fd = open(fn, O_RDONLY); 2737 | if (fd < 0) { 2738 | status_line_bold("\"%s\" %s", fn, strerror(errno)); 2739 | goto fi0; 2740 | } 2741 | size = statbuf.st_size; 2742 | p = text_hole_make(p, size); 2743 | cnt = safe_read(fd, p, size); 2744 | if (cnt < 0) { 2745 | status_line_bold("\"%s\" %s", fn, strerror(errno)); 2746 | p = text_hole_delete(p, p + size - 1); // un-do buffer insert 2747 | } else if (cnt < size) { 2748 | // There was a partial read, shrink unused space text[] 2749 | p = text_hole_delete(p + cnt, p + (size - cnt) - 1); // un-do buffer insert 2750 | status_line_bold("cannot read all of file \"%s\"", fn); 2751 | } 2752 | if (cnt >= size) 2753 | file_modified++; 2754 | close(fd); 2755 | fi0: 2756 | #if ENABLE_FEATURE_VI_READONLY 2757 | if (update_ro_status 2758 | && ((access(fn, W_OK) < 0) || 2759 | /* root will always have access() 2760 | * so we check fileperms too */ 2761 | !(statbuf.st_mode & (S_IWUSR | S_IWGRP | S_IWOTH)) 2762 | ) 2763 | ) { 2764 | SET_READONLY_FILE(readonly_mode); 2765 | } 2766 | #endif 2767 | return cnt; 2768 | } 2769 | 2770 | static int file_write(char *fn, char *first, char *last) 2771 | { 2772 | int fd, cnt, charcnt; 2773 | 2774 | if (fn == 0) { 2775 | status_line_bold("No current filename"); 2776 | return -2; 2777 | } 2778 | charcnt = 0; 2779 | /* By popular request we do not open file with O_TRUNC, 2780 | * but instead ftruncate() it _after_ successful write. 2781 | * Might reduce amount of data lost on power fail etc. 2782 | */ 2783 | fd = open(fn, (O_WRONLY | O_CREAT), 0666); 2784 | if (fd < 0) 2785 | return -1; 2786 | cnt = last - first + 1; 2787 | charcnt = full_write(fd, first, cnt); 2788 | ftruncate(fd, charcnt); 2789 | if (charcnt == cnt) { 2790 | // good write 2791 | //file_modified = FALSE; 2792 | } else { 2793 | charcnt = 0; 2794 | } 2795 | close(fd); 2796 | return charcnt; 2797 | } 2798 | 2799 | //----- Terminal Drawing --------------------------------------- 2800 | // The terminal is made up of 'rows' line of 'columns' columns. 2801 | // classically this would be 24 x 80. 2802 | // screen coordinates 2803 | // 0,0 ... 0,79 2804 | // 1,0 ... 1,79 2805 | // . ... . 2806 | // . ... . 2807 | // 22,0 ... 22,79 2808 | // 23,0 ... 23,79 <- status line 2809 | 2810 | //----- Move the cursor to row x col (count from 0, not 1) ------- 2811 | static void place_cursor(int row, int col, int optimize) 2812 | { 2813 | char cm1[sizeof(CMrc) + sizeof(int)*3 * 2]; 2814 | char *cm; 2815 | 2816 | if (row < 0) row = 0; 2817 | if (row >= rows) row = rows - 1; 2818 | if (col < 0) col = 0; 2819 | if (col >= columns) col = columns - 1; 2820 | 2821 | //----- 1. Try the standard terminal ESC sequence 2822 | sprintf(cm1, CMrc, row + 1, col + 1); 2823 | cm = cm1; 2824 | 2825 | #if ENABLE_FEATURE_VI_OPTIMIZE_CURSOR 2826 | if (optimize && col < 16) { 2827 | enum { 2828 | SZ_UP = sizeof(CMup), 2829 | SZ_DN = sizeof(CMdown), 2830 | SEQ_SIZE = SZ_UP > SZ_DN ? SZ_UP : SZ_DN, 2831 | }; 2832 | char cm2[SEQ_SIZE * 5 + 32]; // bigger than worst case size 2833 | char *screenp; 2834 | int Rrow = last_row; 2835 | int diff = Rrow - row; 2836 | 2837 | if (diff < -5 || diff > 5) 2838 | goto skip; 2839 | 2840 | //----- find the minimum # of chars to move cursor ------------- 2841 | //----- 2. Try moving with discreet chars (Newline, [back]space, ...) 2842 | cm2[0] = '\0'; 2843 | 2844 | // move to the correct row 2845 | while (row < Rrow) { 2846 | // the cursor has to move up 2847 | strcat(cm2, CMup); 2848 | Rrow--; 2849 | } 2850 | while (row > Rrow) { 2851 | // the cursor has to move down 2852 | strcat(cm2, CMdown); 2853 | Rrow++; 2854 | } 2855 | 2856 | // now move to the correct column 2857 | strcat(cm2, "\r"); // start at col 0 2858 | // just send out orignal source char to get to correct place 2859 | screenp = &screen[row * columns]; // start of screen line 2860 | strncat(cm2, screenp, col); 2861 | 2862 | // pick the shortest cursor motion to send out 2863 | if (strlen(cm2) < strlen(cm)) { 2864 | cm = cm2; 2865 | } 2866 | skip: ; 2867 | } 2868 | last_row = row; 2869 | #endif /* FEATURE_VI_OPTIMIZE_CURSOR */ 2870 | write1(cm); 2871 | } 2872 | 2873 | //----- Erase from cursor to end of line ----------------------- 2874 | static void clear_to_eol(void) 2875 | { 2876 | write1(Ceol); // Erase from cursor to end of line 2877 | } 2878 | 2879 | //----- Erase from cursor to end of screen ----------------------- 2880 | static void clear_to_eos(void) 2881 | { 2882 | write1(Ceos); // Erase from cursor to end of screen 2883 | *displayed_buffer=0; //status line was also cleared 2884 | } 2885 | 2886 | //----- Start standout mode ------------------------------------ 2887 | static void standout_start(void) // send "start reverse video" sequence 2888 | { 2889 | write1(SOs); // Start reverse video mode 2890 | } 2891 | 2892 | //----- End standout mode -------------------------------------- 2893 | static void standout_end(void) // send "end reverse video" sequence 2894 | { 2895 | write1(SOn); // End reverse video mode 2896 | } 2897 | 2898 | //----- Flash the screen -------------------------------------- 2899 | static void flash(int h) 2900 | { 2901 | standout_start(); // send "start reverse video" sequence 2902 | redraw(); 2903 | awaitInput(h); 2904 | standout_end(); // send "end reverse video" sequence 2905 | redraw(); 2906 | } 2907 | 2908 | static void Indicate_Error(void) 2909 | { 2910 | #if ENABLE_FEATURE_VI_CRASHME 2911 | if (crashme > 0) 2912 | return; // generate a random command 2913 | #endif 2914 | if (!err_method) { 2915 | write1(bell); // send out a bell character 2916 | } else { 2917 | flash(10); 2918 | } 2919 | } 2920 | 2921 | //----- Screen[] Routines -------------------------------------- 2922 | //----- Erase the Screen[] memory ------------------------------ 2923 | static void screen_erase(void) 2924 | { 2925 | memset(screen, ' ', screensize); // clear new screen 2926 | } 2927 | 2928 | static const char *scompare(const char *s, const char *ref) 2929 | // why isn't this in the ANSI 'C' library? 2930 | { 2931 | while(*s && *s == *ref) 2932 | s++, ref++; 2933 | return *s == *ref ? NULL : s; 2934 | } 2935 | 2936 | //----- Draw the status line at bottom of the screen ------------- 2937 | static void show_status_line(void) 2938 | { 2939 | // either we already have an error or status message, or we 2940 | // create one. 2941 | const char *buffer = status_buffer; 2942 | if (!*buffer) 2943 | format_edit_status(EDIT_STATUS); 2944 | const char *changed = scompare(buffer, displayed_buffer); 2945 | if (changed) { 2946 | size_t unchanged = changed - buffer; 2947 | strcpy(displayed_buffer+unchanged, changed); 2948 | //place cursor on correct column if line begins with standout text 2949 | size_t escapes = *buffer == *SOs ? 2*SOlen : 0; 2950 | place_cursor(rows - 1, // put cursor on status line 2951 | escapes ? unchanged - SOlen : unchanged, FALSE); 2952 | clear_to_eol(); //NOTE: assumes entire status text was in stand-out mode 2953 | if (unchanged && escapes) //need to start in stand-out mode 2954 | fwrite(buffer, SOlen, 1, stdout); 2955 | size_t len = unchanged + strlen(buffer=changed); 2956 | if (len - escapes > columns) { 2957 | const char *limit = status_buffer + columns; 2958 | if (escapes) 2959 | limit += SOlen; 2960 | fwrite(buffer, limit-buffer, 1, stdout); 2961 | buffer = status_buffer + len; 2962 | if (escapes && len > 2*SOlen) //end w/restore to normal ESC sequence 2963 | buffer-=SOlen; 2964 | } 2965 | write1(buffer); //this leaves cursor correctly placed for LINE_INPUT 2966 | if (!(cmd_mode & CMODE_LINE_INPUT)) 2967 | place_cursor(crow, ccol, TRUE); //otherwise, replace it in text area 2968 | }else if (cmd_mode & CMODE_LINE_INPUT) //in case status area was correct 2969 | place_cursor(rows-1, strlen(buffer), FALSE); //put cursor at its end 2970 | else //put cursor back in text area 2971 | place_cursor(crow, ccol, TRUE); 2972 | } 2973 | 2974 | //----- format the status buffer, the bottom line of screen ------ 2975 | // format status buffer, with STANDOUT mode 2976 | static void status_line_bold(const char *format, ...) 2977 | { 2978 | va_list args; 2979 | 2980 | va_start(args, format); 2981 | strcpy(status_buffer, SOs); // Terminal standout mode on 2982 | vsprintf(status_buffer + sizeof(SOs)-1, format, args); 2983 | strcat(status_buffer, SOn); // Terminal standout mode off 2984 | va_end(args); 2985 | } 2986 | 2987 | // format status buffer 2988 | static void status_line(const char *format, ...) 2989 | { 2990 | va_list args; 2991 | 2992 | va_start(args, format); 2993 | vsprintf(status_buffer, format, args); 2994 | va_end(args); 2995 | } 2996 | 2997 | // copy s to buf, convert unprintable 2998 | static void print_literal(char *buf, const char *s) 2999 | { 3000 | unsigned char c; 3001 | char b[2]; 3002 | 3003 | b[1] = '\0'; 3004 | buf[0] = '\0'; 3005 | if (!s[0]) 3006 | s = "(NULL)"; 3007 | for (; *s; s++) { 3008 | int c_is_no_print; 3009 | 3010 | c = *s; 3011 | c_is_no_print = (c & 0x80) && !Isprint(c); 3012 | if (c_is_no_print) { 3013 | strcat(buf, SOn); 3014 | c = '.'; 3015 | } 3016 | if (c < ' ' || c == 127) { 3017 | strcat(buf, "^"); 3018 | if (c == 127) 3019 | c = '?'; 3020 | else 3021 | c += '@'; 3022 | } 3023 | b[0] = c; 3024 | strcat(buf, b); 3025 | if (c_is_no_print) 3026 | strcat(buf, SOs); 3027 | if (*s == '\n') 3028 | strcat(buf, "$"); 3029 | if (strlen(buf) > MAX_INPUT_LEN - 10) // paranoia 3030 | break; 3031 | } 3032 | } 3033 | 3034 | static void not_implemented(const char *s) 3035 | { 3036 | char buf[MAX_INPUT_LEN]; 3037 | 3038 | print_literal(buf, s); 3039 | status_line_bold("\'%s\' is not implemented", buf); 3040 | } 3041 | 3042 | // show file status on status line 3043 | static int format_edit_status(const char *fmt) 3044 | { 3045 | #define tot format_edit_status__tot 3046 | 3047 | int cur, percent, ret, trunc_at; 3048 | 3049 | // file_modified is now a counter rather than a flag. this 3050 | // helps reduce the amount of line counting we need to do. 3051 | // (this will cause a mis-reporting of modified status 3052 | // once every MAXINT editing operations.) 3053 | 3054 | // it would be nice to do a similar optimization here -- if 3055 | // we haven't done a motion that could have changed which line 3056 | // we're on, then we shouldn't have to do this count_lines() 3057 | cur = count_lines(text, dot); 3058 | 3059 | // reduce counting -- the total lines can't have 3060 | // changed if we haven't done any edits. 3061 | if (file_modified != last_file_modified) { 3062 | tot = cur + count_lines(dot, end - 1) - 1; 3063 | last_file_modified = file_modified; 3064 | } 3065 | 3066 | // current line percent 3067 | // ------------- ~~ ---------- 3068 | // total lines 100 3069 | if (tot > 0) { 3070 | percent = (100 * cur) / tot; 3071 | } else { 3072 | cur = tot = 0; 3073 | percent = 100; 3074 | } 3075 | 3076 | trunc_at = columns < STATUS_BUFFER_LEN-1 ? 3077 | columns : STATUS_BUFFER_LEN-1; 3078 | 3079 | ret = snprintf(status_buffer, trunc_at+1, fmt, 3080 | cmd_mode_indicator[cmd_mode & CMODES], 3081 | (current_filename != NULL ? current_filename : "No file"), 3082 | #if ENABLE_FEATURE_VI_READONLY 3083 | (readonly_mode ? " [Readonly]" : ""), 3084 | #endif 3085 | (file_modified ? " [Modified]" : ""), 3086 | cur, tot, percent, offset+ccol+1, cmdcnt); 3087 | 3088 | if (ret >= 0 && ret < trunc_at) 3089 | return ret; /* it all fit */ 3090 | 3091 | return trunc_at; /* had to truncate */ 3092 | #undef tot 3093 | } 3094 | 3095 | //----- Force refresh of all Lines ----------------------------- 3096 | static void redraw(void) 3097 | { 3098 | clear_screen(); //clear teminal screen and our image of it 3099 | screen_erase(); 3100 | refresh(); 3101 | } 3102 | 3103 | //----- Format a text[] line into a buffer --------------------- 3104 | static char* format_line(char *src /*, int li*/) 3105 | { 3106 | unsigned char c; 3107 | int co; 3108 | int ofs = offset; 3109 | char *dest = scr_out_buf; // [MAX_SCR_COLS + MAX_TABSTOP * 2] 3110 | 3111 | c = '~'; // char in col 0 in non-existent lines is '~' 3112 | co = 0; 3113 | while (co < columns + tabstop) { 3114 | // have we gone past the end? 3115 | if (src < end) { 3116 | c = *src++; 3117 | if (c == '\n') 3118 | break; 3119 | if ((c & 0x80) && !Isprint(c)) { 3120 | c = '.'; 3121 | } 3122 | if (c < ' ' || c == 0x7f) { 3123 | if (c == '\t') { 3124 | c = ' '; 3125 | // co % 8 != 7 3126 | while ((co % tabstop) != (tabstop - 1)) { 3127 | dest[co++] = c; 3128 | } 3129 | } else { 3130 | dest[co++] = '^'; 3131 | if (c == 0x7f) 3132 | c = '?'; 3133 | else 3134 | c += '@'; // Ctrl-X -> 'X' 3135 | } 3136 | } 3137 | } 3138 | dest[co++] = c; 3139 | // discard scrolled-off-to-the-left portion, 3140 | // in tabstop-sized pieces 3141 | if (ofs >= tabstop && co >= tabstop) { 3142 | memmove(dest, dest + tabstop, co); 3143 | co -= tabstop; 3144 | ofs -= tabstop; 3145 | } 3146 | if (src >= end) 3147 | break; 3148 | } 3149 | // check "short line, gigantic offset" case 3150 | if (co < ofs) 3151 | ofs = co; 3152 | // discard last scrolled off part 3153 | co -= ofs; 3154 | dest += ofs; 3155 | // fill the rest with spaces 3156 | if (co < columns) 3157 | memset(&dest[co], ' ', columns - co); 3158 | return dest; 3159 | } 3160 | 3161 | //----- Refresh the changed screen lines ----------------------- 3162 | // Copy the source line from text[] into the buffer and note 3163 | // if the current screenline is different from the new buffer. 3164 | // If they differ then that line needs redrawing on the terminal. 3165 | // 3166 | static void refresh(void) 3167 | { 3168 | #define old_offset refresh__old_offset 3169 | 3170 | int li, changed; 3171 | char *tp, *sp; // pointer into text[] and screen[] 3172 | 3173 | // poll to see if there is input already waiting. if we are 3174 | // not able to display output fast enough to keep up, skip 3175 | // the display update until we catch up with input. 3176 | if (chars_to_parse || awaitInput(0)) 3177 | return; 3178 | 3179 | sync_cursor(dot, &crow, &ccol); // where cursor will be (on "dot") 3180 | tp = screenbegin; // index into text[] of top line 3181 | 3182 | // compare text[] to screen[] and mark screen[] lines that need updating 3183 | for (li = 0; li < rows - 1 && !awaitInput(0); li++) { 3184 | int cs, ce; // column start & end 3185 | char *out_buf; 3186 | // format current text line 3187 | out_buf = format_line(tp /*, li*/); 3188 | 3189 | // skip to the end of the current text[] line 3190 | if (tp < end) { 3191 | char *t = memchr(tp, '\n', end - tp); 3192 | if (!t) t = end - 1; 3193 | tp = t + 1; 3194 | } 3195 | 3196 | // see if there are any changes between vitual screen and out_buf 3197 | changed = FALSE; // assume no change 3198 | cs = 0; 3199 | ce = columns - 1; 3200 | sp = &screen[li * columns]; // start of screen line 3201 | // compare newly formatted buffer with virtual screen 3202 | // look forward for first difference between buf and screen 3203 | for (; cs <= ce; cs++) { 3204 | if (out_buf[cs] != sp[cs]) { 3205 | changed = TRUE; // mark for redraw 3206 | break; 3207 | } 3208 | } 3209 | 3210 | // look backward for last difference between out_buf and screen 3211 | for (; ce >= cs; ce--) { 3212 | if (out_buf[ce] != sp[ce]) { 3213 | changed = TRUE; // mark for redraw 3214 | break; 3215 | } 3216 | } 3217 | // now, cs is index of first diff, and ce is index of last diff 3218 | 3219 | // if horz offset has changed, force a redraw 3220 | if (offset != old_offset) { 3221 | changed = TRUE; 3222 | } 3223 | 3224 | // make a sanity check of columns indexes 3225 | if (cs < 0) cs = 0; 3226 | if (ce > columns - 1) ce = columns - 1; 3227 | if (cs > ce) { cs = 0; ce = columns - 1; } 3228 | // is there a change between virtual screen and out_buf 3229 | if (changed) { 3230 | // copy changed part of buffer to virtual screen 3231 | memcpy(sp+cs, out_buf+cs, ce-cs+1); 3232 | 3233 | // move cursor to column of first change 3234 | //if (offset != old_offset) { 3235 | // // place_cursor is still too stupid 3236 | // // to handle offsets correctly 3237 | // place_cursor(li, cs, FALSE); 3238 | //} else { 3239 | place_cursor(li, cs, TRUE); 3240 | //} 3241 | 3242 | // write line out to terminal 3243 | fwrite(&sp[cs], ce - cs + 1, 1, stdout); 3244 | } 3245 | } 3246 | 3247 | place_cursor(crow, ccol, TRUE); 3248 | 3249 | old_offset = offset; 3250 | #undef old_offset 3251 | show_status_line(); 3252 | } 3253 | 3254 | //--------------------------------------------------------------------- 3255 | //----- the Ascii Chart ----------------------------------------------- 3256 | // 3257 | // 00 nul 01 soh 02 stx 03 etx 04 eot 05 enq 06 ack 07 bel 3258 | // 08 bs 09 ht 0a nl 0b vt 0c np 0d cr 0e so 0f si 3259 | // 10 dle 11 dc1 12 dc2 13 dc3 14 dc4 15 nak 16 syn 17 etb 3260 | // 18 can 19 em 1a sub 1b esc 1c fs 1d gs 1e rs 1f us 3261 | // 20 sp 21 ! 22 " 23 # 24 $ 25 % 26 & 27 ' 3262 | // 28 ( 29 ) 2a * 2b + 2c , 2d - 2e . 2f / 3263 | // 30 0 31 1 32 2 33 3 34 4 35 5 36 6 37 7 3264 | // 38 8 39 9 3a : 3b ; 3c < 3d = 3e > 3f ? 3265 | // 40 @ 41 A 42 B 43 C 44 D 45 E 46 F 47 G 3266 | // 48 H 49 I 4a J 4b K 4c L 4d M 4e N 4f O 3267 | // 50 P 51 Q 52 R 53 S 54 T 55 U 56 V 57 W 3268 | // 58 X 59 Y 5a Z 5b [ 5c \ 5d ] 5e ^ 5f _ 3269 | // 60 ` 61 a 62 b 63 c 64 d 65 e 66 f 67 g 3270 | // 68 h 69 i 6a j 6b k 6c l 6d m 6e n 6f o 3271 | // 70 p 71 q 72 r 73 s 74 t 75 u 76 v 77 w 3272 | // 78 x 79 y 7a z 7b { 7c | 7d } 7e ~ 7f del 3273 | //--------------------------------------------------------------------- 3274 | 3275 | //----- Execute a Vi Command ----------------------------------- 3276 | static void do_cmd(char c) 3277 | { 3278 | const char *msg; 3279 | char c1, *p, *q, *save_dot; 3280 | char buf[12]; 3281 | int dir, cnt, i, j; 3282 | 3283 | again: 3284 | /* if this is a cursor key, skip these checks */ 3285 | switch (c) { 3286 | case VI_K_UP: 3287 | case VI_K_DOWN: 3288 | case VI_K_LEFT: 3289 | case VI_K_RIGHT: 3290 | case VI_K_HOME: 3291 | case VI_K_END: 3292 | case VI_K_PAGEUP: 3293 | case VI_K_PAGEDOWN: 3294 | goto key_cmd_mode; 3295 | } 3296 | 3297 | if (cmd_mode == CMODE_REPLACE) { 3298 | // flip-flop Insert/Replace mode 3299 | if (c == VI_K_INSERT) 3300 | goto dc_i; 3301 | // we are 'R'eplacing the current *dot with new char 3302 | if (*dot == '\n') { 3303 | // don't Replace past E-o-l 3304 | cmd_mode = CMODE_INSERT; // convert to insert 3305 | } else { 3306 | if (1 <= c || Isprint(c)) { 3307 | if (c != 27) 3308 | dot = yank_delete(dot, dot, 0, YANKDEL); // delete char 3309 | dot = char_insert(dot, c); // insert new char 3310 | } 3311 | goto dc1; 3312 | } 3313 | } 3314 | if (cmd_mode == CMODE_INSERT) { 3315 | // hitting "Insert" twice means "R" replace mode 3316 | if (c == VI_K_INSERT) goto dc5; 3317 | // insert the char c at "dot" 3318 | if (1 <= c || Isprint(c)) { 3319 | dot = char_insert(dot, c); 3320 | } 3321 | goto dc1; 3322 | } 3323 | 3324 | key_cmd_mode: 3325 | switch (c) { 3326 | //case 0x01: // soh 3327 | //case 0x09: // ht 3328 | //case 0x0b: // vt 3329 | //case 0x0e: // so 3330 | //case 0x0f: // si 3331 | //case 0x10: // dle 3332 | //case 0x11: // dc1 3333 | //case 0x13: // dc3 3334 | #if ENABLE_FEATURE_VI_CRASHME 3335 | case 0x14: // dc4 ctrl-T 3336 | crashme = (crashme == 0) ? 1 : 0; 3337 | break; 3338 | #endif 3339 | //case 0x16: // syn 3340 | //case 0x17: // etb 3341 | //case 0x18: // can 3342 | //case 0x1c: // fs 3343 | //case 0x1d: // gs 3344 | //case 0x1e: // rs 3345 | //case 0x1f: // us 3346 | //case '!': // !- 3347 | //case '#': // #- 3348 | //case '&': // &- 3349 | //case '(': // (- 3350 | //case ')': // )- 3351 | //case '*': // *- 3352 | //case '=': // =- 3353 | //case '@': // @- 3354 | //case 'F': // F- 3355 | //case 'K': // K- 3356 | //case 'Q': // Q- 3357 | //case 'S': // S- 3358 | //case 'T': // T- 3359 | //case 'V': // V- 3360 | //case '[': // [- 3361 | //case '\\': // \- 3362 | //case ']': // ]- 3363 | //case '_': // _- 3364 | //case '`': // `- 3365 | //case 'u': // u- FIXME- there is no undo 3366 | //case 'v': // v- 3367 | default: // unrecognised command 3368 | buf[0] = c; 3369 | buf[1] = '\0'; 3370 | if (c < ' ') { 3371 | buf[0] = '^'; 3372 | buf[1] = c + '@'; 3373 | buf[2] = '\0'; 3374 | } 3375 | not_implemented(buf); 3376 | end_cmd_q(); // stop adding to q 3377 | case 0x00: // nul- ignore 3378 | break; 3379 | case 2: // ctrl-B scroll up full screen 3380 | case VI_K_PAGEUP: // Cursor Key Page Up 3381 | dot_scroll(rows - 2, -1); 3382 | break; 3383 | case 4: // ctrl-D scroll down half screen 3384 | dot_scroll((rows - 2) / 2, 1); 3385 | break; 3386 | case 5: // ctrl-E scroll down one line 3387 | dot_scroll(1, 1); 3388 | break; 3389 | case 6: // ctrl-F scroll down full screen 3390 | case VI_K_PAGEDOWN: // Cursor Key Page Down 3391 | dot_scroll(rows - 2, 1); 3392 | break; 3393 | case 7: // ctrl-G show current status 3394 | format_edit_status(EDIT_STATUS " col %d"); 3395 | break; 3396 | case 'h': // h- move left 3397 | case VI_K_LEFT: // cursor key Left 3398 | case 8: // ctrl-H- move left (This may be ERASE char) 3399 | case 0x7f: // DEL- move left (This may be ERASE char) 3400 | dot_left(); 3401 | repeat: 3402 | if (cmdcnt-- > 1) 3403 | goto again; 3404 | break; 3405 | case 10: // Newline ^J 3406 | case 'j': // j- goto next line, same col 3407 | case VI_K_DOWN: // cursor key Down 3408 | dot_next(); // go to next B-o-l 3409 | dot = move_to_col(dot, ccol + offset); // try stay in same col 3410 | goto repeat; 3411 | case 12: // ctrl-L force redraw whole screen 3412 | case 18: // ctrl-R force redraw 3413 | createScreen(); 3414 | redraw(); 3415 | break; 3416 | case 13: // Carriage Return ^M 3417 | case '+': // +- goto next line 3418 | dot_next(); 3419 | dot_skip_over_ws(); 3420 | goto repeat; 3421 | case 21: // ctrl-U scroll up half screen 3422 | dot_scroll((rows - 2) / 2, -1); 3423 | break; 3424 | case 25: // ctrl-Y scroll up one line 3425 | dot_scroll(1, -1); 3426 | break; 3427 | case 27: // esc 3428 | if (cmd_mode == CMODE_COMMAND) 3429 | indicate_error(c); 3430 | cmd_mode = CMODE_COMMAND; // stop insrting 3431 | end_cmd_q(); 3432 | break; 3433 | case ' ': // move right 3434 | case 'l': // move right 3435 | case VI_K_RIGHT: // Cursor Key Right 3436 | dot_right(); 3437 | goto repeat; 3438 | #if ENABLE_FEATURE_VI_YANKMARK 3439 | case '"': // "- name a register to use for Delete/Yank 3440 | c1 = get_one_char(); 3441 | c1 = tolower(c1); 3442 | if (islower(c1)) { 3443 | YDreg = c1 - 'a'; 3444 | } else { 3445 | indicate_error(c); 3446 | } 3447 | break; 3448 | case '\'': // '- goto a specific mark 3449 | c1 = get_one_char(); 3450 | c1 = tolower(c1); 3451 | if (islower(c1)) { 3452 | c1 = c1 - 'a'; 3453 | // get the b-o-l 3454 | q = mark[(unsigned char) c1]; 3455 | if (text <= q && q < end) { 3456 | dot = q; 3457 | dot_begin(); // go to B-o-l 3458 | dot_skip_over_ws(); 3459 | } 3460 | } else if (c1 == '\'') { // goto previous context 3461 | dot = swap_context(dot); // swap current and previous context 3462 | dot_begin(); // go to B-o-l 3463 | dot_skip_over_ws(); 3464 | } else { 3465 | indicate_error(c); 3466 | } 3467 | break; 3468 | case 'm': // m- Mark a line 3469 | // this is really stupid. If there are any inserts or deletes 3470 | // between text[0] and dot then this mark will not point to the 3471 | // correct location! It could be off by many lines! 3472 | // Well..., at least its quick and dirty. 3473 | c1 = get_one_char(); 3474 | c1 = tolower(c1); 3475 | if (islower(c1)) { 3476 | c1 = c1 - 'a'; 3477 | // remember the line 3478 | mark[(int) c1] = dot; 3479 | } else { 3480 | indicate_error(c); 3481 | } 3482 | break; 3483 | case 'P': // P- Put register before 3484 | case 'p': // p- put register after 3485 | p = reg[YDreg]; 3486 | if (p == 0) { 3487 | status_line_bold("Nothing in register %c", what_reg()); 3488 | break; 3489 | } 3490 | // are we putting whole lines or strings 3491 | if (strchr(p, '\n') != NULL) { 3492 | if (c == 'P') { 3493 | dot_begin(); // putting lines- Put above 3494 | } 3495 | if (c == 'p') { 3496 | // are we putting after very last line? 3497 | if (end_line(dot) == (end - 1)) { 3498 | dot = end; // force dot to end of text[] 3499 | } else { 3500 | dot_next(); // next line, then put before 3501 | } 3502 | } 3503 | } else { 3504 | if (c == 'p') 3505 | dot_right(); // move to right, can move to NL 3506 | } 3507 | dot = string_insert(dot, p); // insert the string 3508 | end_cmd_q(); // stop adding to q 3509 | break; 3510 | case 'U': // U- Undo; replace current line with original version 3511 | if (reg[Ureg] != 0) { 3512 | p = begin_line(dot); 3513 | q = end_line(dot); 3514 | p = text_hole_delete(p, q); // delete cur line 3515 | p = string_insert(p, reg[Ureg]); // insert orig line 3516 | dot = p; 3517 | dot_skip_over_ws(); 3518 | } 3519 | break; 3520 | #endif /* FEATURE_VI_YANKMARK */ 3521 | case '$': // $- goto end of line 3522 | case VI_K_END: // Cursor Key End 3523 | dot = end_line(dot); 3524 | goto repeat; 3525 | case '%': // %- find matching char of pair () [] {} 3526 | for (q = dot; q < end && *q != '\n'; q++) { 3527 | if (strchr("()[]{}", *q) != NULL) { 3528 | // we found half of a pair 3529 | p = find_pair(q, *q); 3530 | if (p == NULL) { 3531 | indicate_error(c); 3532 | } else { 3533 | dot = p; 3534 | } 3535 | break; 3536 | } 3537 | } 3538 | if (*q == '\n') 3539 | indicate_error(c); 3540 | break; 3541 | case 'f': // f- forward to a user specified char 3542 | last_forward_char = get_one_char(); // get the search char 3543 | // 3544 | // dont separate these two commands. 'f' depends on ';' 3545 | // 3546 | //**** fall through to ... ';' 3547 | case ';': // ;- look at rest of line for last forward char 3548 | if (last_forward_char == 0) 3549 | break; 3550 | q = dot + 1; 3551 | while (q < end - 1 && *q != '\n' && *q != last_forward_char) { 3552 | q++; 3553 | } 3554 | if (*q == last_forward_char) 3555 | dot = q; 3556 | c = ';'; goto repeat; 3557 | case ',': // repeat latest 'f' in opposite direction 3558 | if (last_forward_char == 0) 3559 | break; 3560 | q = dot - 1; 3561 | while (q >= text && *q != '\n' && *q != last_forward_char) { 3562 | q--; 3563 | } 3564 | if (q >= text && *q == last_forward_char) 3565 | dot = q; 3566 | c = ','; goto repeat; 3567 | 3568 | case '-': // -- goto prev line 3569 | dot_prev(); 3570 | dot_skip_over_ws(); 3571 | goto repeat; 3572 | #if ENABLE_FEATURE_VI_DOT_CMD 3573 | case '.': // .- repeat the last modifying command 3574 | // Stuff the last_modifying_cmd back into stdin 3575 | // and let it be re-executed. 3576 | if (lmc_len > 0) { 3577 | last_modifying_cmd[lmc_len] = 0; 3578 | ioq = ioq_start = xstrdup(last_modifying_cmd); 3579 | } 3580 | break; 3581 | #endif 3582 | #if ENABLE_FEATURE_VI_SEARCH 3583 | case '?': // /- search for a pattern 3584 | case '/': // /- search for a pattern 3585 | buf[0] = c; 3586 | buf[1] = '\0'; 3587 | q = get_input_line(buf); // get input line- use "status line" 3588 | if (!*q) 3589 | break; // bail out if user erased the entire pattern 3590 | if (q[1]) { // strlen(q) > 1: new pat- save it and find 3591 | free(last_search_pattern); 3592 | last_search_pattern = xstrdup(q); 3593 | goto findNormal; // new pattern determines search direction 3594 | } //Reuse pattern. If c=='?', search in direction opposite pattern's 3595 | if (c == '/') 3596 | goto findNormal; 3597 | c = 'N'; 3598 | case 'N': // N- repeat search in opposite direction of last pattern 3599 | dir = BACK; //BACK here means "opposite" pattern's spec'd direction 3600 | goto findPattern; 3601 | 3602 | findNormal: 3603 | c = 'n'; 3604 | case 'n': // n- repeat search for last pattern in "normal" direction 3605 | // search rest of text[] starting at next char 3606 | // if search fails return orignal "p" not the "p+1" address 3607 | dir = FORWARD; //in pattern's spec'd direction 3608 | findPattern: 3609 | if (!last_search_pattern) { 3610 | msg = "No previous regular expression"; 3611 | goto dc2; 3612 | } //derive absolute search direction from that relative to pattern's 3613 | if (*last_search_pattern == '?') 3614 | dir = -dir; //relies on FORWARD/BACK being 1/-1, respectively 3615 | p = dot + dir; 3616 | q = char_search(p, last_search_pattern + 1, dir, FULL); 3617 | if (q != NULL) { 3618 | dot = q; // good search, update "dot" 3619 | goto repeat; 3620 | } 3621 | // no pattern found between "dot" and "end"- continue at top 3622 | p = text; 3623 | if (dir == BACK) { 3624 | p = end - 1; 3625 | } 3626 | q = char_search(p, last_search_pattern + 1, dir, FULL); 3627 | if (q != NULL) { // found something 3628 | dot = q; // found new pattern- goto it 3629 | msg = "search hit BOTTOM, continuing at TOP"; 3630 | if (dir == BACK) 3631 | msg = "search hit TOP, continuing at BOTTOM"; 3632 | } else 3633 | msg = "Pattern not found"; 3634 | dc2: 3635 | status_line_bold("%s", msg); 3636 | break; 3637 | case '{': // {- move backward paragraph 3638 | q = char_search(dot, "\n\n", BACK, FULL); 3639 | if (q != NULL) { // found blank line 3640 | dot = next_line(q); // move to next blank line 3641 | } 3642 | break; 3643 | case '}': // }- move forward paragraph 3644 | q = char_search(dot, "\n\n", FORWARD, FULL); 3645 | if (q != NULL) { // found blank line 3646 | dot = next_line(q); // move to next blank line 3647 | } 3648 | break; 3649 | #endif /* FEATURE_VI_SEARCH */ 3650 | case '0': // 0- goto begining of line 3651 | case '1': // 1- 3652 | case '2': // 2- 3653 | case '3': // 3- 3654 | case '4': // 4- 3655 | case '5': // 5- 3656 | case '6': // 6- 3657 | case '7': // 7- 3658 | case '8': // 8- 3659 | case '9': // 9- 3660 | if (c == '0' && cmdcnt < 1) { 3661 | dot_begin(); // this was a standalone zero 3662 | } else { 3663 | if (cmdcnt >= INT_MAX/10) { 3664 | cmdcnt = 0; 3665 | status_line_bold("Repeat Count OVERFLOW"); 3666 | return; 3667 | } 3668 | cmdcnt = cmdcnt * 10 + (c - '0'); // this 0 is part of a number 3669 | if (cmdcnt!=1) 3670 | format_edit_status(EDIT_STATUS " col %d {%d times}"); 3671 | } 3672 | break; 3673 | case ':': // :- the colon mode commands 3674 | p = get_input_line(":"); // get input line- use "status line" 3675 | #if ENABLE_FEATURE_VI_COLON 3676 | colon(p); // execute the command 3677 | #else 3678 | if (*p == ':') 3679 | p++; // move past the ':' 3680 | cnt = strlen(p); 3681 | if (cnt <= 0) 3682 | break; 3683 | if (strncasecmp(p, "quit", cnt) == 0 3684 | || strncasecmp(p, "q!", cnt) == 0 // delete lines 3685 | ) { 3686 | if (file_modified && p[1] != '!') { 3687 | status_line_bold("No write since last change (:quit! overrides)"); 3688 | } else { 3689 | editing = 0; 3690 | } 3691 | } else if (strncasecmp(p, "write", cnt) == 0 3692 | || strncasecmp(p, "wq", cnt) == 0 3693 | || strncasecmp(p, "wn", cnt) == 0 3694 | || strncasecmp(p, "x", cnt) == 0 3695 | ) { 3696 | cnt = file_write(current_filename, text, end - 1); 3697 | if (cnt < 0) { 3698 | if (cnt == -1) 3699 | status_line_bold("Write error: %s", strerror(errno)); 3700 | } else { 3701 | file_modified = 0; 3702 | last_file_modified = -1; 3703 | status_line("\"%s\" %dL, %dC", current_filename, count_lines(text, end - 1), cnt); 3704 | if (p[0] == 'x' || p[1] == 'q' || p[1] == 'n' 3705 | || p[0] == 'X' || p[1] == 'Q' || p[1] == 'N' 3706 | ) { 3707 | editing = 0; 3708 | } 3709 | } 3710 | } else if (strncasecmp(p, "file", cnt)) 3711 | if (sscanf(p, "%d", &j) > 0) { 3712 | dot = find_line(j); // go to line # j 3713 | dot_skip_over_ws(); 3714 | } else { // unrecognised cmd 3715 | not_implemented(p); 3716 | } 3717 | #endif /* !FEATURE_VI_COLON */ 3718 | break; 3719 | case '<': // <- Left shift something 3720 | case '>': // >- Right shift something 3721 | cnt = count_lines(text, dot); // remember what line we are on 3722 | c1 = get_one_char(); // get the type of thing to delete 3723 | find_range(&p, &q, c1); 3724 | yank_delete(p, q, 1, YANKONLY); // save copy before change 3725 | p = begin_line(p); 3726 | q = end_line(q); 3727 | i = count_lines(p, q); // # of lines we are shifting 3728 | for ( ; i > 0; i--, p = next_line(p)) { 3729 | if (c == '<') { 3730 | // shift left- remove tab or 8 spaces 3731 | if (*p == '\t') { 3732 | // shrink buffer 1 char 3733 | text_hole_delete(p, p); 3734 | } else if (*p == ' ') { 3735 | // we should be calculating columns, not just SPACE 3736 | for (j = 0; *p == ' ' && j < tabstop; j++) { 3737 | text_hole_delete(p, p); 3738 | } 3739 | } 3740 | } else if (c == '>') { 3741 | // shift right -- add tab or 8 spaces 3742 | char_insert(p, '\t'); 3743 | } 3744 | } 3745 | dot = find_line(cnt); // what line were we on 3746 | dot_skip_over_ws(); 3747 | end_cmd_q(); // stop adding to q 3748 | break; 3749 | case 'A': // A- append at e-o-l 3750 | dot_end(); // go to e-o-l 3751 | //**** fall through to ... 'a' 3752 | case 'a': // a- append after current char 3753 | if (*dot != '\n') 3754 | dot++; 3755 | goto dc_i; 3756 | break; 3757 | case 'B': // B- back a blank-delimited Word 3758 | case 'E': // E- end of a blank-delimited word 3759 | case 'W': // W- forward a blank-delimited word 3760 | dir = FORWARD; 3761 | if (c == 'B') 3762 | dir = BACK; 3763 | if (c == 'W' || isspace(dot[dir])) { 3764 | dot = skip_thing(dot, 1, dir, S_TO_WS); 3765 | dot = skip_thing(dot, 2, dir, S_OVER_WS); 3766 | } 3767 | if (c != 'W') 3768 | dot = skip_thing(dot, 1, dir, S_BEFORE_WS); 3769 | goto repeat; 3770 | case 'C': // C- Change to e-o-l 3771 | case 'D': // D- delete to e-o-l 3772 | save_dot = dot; 3773 | dot = dollar_line(dot); // move to before NL 3774 | // copy text into a register and delete 3775 | dot = yank_delete(save_dot, dot, 0, YANKDEL); // delete to e-o-l 3776 | if (c == 'C') 3777 | goto dc_i; // start inserting 3778 | #if ENABLE_FEATURE_VI_DOT_CMD 3779 | if (c == 'D') 3780 | end_cmd_q(); // stop adding to q 3781 | #endif 3782 | break; 3783 | case 'g': // 'gg' goto a line number (from vim) 3784 | // (default to first line in file) 3785 | c1 = get_one_char(); 3786 | if (c1 != 'g') { 3787 | buf[0] = 'g'; 3788 | buf[1] = c1; 3789 | buf[2] = '\0'; 3790 | not_implemented(buf); 3791 | break; 3792 | } 3793 | if (cmdcnt == 0) 3794 | cmdcnt = 1; 3795 | /* fall through */ 3796 | case 'G': // G- goto to a line number (default= E-O-F) 3797 | dot = end - 1; // assume E-O-F 3798 | if (cmdcnt > 0) { 3799 | dot = find_line(cmdcnt); // what line is #cmdcnt 3800 | } 3801 | dot_skip_over_ws(); 3802 | break; 3803 | case 'H': // H- goto top line on screen 3804 | dot = screenbegin; 3805 | if (cmdcnt > (rows - 1)) { 3806 | cmdcnt = (rows - 1); 3807 | } 3808 | if (cmdcnt-- > 1) { 3809 | do_cmd('+'); 3810 | } // repeat cnt 3811 | dot_skip_over_ws(); 3812 | break; 3813 | case 'I': // I- insert before first non-blank 3814 | dot_begin(); // 0 3815 | dot_skip_over_ws(); 3816 | //**** fall through to ... 'i' 3817 | case 'i': // i- insert before current char 3818 | case VI_K_INSERT: // Cursor Key Insert 3819 | dc_i: 3820 | cmd_mode = CMODE_INSERT; // start insrting 3821 | break; 3822 | case 'J': // J- join current and next lines together 3823 | dot_end(); // move to NL 3824 | if (dot < end - 1) { // make sure not last char in text[] 3825 | *dot++ = ' '; // replace NL with space 3826 | file_modified++; 3827 | while (isblank(*dot)) { // delete leading WS 3828 | dot_delete(); 3829 | } 3830 | } 3831 | end_cmd_q(); // stop adding to q 3832 | if (cmdcnt-- > 2) 3833 | goto again; 3834 | break; 3835 | case 'L': // L- goto bottom line on screen 3836 | dot = end_screen(); 3837 | if (cmdcnt > (rows - 1)) { 3838 | cmdcnt = (rows - 1); 3839 | } 3840 | if (cmdcnt-- > 1) { 3841 | do_cmd('-'); 3842 | } // repeat cnt 3843 | dot_begin(); 3844 | dot_skip_over_ws(); 3845 | break; 3846 | case 'M': // M- goto middle line on screen 3847 | dot = screenbegin; 3848 | for (cnt = 0; cnt < (rows-1) / 2; cnt++) 3849 | dot = next_line(dot); 3850 | break; 3851 | case 'O': // O- open a empty line above 3852 | // 0i\n ESC -i 3853 | p = begin_line(dot); 3854 | if (p[-1] == '\n') { 3855 | dot_prev(); 3856 | case 'o': // o- open a empty line below; Yes, I know it is in the middle of the "if (..." 3857 | dot_end(); 3858 | dot = char_insert(dot, '\n'); 3859 | } else { 3860 | dot_begin(); // 0 3861 | dot = char_insert(dot, '\n'); // i\n ESC 3862 | dot_prev(); // - 3863 | } 3864 | goto dc_i; 3865 | break; 3866 | case 'R': // R- continuous Replace char 3867 | dc5: 3868 | cmd_mode = CMODE_REPLACE; 3869 | break; 3870 | case VI_K_DELETE: 3871 | c = 'x'; 3872 | // fall through 3873 | case 'X': // X- delete char before dot 3874 | case 'x': // x- delete the current char 3875 | case 's': // s- substitute the current char 3876 | dir = 0; 3877 | if (c == 'X') 3878 | dir = -1; 3879 | if (dot[dir] != '\n') { 3880 | if (c == 'X') 3881 | dot--; // delete prev char 3882 | dot = yank_delete(dot, dot, 0, YANKDEL); // delete char 3883 | } 3884 | if (c == 's') 3885 | goto dc_i; // start insrting 3886 | end_cmd_q(); // stop adding to q 3887 | goto repeat; 3888 | case 'Z': // Z- if modified, {write}; exit 3889 | // ZZ means to save file (if necessary), then exit 3890 | c1 = get_one_char(); 3891 | if (c1 != 'Z') { 3892 | indicate_error(c); 3893 | break; 3894 | } 3895 | if (file_modified) { 3896 | if (ENABLE_FEATURE_VI_READONLY && readonly_mode) { 3897 | status_line_bold("\"%s\" File is read only", current_filename); 3898 | break; 3899 | } 3900 | cnt = file_write(current_filename, text, end - 1); 3901 | if (cnt < 0) { 3902 | if (cnt == -1) 3903 | status_line_bold("Write error: %s", strerror(errno)); 3904 | } else if (cnt == (end - 1 - text + 1)) { 3905 | editing = 0; 3906 | } 3907 | } else { 3908 | editing = 0; 3909 | } 3910 | break; 3911 | case '^': // ^- move to first non-blank on line 3912 | dot_begin(); 3913 | dot_skip_over_ws(); 3914 | break; 3915 | case 'b': // b- back a word 3916 | case 'e': // e- end of word 3917 | dir = FORWARD; 3918 | if (c == 'b') 3919 | dir = BACK; 3920 | if ((dot + dir) < text || (dot + dir) > end - 1) 3921 | break; 3922 | dot += dir; 3923 | if (isspace(*dot)) { 3924 | dot = skip_thing(dot, (c == 'e') ? 2 : 1, dir, S_OVER_WS); 3925 | } 3926 | if (isalnum(*dot) || *dot == '_') { 3927 | dot = skip_thing(dot, 1, dir, S_END_ALNUM); 3928 | } else if (ispunct(*dot)) { 3929 | dot = skip_thing(dot, 1, dir, S_END_PUNCT); 3930 | } 3931 | goto repeat; 3932 | case 'c': // c- change something 3933 | case 'd': // d- delete something 3934 | #if ENABLE_FEATURE_VI_YANKMARK 3935 | case 'y': // y- yank something 3936 | case 'Y': // Y- Yank a line 3937 | #endif 3938 | { 3939 | int yf, ml, whole = 0; 3940 | yf = YANKDEL; // assume either "c" or "d" 3941 | #if ENABLE_FEATURE_VI_YANKMARK 3942 | if (c == 'y' || c == 'Y') 3943 | yf = YANKONLY; 3944 | #endif 3945 | c1 = 'y'; 3946 | if (c != 'Y') 3947 | c1 = get_one_char(); // get the type of thing to delete 3948 | // determine range, and whether it spans lines 3949 | ml = find_range(&p, &q, c1); 3950 | if (c1 == 27) { // ESC- user changed mind and wants out 3951 | c = c1 = 27; // Escape- do nothing 3952 | } else if (strchr("wW", c1)) { 3953 | if (c == 'c') { 3954 | // don't include trailing WS as part of word 3955 | while (isblank(*q)) { 3956 | if (q <= text || q[-1] == '\n') 3957 | break; 3958 | q--; 3959 | } 3960 | } 3961 | dot = yank_delete(p, q, ml, yf); // delete word 3962 | } else if (strchr("^0bBeEft%$ lh\b\177", c1)) { 3963 | // partial line copy text into a register and delete 3964 | dot = yank_delete(p, q, ml, yf); // delete word 3965 | } else if (strchr("cdykjHL+-{}\r\n", c1)) { 3966 | // whole line copy text into a register and delete 3967 | dot = yank_delete(p, q, ml, yf); // delete lines 3968 | whole = 1; 3969 | } else { 3970 | // could not recognize object 3971 | c = c1 = 27; // error- 3972 | ml = 0; 3973 | indicate_error(c); 3974 | } 3975 | if (ml && whole) { 3976 | if (c == 'c') { 3977 | dot = char_insert(dot, '\n'); 3978 | // on the last line of file don't move to prev line 3979 | if (whole && dot != (end-1)) { 3980 | dot_prev(); 3981 | } 3982 | } else if (c == 'd') { 3983 | dot_begin(); 3984 | dot_skip_over_ws(); 3985 | } 3986 | } 3987 | if (c1 != 27) { 3988 | // if CHANGING, not deleting, start inserting after the delete 3989 | if (c == 'c') { 3990 | strcpy(buf, "Change"); 3991 | goto dc_i; // start inserting 3992 | } 3993 | if (c == 'd') { 3994 | strcpy(buf, "Delete"); 3995 | } 3996 | #if ENABLE_FEATURE_VI_YANKMARK 3997 | if (c == 'y' || c == 'Y') { 3998 | strcpy(buf, "Yank"); 3999 | } 4000 | p = reg[YDreg]; 4001 | q = p + strlen(p); 4002 | for (cnt = 0; p <= q; p++) { 4003 | if (*p == '\n') 4004 | cnt++; 4005 | } 4006 | status_line("%s %d lines (%d chars) using [%c]", 4007 | buf, cnt, strlen(reg[YDreg]), what_reg()); 4008 | #endif 4009 | end_cmd_q(); // stop adding to q 4010 | } 4011 | } 4012 | break; 4013 | case 'k': // k- goto prev line, same col 4014 | case VI_K_UP: // cursor key Up 4015 | dot_prev(); 4016 | dot = move_to_col(dot, ccol + offset); // try stay in same col 4017 | goto repeat; 4018 | case 'r': // r- replace the current char with user input 4019 | c1 = get_one_char(); // get the replacement char 4020 | if (*dot != '\n') { 4021 | *dot = c1; 4022 | file_modified++; 4023 | } 4024 | end_cmd_q(); // stop adding to q 4025 | break; 4026 | case 't': // t- move to char prior to next x 4027 | last_forward_char = get_one_char(); 4028 | do_cmd(';'); 4029 | if (*dot == last_forward_char) 4030 | dot_left(); 4031 | last_forward_char= 0; 4032 | break; 4033 | case 'w': // w- forward a word 4034 | if (isalnum(*dot) || *dot == '_') { // we are on ALNUM 4035 | dot = skip_thing(dot, 1, FORWARD, S_END_ALNUM); 4036 | } else if (ispunct(*dot)) { // we are on PUNCT 4037 | dot = skip_thing(dot, 1, FORWARD, S_END_PUNCT); 4038 | } 4039 | if (dot < end - 1) 4040 | dot++; // move over word 4041 | if (isspace(*dot)) { 4042 | dot = skip_thing(dot, 2, FORWARD, S_OVER_WS); 4043 | } 4044 | goto repeat; 4045 | case 'z': // z- 4046 | c1 = get_one_char(); // get the replacement char 4047 | cnt = 0; 4048 | if (c1 == '.') 4049 | cnt = (rows - 2) / 2; // put dot at center 4050 | if (c1 == '-') 4051 | cnt = rows - 2; // put dot at bottom 4052 | screenbegin = begin_line(dot); // start dot at top 4053 | dot_scroll(cnt, -1); 4054 | break; 4055 | case '|': // |- move to column "cmdcnt" 4056 | dot = move_to_col(dot, cmdcnt - 1); // try to move to column 4057 | break; 4058 | case '~': // ~- flip the case of letters a-z -> A-Z 4059 | if (islower(*dot)) { 4060 | *dot = toupper(*dot); 4061 | file_modified++; 4062 | } else if (isupper(*dot)) { 4063 | *dot = tolower(*dot); 4064 | file_modified++; 4065 | } 4066 | dot_right(); 4067 | end_cmd_q(); // stop adding to q 4068 | goto repeat; 4069 | //----- The Cursor and Function Keys ----------------------------- 4070 | case VI_K_HOME: // Cursor Key Home 4071 | dot_begin(); 4072 | break; 4073 | // The Fn keys could point to do_macro which could translate them 4074 | case VI_K_FUN1: // Function Key F1 4075 | case VI_K_FUN2: // Function Key F2 4076 | case VI_K_FUN3: // Function Key F3 4077 | case VI_K_FUN4: // Function Key F4 4078 | case VI_K_FUN5: // Function Key F5 4079 | case VI_K_FUN6: // Function Key F6 4080 | case VI_K_FUN7: // Function Key F7 4081 | case VI_K_FUN8: // Function Key F8 4082 | case VI_K_FUN9: // Function Key F9 4083 | case VI_K_FUN10: // Function Key F10 4084 | case VI_K_FUN11: // Function Key F11 4085 | case VI_K_FUN12: // Function Key F12 4086 | break; 4087 | } 4088 | 4089 | dc1: 4090 | // if text[] just became empty, add back an empty line 4091 | if (end == text) { 4092 | char_insert(text, '\n'); // start empty buf with dummy line 4093 | dot = text; 4094 | } 4095 | // it is OK for dot to exactly equal to end, otherwise check dot validity 4096 | if (dot != end) { 4097 | dot = bound_dot(dot); // make sure "dot" is valid 4098 | } 4099 | #if ENABLE_FEATURE_VI_YANKMARK 4100 | check_context(c); // update the current context 4101 | #endif 4102 | 4103 | if (!isdigit(c)) 4104 | cmdcnt = 0; // cmd was not a number, reset cmdcnt 4105 | cnt = dot - begin_line(dot); 4106 | // Try to stay off of the Newline 4107 | if (*dot == '\n' && cnt > 0 && cmd_mode == CMODE_COMMAND) 4108 | dot--; 4109 | } 4110 | 4111 | /* NB! the CRASHME code is unmaintained, and doesn't currently build */ 4112 | #if ENABLE_FEATURE_VI_CRASHME 4113 | static int totalcmds = 0; 4114 | static int Mp = 85; // Movement command Probability 4115 | static int Np = 90; // Non-movement command Probability 4116 | static int Dp = 96; // Delete command Probability 4117 | static int Ip = 97; // Insert command Probability 4118 | static int Yp = 98; // Yank command Probability 4119 | static int Pp = 99; // Put command Probability 4120 | static int M = 0, N = 0, I = 0, D = 0, Y = 0, P = 0, U = 0; 4121 | static const char chars[20] = "\t012345 abcdABCD-=.$"; 4122 | static const char *const words[20] = { 4123 | "this", "is", "a", "test", 4124 | "broadcast", "the", "emergency", "of", 4125 | "system", "quick", "brown", "fox", 4126 | "jumped", "over", "lazy", "dogs", 4127 | "back", "January", "Febuary", "March" 4128 | }; 4129 | static const char *const lines[20] = { 4130 | "You should have received a copy of the GNU General Public License\n", 4131 | "char c, cm, *cmd, *cmd1;\n", 4132 | "generate a command by percentages\n", 4133 | "Numbers may be typed as a prefix to some commands.\n", 4134 | "Quit, discarding changes!\n", 4135 | "Forced write, if permission originally not valid.\n", 4136 | "In general, any ex or ed command (such as substitute or delete).\n", 4137 | "I have tickets available for the Blazers vs LA Clippers for Monday, Janurary 1 at 1:00pm.\n", 4138 | "Please get w/ me and I will go over it with you.\n", 4139 | "The following is a list of scheduled, committed changes.\n", 4140 | "1. Launch Norton Antivirus (Start, Programs, Norton Antivirus)\n", 4141 | "Reminder....Town Meeting in Central Perk cafe today at 3:00pm.\n", 4142 | "Any question about transactions please contact Sterling Huxley.\n", 4143 | "I will try to get back to you by Friday, December 31.\n", 4144 | "This Change will be implemented on Friday.\n", 4145 | "Let me know if you have problems accessing this;\n", 4146 | "Sterling Huxley recently added you to the access list.\n", 4147 | "Would you like to go to lunch?\n", 4148 | "The last command will be automatically run.\n", 4149 | "This is too much english for a computer geek.\n", 4150 | }; 4151 | static char *multilines[20] = { 4152 | "You should have received a copy of the GNU General Public License\n", 4153 | "char c, cm, *cmd, *cmd1;\n", 4154 | "generate a command by percentages\n", 4155 | "Numbers may be typed as a prefix to some commands.\n", 4156 | "Quit, discarding changes!\n", 4157 | "Forced write, if permission originally not valid.\n", 4158 | "In general, any ex or ed command (such as substitute or delete).\n", 4159 | "I have tickets available for the Blazers vs LA Clippers for Monday, Janurary 1 at 1:00pm.\n", 4160 | "Please get w/ me and I will go over it with you.\n", 4161 | "The following is a list of scheduled, committed changes.\n", 4162 | "1. Launch Norton Antivirus (Start, Programs, Norton Antivirus)\n", 4163 | "Reminder....Town Meeting in Central Perk cafe today at 3:00pm.\n", 4164 | "Any question about transactions please contact Sterling Huxley.\n", 4165 | "I will try to get back to you by Friday, December 31.\n", 4166 | "This Change will be implemented on Friday.\n", 4167 | "Let me know if you have problems accessing this;\n", 4168 | "Sterling Huxley recently added you to the access list.\n", 4169 | "Would you like to go to lunch?\n", 4170 | "The last command will be automatically run.\n", 4171 | "This is too much english for a computer geek.\n", 4172 | }; 4173 | 4174 | // create a random command to execute 4175 | static void crash_dummy() 4176 | { 4177 | static int sleeptime; // how long to pause between commands 4178 | char c, cm, *cmd, *cmd1; 4179 | int i, cnt, thing, rbi, startrbi, percent; 4180 | 4181 | // "dot" movement commands 4182 | cmd1 = " \n\r\002\004\005\006\025\0310^$-+wWeEbBhjklHL"; 4183 | 4184 | // is there already a command running? 4185 | if (chars_to_parse > 0) 4186 | goto cd1; 4187 | cd0: 4188 | startrbi = rbi = 0; 4189 | sleeptime = 0; // how long to pause between commands 4190 | memset(readbuffer, '\0', sizeof(readbuffer)); 4191 | // generate a command by percentages 4192 | percent = (int) lrand48() % 100; // get a number from 0-99 4193 | if (percent < Mp) { // Movement commands 4194 | // available commands 4195 | cmd = cmd1; 4196 | M++; 4197 | } else if (percent < Np) { // non-movement commands 4198 | cmd = "mz<>\'\""; // available commands 4199 | N++; 4200 | } else if (percent < Dp) { // Delete commands 4201 | cmd = "dx"; // available commands 4202 | D++; 4203 | } else if (percent < Ip) { // Inset commands 4204 | cmd = "iIaAsrJ"; // available commands 4205 | I++; 4206 | } else if (percent < Yp) { // Yank commands 4207 | cmd = "yY"; // available commands 4208 | Y++; 4209 | } else if (percent < Pp) { // Put commands 4210 | cmd = "pP"; // available commands 4211 | P++; 4212 | } else { 4213 | // We do not know how to handle this command, try again 4214 | U++; 4215 | goto cd0; 4216 | } 4217 | // randomly pick one of the available cmds from "cmd[]" 4218 | i = (int) lrand48() % strlen(cmd); 4219 | cm = cmd[i]; 4220 | if (strchr(":\024", cm)) 4221 | goto cd0; // dont allow colon or ctrl-T commands 4222 | readbuffer[rbi++] = cm; // put cmd into input buffer 4223 | 4224 | // now we have the command- 4225 | // there are 1, 2, and multi char commands 4226 | // find out which and generate the rest of command as necessary 4227 | if (strchr("dmryz<>\'\"", cm)) { // 2-char commands 4228 | cmd1 = " \n\r0$^-+wWeEbBhjklHL"; 4229 | if (cm == 'm' || cm == '\'' || cm == '\"') { // pick a reg[] 4230 | cmd1 = "abcdefghijklmnopqrstuvwxyz"; 4231 | } 4232 | thing = (int) lrand48() % strlen(cmd1); // pick a movement command 4233 | c = cmd1[thing]; 4234 | readbuffer[rbi++] = c; // add movement to input buffer 4235 | } 4236 | if (strchr("iIaAsc", cm)) { // multi-char commands 4237 | if (cm == 'c') { 4238 | // change some thing 4239 | thing = (int) lrand48() % strlen(cmd1); // pick a movement command 4240 | c = cmd1[thing]; 4241 | readbuffer[rbi++] = c; // add movement to input buffer 4242 | } 4243 | thing = (int) lrand48() % 4; // what thing to insert 4244 | cnt = (int) lrand48() % 10; // how many to insert 4245 | for (i = 0; i < cnt; i++) { 4246 | if (thing == 0) { // insert chars 4247 | readbuffer[rbi++] = chars[((int) lrand48() % strlen(chars))]; 4248 | } else if (thing == 1) { // insert words 4249 | strcat(readbuffer, words[(int) lrand48() % 20]); 4250 | strcat(readbuffer, " "); 4251 | sleeptime = 0; // how fast to type 4252 | } else if (thing == 2) { // insert lines 4253 | strcat(readbuffer, lines[(int) lrand48() % 20]); 4254 | sleeptime = 0; // how fast to type 4255 | } else { // insert multi-lines 4256 | strcat(readbuffer, multilines[(int) lrand48() % 20]); 4257 | sleeptime = 0; // how fast to type 4258 | } 4259 | } 4260 | strcat(readbuffer, "\033"); 4261 | } 4262 | chars_to_parse = strlen(readbuffer); 4263 | cd1: 4264 | totalcmds++; 4265 | if (sleeptime > 0) 4266 | awaitInput(sleeptime); // sleep 1/100 sec 4267 | } 4268 | 4269 | // test to see if there are any errors 4270 | static void crash_test() 4271 | { 4272 | static time_t oldtim; 4273 | 4274 | time_t tim; 4275 | char d[2], msg[80]; 4276 | 4277 | msg[0] = '\0'; 4278 | if (end < text) { 4279 | strcat(msg, "end textend) { 4282 | strcat(msg, "end>textend "); 4283 | } 4284 | if (dot < text) { 4285 | strcat(msg, "dot end) { 4288 | strcat(msg, "dot>end "); 4289 | } 4290 | if (screenbegin < text) { 4291 | strcat(msg, "screenbegin end - 1) { 4294 | strcat(msg, "screenbegin>end-1 "); 4295 | } 4296 | 4297 | if (msg[0]) { 4298 | printf("\n\n%d: \'%c\' %s\n\n\n%s[Hit return to continue]%s", 4299 | totalcmds, last_input_char, msg, SOs, SOn); 4300 | fflush(stdout); 4301 | while (safe_read(STDIN_FILENO, d, 1) > 0) { 4302 | if (d[0] == '\n' || d[0] == '\r') 4303 | break; 4304 | } 4305 | } 4306 | tim = time(NULL); 4307 | if (tim >= (oldtim + 3)) { 4308 | sprintf(status_buffer, 4309 | "Tot=%d: M=%d N=%d I=%d D=%d Y=%d P=%d U=%d size=%d", 4310 | totalcmds, M, N, I, D, Y, P, U, end - text + 1); 4311 | oldtim = tim; 4312 | } 4313 | } 4314 | #endif 4315 | --------------------------------------------------------------------------------