From 35ba6f0ff982060c9bc1fe9868092380d302646b Mon Sep 17 00:00:00 2001 From: JinWang An Date: Fri, 20 Jan 2023 12:37:01 +0900 Subject: [PATCH] Imported Upstream version 1.18 --- COPYING | 904 +++++++++++++++++------------------------------------ ChangeLog | 41 ++- INSTALL | 4 +- Makefile.in | 3 +- NEWS | 40 ++- README | 2 +- TODO | 8 - buffer.c | 103 +++--- carg_parser.c | 110 ++++--- carg_parser.h | 14 +- configure | 6 +- doc/ed.1 | 11 +- doc/ed.info | 266 +++++++++------- doc/ed.texi | 305 ++++++++++-------- ed.h | 24 +- global.c | 38 +-- io.c | 45 ++- main.c | 61 ++-- main_loop.c | 184 ++++++----- regex.c | 171 ++++++---- signal.c | 64 ++-- testsuite/check.sh | 2 +- testsuite/d.ed | 4 + testsuite/d.r | 4 - testsuite/g.ed | 4 +- testsuite/g4.err | 4 + testsuite/s.ed | 3 + testsuite/s22.err | 4 + 28 files changed, 1213 insertions(+), 1216 deletions(-) delete mode 100644 TODO create mode 100644 testsuite/g4.err create mode 100644 testsuite/s22.err diff --git a/COPYING b/COPYING index b27ad83..4ad17ae 100644 --- a/COPYING +++ b/COPYING @@ -1,626 +1,285 @@ - GNU GENERAL PUBLIC LICENSE - Version 3, 29 June 2007 + GNU GENERAL PUBLIC LICENSE + Version 2, June 1991 - Copyright (C) 2007 Free Software Foundation, Inc. + Copyright (C) 1989, 1991 Free Software Foundation, Inc., + 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. - Preamble + Preamble - The GNU General Public License is a free, copyleft license for -software and other kinds of works. - - The licenses for most software and other practical works are designed -to take away your freedom to share and change the works. By contrast, -the GNU General Public License is intended to guarantee your freedom to -share and change all versions of a program--to make sure it remains free -software for all its users. We, the Free Software Foundation, use the -GNU General Public License for most of our software; it applies also to -any other work released this way by its authors. You can apply it to + The licenses for most software are designed to take away your +freedom to share and change it. By contrast, the GNU General Public +License is intended to guarantee your freedom to share and change free +software--to make sure the software is free for all its users. This +General Public License applies to most of the Free Software +Foundation's software and to any other program whose authors commit to +using it. (Some other Free Software Foundation software is covered by +the GNU Lesser General Public License instead.) You can apply it to your programs, too. When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for -them if you wish), that you receive source code or can get it if you -want it, that you can change the software or use pieces of it in new -free programs, and that you know you can do these things. +this service if you wish), that you receive source code or can get it +if you want it, that you can change the software or use pieces of it +in new free programs; and that you know you can do these things. - To protect your rights, we need to prevent others from denying you -these rights or asking you to surrender the rights. Therefore, you have -certain responsibilities if you distribute copies of the software, or if -you modify it: responsibilities to respect the freedom of others. + To protect your rights, we need to make restrictions that forbid +anyone to deny you these rights or to ask you to surrender the rights. +These restrictions translate to certain responsibilities for you if you +distribute copies of the software, or if you modify it. For example, if you distribute copies of such a program, whether -gratis or for a fee, you must pass on to the recipients the same -freedoms that you received. You must make sure that they, too, receive -or can get the source code. And you must show them these terms so they -know their rights. - - Developers that use the GNU GPL protect your rights with two steps: -(1) assert copyright on the software, and (2) offer you this License -giving you legal permission to copy, distribute and/or modify it. - - For the developers' and authors' protection, the GPL clearly explains -that there is no warranty for this free software. For both users' and -authors' sake, the GPL requires that modified versions be marked as -changed, so that their problems will not be attributed erroneously to -authors of previous versions. - - Some devices are designed to deny users access to install or run -modified versions of the software inside them, although the manufacturer -can do so. This is fundamentally incompatible with the aim of -protecting users' freedom to change the software. The systematic -pattern of such abuse occurs in the area of products for individuals to -use, which is precisely where it is most unacceptable. Therefore, we -have designed this version of the GPL to prohibit the practice for those -products. If such problems arise substantially in other domains, we -stand ready to extend this provision to those domains in future versions -of the GPL, as needed to protect the freedom of users. - - Finally, every program is threatened constantly by software patents. -States should not allow patents to restrict development and use of -software on general-purpose computers, but in those that do, we wish to -avoid the special danger that patents applied to a free program could -make it effectively proprietary. To prevent this, the GPL assures that -patents cannot be used to render the program non-free. +gratis or for a fee, you must give the recipients all the rights that +you have. You must make sure that they, too, receive or can get the +source code. And you must show them these terms so they know their +rights. + + We protect your rights with two steps: (1) copyright the software, and +(2) offer you this license which gives you legal permission to copy, +distribute and/or modify the software. + + Also, for each author's protection and ours, we want to make certain +that everyone understands that there is no warranty for this free +software. If the software is modified by someone else and passed on, we +want its recipients to know that what they have is not the original, so +that any problems introduced by others will not reflect on the original +authors' reputations. + + Finally, any free program is threatened constantly by software +patents. We wish to avoid the danger that redistributors of a free +program will individually obtain patent licenses, in effect making the +program proprietary. To prevent this, we have made it clear that any +patent must be licensed for everyone's free use or not licensed at all. The precise terms and conditions for copying, distribution and modification follow. - TERMS AND CONDITIONS - - 0. Definitions. - - "This License" refers to version 3 of the GNU General Public License. - - "Copyright" also means copyright-like laws that apply to other kinds of -works, such as semiconductor masks. - - "The Program" refers to any copyrightable work licensed under this -License. Each licensee is addressed as "you". "Licensees" and -"recipients" may be individuals or organizations. - - To "modify" a work means to copy from or adapt all or part of the work -in a fashion requiring copyright permission, other than the making of an -exact copy. The resulting work is called a "modified version" of the -earlier work or a work "based on" the earlier work. - - A "covered work" means either the unmodified Program or a work based -on the Program. - - To "propagate" a work means to do anything with it that, without -permission, would make you directly or secondarily liable for -infringement under applicable copyright law, except executing it on a -computer or modifying a private copy. Propagation includes copying, -distribution (with or without modification), making available to the -public, and in some countries other activities as well. - - To "convey" a work means any kind of propagation that enables other -parties to make or receive copies. Mere interaction with a user through -a computer network, with no transfer of a copy, is not conveying. - - An interactive user interface displays "Appropriate Legal Notices" -to the extent that it includes a convenient and prominently visible -feature that (1) displays an appropriate copyright notice, and (2) -tells the user that there is no warranty for the work (except to the -extent that warranties are provided), that licensees may convey the -work under this License, and how to view a copy of this License. If -the interface presents a list of user commands or options, such as a -menu, a prominent item in the list meets this criterion. - - 1. Source Code. - - The "source code" for a work means the preferred form of the work -for making modifications to it. "Object code" means any non-source -form of a work. - - A "Standard Interface" means an interface that either is an official -standard defined by a recognized standards body, or, in the case of -interfaces specified for a particular programming language, one that -is widely used among developers working in that language. - - The "System Libraries" of an executable work include anything, other -than the work as a whole, that (a) is included in the normal form of -packaging a Major Component, but which is not part of that Major -Component, and (b) serves only to enable use of the work with that -Major Component, or to implement a Standard Interface for which an -implementation is available to the public in source code form. A -"Major Component", in this context, means a major essential component -(kernel, window system, and so on) of the specific operating system -(if any) on which the executable work runs, or a compiler used to -produce the work, or an object code interpreter used to run it. - - The "Corresponding Source" for a work in object code form means all -the source code needed to generate, install, and (for an executable -work) run the object code and to modify the work, including scripts to -control those activities. However, it does not include the work's -System Libraries, or general-purpose tools or generally available free -programs which are used unmodified in performing those activities but -which are not part of the work. For example, Corresponding Source -includes interface definition files associated with source files for -the work, and the source code for shared libraries and dynamically -linked subprograms that the work is specifically designed to require, -such as by intimate data communication or control flow between those -subprograms and other parts of the work. - - The Corresponding Source need not include anything that users -can regenerate automatically from other parts of the Corresponding -Source. - - The Corresponding Source for a work in source code form is that -same work. - - 2. Basic Permissions. - - All rights granted under this License are granted for the term of -copyright on the Program, and are irrevocable provided the stated -conditions are met. This License explicitly affirms your unlimited -permission to run the unmodified Program. The output from running a -covered work is covered by this License only if the output, given its -content, constitutes a covered work. This License acknowledges your -rights of fair use or other equivalent, as provided by copyright law. - - You may make, run and propagate covered works that you do not -convey, without conditions so long as your license otherwise remains -in force. You may convey covered works to others for the sole purpose -of having them make modifications exclusively for you, or provide you -with facilities for running those works, provided that you comply with -the terms of this License in conveying all material for which you do -not control copyright. Those thus making or running the covered works -for you must do so exclusively on your behalf, under your direction -and control, on terms that prohibit them from making any copies of -your copyrighted material outside their relationship with you. - - Conveying under any other circumstances is permitted solely under -the conditions stated below. Sublicensing is not allowed; section 10 -makes it unnecessary. - - 3. Protecting Users' Legal Rights From Anti-Circumvention Law. - - No covered work shall be deemed part of an effective technological -measure under any applicable law fulfilling obligations under article -11 of the WIPO copyright treaty adopted on 20 December 1996, or -similar laws prohibiting or restricting circumvention of such -measures. - - When you convey a covered work, you waive any legal power to forbid -circumvention of technological measures to the extent such circumvention -is effected by exercising rights under this License with respect to -the covered work, and you disclaim any intention to limit operation or -modification of the work as a means of enforcing, against the work's -users, your or third parties' legal rights to forbid circumvention of -technological measures. - - 4. Conveying Verbatim Copies. - - You may convey verbatim copies of the Program's source code as you -receive it, in any medium, provided that you conspicuously and -appropriately publish on each copy an appropriate copyright notice; -keep intact all notices stating that this License and any -non-permissive terms added in accord with section 7 apply to the code; -keep intact all notices of the absence of any warranty; and give all -recipients a copy of this License along with the Program. - - You may charge any price or no price for each copy that you convey, -and you may offer support or warranty protection for a fee. - - 5. Conveying Modified Source Versions. - - You may convey a work based on the Program, or the modifications to -produce it from the Program, in the form of source code under the -terms of section 4, provided that you also meet all of these conditions: - - a) The work must carry prominent notices stating that you modified - it, and giving a relevant date. - - b) The work must carry prominent notices stating that it is - released under this License and any conditions added under section - 7. This requirement modifies the requirement in section 4 to - "keep intact all notices". - - c) You must license the entire work, as a whole, under this - License to anyone who comes into possession of a copy. This - License will therefore apply, along with any applicable section 7 - additional terms, to the whole of the work, and all its parts, - regardless of how they are packaged. This License gives no - permission to license the work in any other way, but it does not - invalidate such permission if you have separately received it. - - d) If the work has interactive user interfaces, each must display - Appropriate Legal Notices; however, if the Program has interactive - interfaces that do not display Appropriate Legal Notices, your - work need not make them do so. - - A compilation of a covered work with other separate and independent -works, which are not by their nature extensions of the covered work, -and which are not combined with it such as to form a larger program, -in or on a volume of a storage or distribution medium, is called an -"aggregate" if the compilation and its resulting copyright are not -used to limit the access or legal rights of the compilation's users -beyond what the individual works permit. Inclusion of a covered work -in an aggregate does not cause this License to apply to the other -parts of the aggregate. - - 6. Conveying Non-Source Forms. - - You may convey a covered work in object code form under the terms -of sections 4 and 5, provided that you also convey the -machine-readable Corresponding Source under the terms of this License, -in one of these ways: - - a) Convey the object code in, or embodied in, a physical product - (including a physical distribution medium), accompanied by the - Corresponding Source fixed on a durable physical medium - customarily used for software interchange. - - b) Convey the object code in, or embodied in, a physical product - (including a physical distribution medium), accompanied by a - written offer, valid for at least three years and valid for as - long as you offer spare parts or customer support for that product - model, to give anyone who possesses the object code either (1) a - copy of the Corresponding Source for all the software in the - product that is covered by this License, on a durable physical - medium customarily used for software interchange, for a price no - more than your reasonable cost of physically performing this - conveying of source, or (2) access to copy the - Corresponding Source from a network server at no charge. - - c) Convey individual copies of the object code with a copy of the - written offer to provide the Corresponding Source. This - alternative is allowed only occasionally and noncommercially, and - only if you received the object code with such an offer, in accord - with subsection 6b. - - d) Convey the object code by offering access from a designated - place (gratis or for a charge), and offer equivalent access to the - Corresponding Source in the same way through the same place at no - further charge. You need not require recipients to copy the - Corresponding Source along with the object code. If the place to - copy the object code is a network server, the Corresponding Source - may be on a different server (operated by you or a third party) - that supports equivalent copying facilities, provided you maintain - clear directions next to the object code saying where to find the - Corresponding Source. Regardless of what server hosts the - Corresponding Source, you remain obligated to ensure that it is - available for as long as needed to satisfy these requirements. - - e) Convey the object code using peer-to-peer transmission, provided - you inform other peers where the object code and Corresponding - Source of the work are being offered to the general public at no - charge under subsection 6d. - - A separable portion of the object code, whose source code is excluded -from the Corresponding Source as a System Library, need not be -included in conveying the object code work. - - A "User Product" is either (1) a "consumer product", which means any -tangible personal property which is normally used for personal, family, -or household purposes, or (2) anything designed or sold for incorporation -into a dwelling. In determining whether a product is a consumer product, -doubtful cases shall be resolved in favor of coverage. For a particular -product received by a particular user, "normally used" refers to a -typical or common use of that class of product, regardless of the status -of the particular user or of the way in which the particular user -actually uses, or expects or is expected to use, the product. A product -is a consumer product regardless of whether the product has substantial -commercial, industrial or non-consumer uses, unless such uses represent -the only significant mode of use of the product. - - "Installation Information" for a User Product means any methods, -procedures, authorization keys, or other information required to install -and execute modified versions of a covered work in that User Product from -a modified version of its Corresponding Source. The information must -suffice to ensure that the continued functioning of the modified object -code is in no case prevented or interfered with solely because -modification has been made. - - If you convey an object code work under this section in, or with, or -specifically for use in, a User Product, and the conveying occurs as -part of a transaction in which the right of possession and use of the -User Product is transferred to the recipient in perpetuity or for a -fixed term (regardless of how the transaction is characterized), the -Corresponding Source conveyed under this section must be accompanied -by the Installation Information. But this requirement does not apply -if neither you nor any third party retains the ability to install -modified object code on the User Product (for example, the work has -been installed in ROM). - - The requirement to provide Installation Information does not include a -requirement to continue to provide support service, warranty, or updates -for a work that has been modified or installed by the recipient, or for -the User Product in which it has been modified or installed. Access to a -network may be denied when the modification itself materially and -adversely affects the operation of the network or violates the rules and -protocols for communication across the network. - - Corresponding Source conveyed, and Installation Information provided, -in accord with this section must be in a format that is publicly -documented (and with an implementation available to the public in -source code form), and must require no special password or key for -unpacking, reading or copying. - - 7. Additional Terms. - - "Additional permissions" are terms that supplement the terms of this -License by making exceptions from one or more of its conditions. -Additional permissions that are applicable to the entire Program shall -be treated as though they were included in this License, to the extent -that they are valid under applicable law. If additional permissions -apply only to part of the Program, that part may be used separately -under those permissions, but the entire Program remains governed by -this License without regard to the additional permissions. - - When you convey a copy of a covered work, you may at your option -remove any additional permissions from that copy, or from any part of -it. (Additional permissions may be written to require their own -removal in certain cases when you modify the work.) You may place -additional permissions on material, added by you to a covered work, -for which you have or can give appropriate copyright permission. - - Notwithstanding any other provision of this License, for material you -add to a covered work, you may (if authorized by the copyright holders of -that material) supplement the terms of this License with terms: - - a) Disclaiming warranty or limiting liability differently from the - terms of sections 15 and 16 of this License; or - - b) Requiring preservation of specified reasonable legal notices or - author attributions in that material or in the Appropriate Legal - Notices displayed by works containing it; or - - c) Prohibiting misrepresentation of the origin of that material, or - requiring that modified versions of such material be marked in - reasonable ways as different from the original version; or - - d) Limiting the use for publicity purposes of names of licensors or - authors of the material; or - - e) Declining to grant rights under trademark law for use of some - trade names, trademarks, or service marks; or - - f) Requiring indemnification of licensors and authors of that - material by anyone who conveys the material (or modified versions of - it) with contractual assumptions of liability to the recipient, for - any liability that these contractual assumptions directly impose on - those licensors and authors. - - All other non-permissive additional terms are considered "further -restrictions" within the meaning of section 10. If the Program as you -received it, or any part of it, contains a notice stating that it is -governed by this License along with a term that is a further -restriction, you may remove that term. If a license document contains -a further restriction but permits relicensing or conveying under this -License, you may add to a covered work material governed by the terms -of that license document, provided that the further restriction does -not survive such relicensing or conveying. - - If you add terms to a covered work in accord with this section, you -must place, in the relevant source files, a statement of the -additional terms that apply to those files, or a notice indicating -where to find the applicable terms. - - Additional terms, permissive or non-permissive, may be stated in the -form of a separately written license, or stated as exceptions; -the above requirements apply either way. - - 8. Termination. - - You may not propagate or modify a covered work except as expressly -provided under this License. Any attempt otherwise to propagate or -modify it is void, and will automatically terminate your rights under -this License (including any patent licenses granted under the third -paragraph of section 11). - - However, if you cease all violation of this License, then your -license from a particular copyright holder is reinstated (a) -provisionally, unless and until the copyright holder explicitly and -finally terminates your license, and (b) permanently, if the copyright -holder fails to notify you of the violation by some reasonable means -prior to 60 days after the cessation. - - Moreover, your license from a particular copyright holder is -reinstated permanently if the copyright holder notifies you of the -violation by some reasonable means, this is the first time you have -received notice of violation of this License (for any work) from that -copyright holder, and you cure the violation prior to 30 days after -your receipt of the notice. - - Termination of your rights under this section does not terminate the -licenses of parties who have received copies or rights from you under -this License. If your rights have been terminated and not permanently -reinstated, you do not qualify to receive new licenses for the same -material under section 10. - - 9. Acceptance Not Required for Having Copies. - - You are not required to accept this License in order to receive or -run a copy of the Program. Ancillary propagation of a covered work -occurring solely as a consequence of using peer-to-peer transmission -to receive a copy likewise does not require acceptance. However, -nothing other than this License grants you permission to propagate or -modify any covered work. These actions infringe copyright if you do -not accept this License. Therefore, by modifying or propagating a -covered work, you indicate your acceptance of this License to do so. - - 10. Automatic Licensing of Downstream Recipients. - - Each time you convey a covered work, the recipient automatically -receives a license from the original licensors, to run, modify and -propagate that work, subject to this License. You are not responsible -for enforcing compliance by third parties with this License. - - An "entity transaction" is a transaction transferring control of an -organization, or substantially all assets of one, or subdividing an -organization, or merging organizations. If propagation of a covered -work results from an entity transaction, each party to that -transaction who receives a copy of the work also receives whatever -licenses to the work the party's predecessor in interest had or could -give under the previous paragraph, plus a right to possession of the -Corresponding Source of the work from the predecessor in interest, if -the predecessor has it or can get it with reasonable efforts. - - You may not impose any further restrictions on the exercise of the -rights granted or affirmed under this License. For example, you may -not impose a license fee, royalty, or other charge for exercise of -rights granted under this License, and you may not initiate litigation -(including a cross-claim or counterclaim in a lawsuit) alleging that -any patent claim is infringed by making, using, selling, offering for -sale, or importing the Program or any portion of it. - - 11. Patents. - - A "contributor" is a copyright holder who authorizes use under this -License of the Program or a work on which the Program is based. The -work thus licensed is called the contributor's "contributor version". - - A contributor's "essential patent claims" are all patent claims -owned or controlled by the contributor, whether already acquired or -hereafter acquired, that would be infringed by some manner, permitted -by this License, of making, using, or selling its contributor version, -but do not include claims that would be infringed only as a -consequence of further modification of the contributor version. For -purposes of this definition, "control" includes the right to grant -patent sublicenses in a manner consistent with the requirements of + GNU GENERAL PUBLIC LICENSE + TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION + + 0. This License applies to any program or other work which contains +a notice placed by the copyright holder saying it may be distributed +under the terms of this General Public License. The "Program", below, +refers to any such program or work, and a "work based on the Program" +means either the Program or any derivative work under copyright law: +that is to say, a work containing the Program or a portion of it, +either verbatim or with modifications and/or translated into another +language. (Hereinafter, translation is included without limitation in +the term "modification".) Each licensee is addressed as "you". + +Activities other than copying, distribution and modification are not +covered by this License; they are outside its scope. The act of +running the Program is not restricted, and the output from the Program +is covered only if its contents constitute a work based on the +Program (independent of having been made by running the Program). +Whether that is true depends on what the Program does. + + 1. You may copy and distribute verbatim copies of the Program's +source code as you receive it, in any medium, provided that you +conspicuously and appropriately publish on each copy an appropriate +copyright notice and disclaimer of warranty; keep intact all the +notices that refer to this License and to the absence of any warranty; +and give any other recipients of the Program a copy of this License +along with the Program. + +You may charge a fee for the physical act of transferring a copy, and +you may at your option offer warranty protection in exchange for a fee. + + 2. You may modify your copy or copies of the Program or any portion +of it, thus forming a work based on the Program, and copy and +distribute such modifications or work under the terms of Section 1 +above, provided that you also meet all of these conditions: + + a) You must cause the modified files to carry prominent notices + stating that you changed the files and the date of any change. + + b) You must cause any work that you distribute or publish, that in + whole or in part contains or is derived from the Program or any + part thereof, to be licensed as a whole at no charge to all third + parties under the terms of this License. + + c) If the modified program normally reads commands interactively + when run, you must cause it, when started running for such + interactive use in the most ordinary way, to print or display an + announcement including an appropriate copyright notice and a + notice that there is no warranty (or else, saying that you provide + a warranty) and that users may redistribute the program under + these conditions, and telling the user how to view a copy of this + License. (Exception: if the Program itself is interactive but + does not normally print such an announcement, your work based on + the Program is not required to print an announcement.) + +These requirements apply to the modified work as a whole. If +identifiable sections of that work are not derived from the Program, +and can be reasonably considered independent and separate works in +themselves, then this License, and its terms, do not apply to those +sections when you distribute them as separate works. But when you +distribute the same sections as part of a whole which is a work based +on the Program, the distribution of the whole must be on the terms of +this License, whose permissions for other licensees extend to the +entire whole, and thus to each and every part regardless of who wrote it. + +Thus, it is not the intent of this section to claim rights or contest +your rights to work written entirely by you; rather, the intent is to +exercise the right to control the distribution of derivative or +collective works based on the Program. + +In addition, mere aggregation of another work not based on the Program +with the Program (or with a work based on the Program) on a volume of +a storage or distribution medium does not bring the other work under +the scope of this License. + + 3. You may copy and distribute the Program (or a work based on it, +under Section 2) in object code or executable form under the terms of +Sections 1 and 2 above provided that you also do one of the following: + + a) Accompany it with the complete corresponding machine-readable + source code, which must be distributed under the terms of Sections + 1 and 2 above on a medium customarily used for software interchange; or, + + b) Accompany it with a written offer, valid for at least three + years, to give any third party, for a charge no more than your + cost of physically performing source distribution, a complete + machine-readable copy of the corresponding source code, to be + distributed under the terms of Sections 1 and 2 above on a medium + customarily used for software interchange; or, + + c) Accompany it with the information you received as to the offer + to distribute corresponding source code. (This alternative is + allowed only for noncommercial distribution and only if you + received the program in object code or executable form with such + an offer, in accord with Subsection b above.) + +The source code for a work means the preferred form of the work for +making modifications to it. For an executable work, complete source +code means all the source code for all modules it contains, plus any +associated interface definition files, plus the scripts used to +control compilation and installation of the executable. However, as a +special exception, the source code distributed need not include +anything that is normally distributed (in either source or binary +form) with the major components (compiler, kernel, and so on) of the +operating system on which the executable runs, unless that component +itself accompanies the executable. + +If distribution of executable or object code is made by offering +access to copy from a designated place, then offering equivalent +access to copy the source code from the same place counts as +distribution of the source code, even though third parties are not +compelled to copy the source along with the object code. + + 4. You may not copy, modify, sublicense, or distribute the Program +except as expressly provided under this License. Any attempt +otherwise to copy, modify, sublicense or distribute the Program is +void, and will automatically terminate your rights under this License. +However, parties who have received copies, or rights, from you under +this License will not have their licenses terminated so long as such +parties remain in full compliance. + + 5. You are not required to accept this License, since you have not +signed it. However, nothing else grants you permission to modify or +distribute the Program or its derivative works. These actions are +prohibited by law if you do not accept this License. Therefore, by +modifying or distributing the Program (or any work based on the +Program), you indicate your acceptance of this License to do so, and +all its terms and conditions for copying, distributing or modifying +the Program or works based on it. + + 6. Each time you redistribute the Program (or any work based on the +Program), the recipient automatically receives a license from the +original licensor to copy, distribute or modify the Program subject to +these terms and conditions. You may not impose any further +restrictions on the recipients' exercise of the rights granted herein. +You are not responsible for enforcing compliance by third parties to this License. - Each contributor grants you a non-exclusive, worldwide, royalty-free -patent license under the contributor's essential patent claims, to -make, use, sell, offer for sale, import and otherwise run, modify and -propagate the contents of its contributor version. - - In the following three paragraphs, a "patent license" is any express -agreement or commitment, however denominated, not to enforce a patent -(such as an express permission to practice a patent or covenant not to -sue for patent infringement). To "grant" such a patent license to a -party means to make such an agreement or commitment not to enforce a -patent against the party. - - If you convey a covered work, knowingly relying on a patent license, -and the Corresponding Source of the work is not available for anyone -to copy, free of charge and under the terms of this License, through a -publicly available network server or other readily accessible means, -then you must either (1) cause the Corresponding Source to be so -available, or (2) arrange to deprive yourself of the benefit of the -patent license for this particular work, or (3) arrange, in a manner -consistent with the requirements of this License, to extend the patent -license to downstream recipients. "Knowingly relying" means you have -actual knowledge that, but for the patent license, your conveying the -covered work in a country, or your recipient's use of the covered work -in a country, would infringe one or more identifiable patents in that -country that you have reason to believe are valid. - - If, pursuant to or in connection with a single transaction or -arrangement, you convey, or propagate by procuring conveyance of, a -covered work, and grant a patent license to some of the parties -receiving the covered work authorizing them to use, propagate, modify -or convey a specific copy of the covered work, then the patent license -you grant is automatically extended to all recipients of the covered -work and works based on it. - - A patent license is "discriminatory" if it does not include within -the scope of its coverage, prohibits the exercise of, or is -conditioned on the non-exercise of one or more of the rights that are -specifically granted under this License. You may not convey a covered -work if you are a party to an arrangement with a third party that is -in the business of distributing software, under which you make payment -to the third party based on the extent of your activity of conveying -the work, and under which the third party grants, to any of the -parties who would receive the covered work from you, a discriminatory -patent license (a) in connection with copies of the covered work -conveyed by you (or copies made from those copies), or (b) primarily -for and in connection with specific products or compilations that -contain the covered work, unless you entered into that arrangement, -or that patent license was granted, prior to 28 March 2007. - - Nothing in this License shall be construed as excluding or limiting -any implied license or other defenses to infringement that may -otherwise be available to you under applicable patent law. - - 12. No Surrender of Others' Freedom. - - If conditions are imposed on you (whether by court order, agreement or + 7. If, as a consequence of a court judgment or allegation of patent +infringement or for any other reason (not limited to patent issues), +conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not -excuse you from the conditions of this License. If you cannot convey a -covered work so as to satisfy simultaneously your obligations under this -License and any other pertinent obligations, then as a consequence you may -not convey it at all. For example, if you agree to terms that obligate you -to collect a royalty for further conveying from those to whom you convey -the Program, the only way you could satisfy both those terms and this -License would be to refrain entirely from conveying the Program. - - 13. Use with the GNU Affero General Public License. - - Notwithstanding any other provision of this License, you have -permission to link or combine any covered work with a work licensed -under version 3 of the GNU Affero General Public License into a single -combined work, and to convey the resulting work. The terms of this -License will continue to apply to the part which is the covered work, -but the special requirements of the GNU Affero General Public License, -section 13, concerning interaction through a network will apply to the -combination as such. - - 14. Revised Versions of this License. - - The Free Software Foundation may publish revised and/or new versions of -the GNU General Public License from time to time. Such new versions will +excuse you from the conditions of this License. If you cannot +distribute so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you +may not distribute the Program at all. For example, if a patent +license would not permit royalty-free redistribution of the Program by +all those who receive copies directly or indirectly through you, then +the only way you could satisfy both it and this License would be to +refrain entirely from distribution of the Program. + +If any portion of this section is held invalid or unenforceable under +any particular circumstance, the balance of the section is intended to +apply and the section as a whole is intended to apply in other +circumstances. + +It is not the purpose of this section to induce you to infringe any +patents or other property right claims or to contest validity of any +such claims; this section has the sole purpose of protecting the +integrity of the free software distribution system, which is +implemented by public license practices. Many people have made +generous contributions to the wide range of software distributed +through that system in reliance on consistent application of that +system; it is up to the author/donor to decide if he or she is willing +to distribute software through any other system and a licensee cannot +impose that choice. + +This section is intended to make thoroughly clear what is believed to +be a consequence of the rest of this License. + + 8. If the distribution and/or use of the Program is restricted in +certain countries either by patents or by copyrighted interfaces, the +original copyright holder who places the Program under this License +may add an explicit geographical distribution limitation excluding +those countries, so that distribution is permitted only in or among +countries not thus excluded. In such case, this License incorporates +the limitation as if written in the body of this License. + + 9. The Free Software Foundation may publish revised and/or new versions +of the General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. - Each version is given a distinguishing version number. If the -Program specifies that a certain numbered version of the GNU General -Public License "or any later version" applies to it, you have the -option of following the terms and conditions either of that numbered -version or of any later version published by the Free Software -Foundation. If the Program does not specify a version number of the -GNU General Public License, you may choose any version ever published -by the Free Software Foundation. - - If the Program specifies that a proxy can decide which future -versions of the GNU General Public License can be used, that proxy's -public statement of acceptance of a version permanently authorizes you -to choose that version for the Program. - - Later license versions may give you additional or different -permissions. However, no additional obligations are imposed on any -author or copyright holder as a result of your choosing to follow a -later version. - - 15. Disclaimer of Warranty. - - THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY -APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT -HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY -OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, -THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR -PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM -IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF -ALL NECESSARY SERVICING, REPAIR OR CORRECTION. - - 16. Limitation of Liability. - - IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING -WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS -THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY -GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE -USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF -DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD -PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), -EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF -SUCH DAMAGES. - - 17. Interpretation of Sections 15 and 16. - - If the disclaimer of warranty and limitation of liability provided -above cannot be given local legal effect according to their terms, -reviewing courts shall apply local law that most closely approximates -an absolute waiver of all civil liability in connection with the -Program, unless a warranty or assumption of liability accompanies a -copy of the Program in return for a fee. - - END OF TERMS AND CONDITIONS - - How to Apply These Terms to Your New Programs +Each version is given a distinguishing version number. If the Program +specifies a version number of this License which applies to it and "any +later version", you have the option of following the terms and conditions +either of that version or of any later version published by the Free +Software Foundation. If the Program does not specify a version number of +this License, you may choose any version ever published by the Free Software +Foundation. + + 10. If you wish to incorporate parts of the Program into other free +programs whose distribution conditions are different, write to the author +to ask for permission. For software which is copyrighted by the Free +Software Foundation, write to the Free Software Foundation; we sometimes +make exceptions for this. Our decision will be guided by the two goals +of preserving the free status of all derivatives of our free software and +of promoting the sharing and reuse of software generally. + + NO WARRANTY + + 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY +FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN +OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES +PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED +OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF +MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS +TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE +PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, +REPAIR OR CORRECTION. + + 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR +REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, +INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING +OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED +TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY +YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER +PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE +POSSIBILITY OF SUCH DAMAGES. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it @@ -628,7 +287,7 @@ free software which everyone can redistribute and change under these terms. To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively -state the exclusion of warranty; and each file should have at least +convey the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. @@ -636,7 +295,7 @@ the "copyright" line and a pointer to where the full notice is found. This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 3 of the License, or + the Free Software Foundation, either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, @@ -649,26 +308,31 @@ the "copyright" line and a pointer to where the full notice is found. Also add information on how to contact you by electronic and paper mail. - If the program does terminal interaction, make it output a short -notice like this when it starts in an interactive mode: +If the program is interactive, make it output a short notice like this +when it starts in an interactive mode: - Copyright (C) - This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + Gnomovision version 69, Copyright (C) + Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details. The hypothetical commands `show w' and `show c' should show the appropriate -parts of the General Public License. Of course, your program's commands -might be different; for a GUI interface, you would use an "about box". - - You should also get your employer (if you work as a programmer) or school, -if any, to sign a "copyright disclaimer" for the program, if necessary. -For more information on this, and how to apply and follow the GNU GPL, see -. - - The GNU General Public License does not permit incorporating your program -into proprietary programs. If your program is a subroutine library, you -may consider it more useful to permit linking proprietary applications with -the library. If this is what you want to do, use the GNU Lesser General -Public License instead of this License. But first, please read -. +parts of the General Public License. Of course, the commands you use may +be called something other than `show w' and `show c'; they could even be +mouse-clicks or menu items--whatever suits your program. + +You should also get your employer (if you work as a programmer) or your +school, if any, to sign a "copyright disclaimer" for the program, if +necessary. Here is a sample; alter the names: + + Yoyodyne, Inc., hereby disclaims all copyright interest in the program + `Gnomovision' (which makes passes at compilers) written by James Hacker. + + , 1 April 1989 + Ty Coon, President of Vice + +This General Public License does not permit incorporating your program into +proprietary programs. If your program is a subroutine library, you may +consider it more useful to permit linking proprietary applications with the +library. If this is what you want to do, use the GNU Lesser General +Public License instead of this License. diff --git a/ChangeLog b/ChangeLog index e946bd2..96314b6 100644 --- a/ChangeLog +++ b/ChangeLog @@ -1,3 +1,29 @@ +2022-02-04 Antonio Diaz Diaz + + * Version 1.18 released. + * main_loop.c (get_shell_command): Flush stdout after printing cmd. + (Reported by Sören Tempel). + * signal.c (sighup_handler): Fix a memory leak just before exiting. + * carg_parser.c (ap_init): Likewise. + (Both reported by Xosé Vázquez Pérez). + * io.c (read_file, write_file): Check ptr returned by strip_escapes. + * main_loop.c (get_shell_command, exec_command): Likewise. + * main_loop.c (get_shell_command): Remove backslash from escaped '%'. + (Reported by Martin Thomsen). + * main_loop.c, regex.c: Implement case-insensitive REs. + * regex.c (compile_regex): Don't overwrite previous regex if error. + * main.c: New option '--strip-trailing-cr'. + * buffer.c (push_undo_atom): Fail if stack grows larger than INT_MAX. + (too_many_lines): Fail if buffer grows larger than INT_MAX lines. + * global.c (set_active_node): Fail if list grows larger than INT_MAX. + * signal.c (resize_buffer): Fail if a line grows longer than INT_MAX. + * io.c (read_file): Return -2 for fatal errors. + * main_loop.c (main_loop): Set error status if fatal error from main. + * main.c [restricted_]: New message "Directory access restricted". + * ed.texi: New chapter "The 's' Command". + * COPYING: Restored. (I forgot to do it in 1.11). + * TODO: Removed. + 2021-01-06 Antonio Diaz Diaz * Version 1.17 released. @@ -32,7 +58,7 @@ * regex.c (extract_replacement): Allow newlines even if global. * main_loop.c (exec_command): Make command 'c' reject address 0. * ed.texi: Minor fixes. - * configure: Accept appending to CFLAGS, 'CFLAGS+=OPTIONS'. + * configure: Accept appending to CFLAGS; 'CFLAGS+=OPTIONS'. 2017-02-22 Antonio Diaz Diaz @@ -90,9 +116,9 @@ (zN printed N + 1 lines). * ed.texi: Document the window size used by the command 'z'. * Makefile.in: New targets 'install*-compress'. - * Restore original copyright notices in the code. I assigned to - the FSF the copyright on changes made to the part of ed already - copyrighted by the FSF, which seems to be just the manual. + * Restore original copyright and license notices in the code. I + assigned to the FSF the copyright on changes made to the part of ed + already copyrighted by the FSF, which seems to be just the manual. 2014-01-22 Antonio Diaz Diaz @@ -162,6 +188,7 @@ * Convert C99 style comments '//' to C89 style comments '/* */'. * ed.texinfo: Fix an erratum. * Change copyright holder from Andrew, Antonio to the FSF. + (This change was later discovered to be wrong. See 1.6 and 1.11). 2009-07-10 Antonio Diaz Diaz @@ -198,8 +225,8 @@ * Version 1.0 released. * configure: New option '--program-prefix'. - * signal.c (strip_escapes): Buffer overflow fixed. - * signal.c (resize_buffer): Pointer aliasing warning fixed. + * signal.c (strip_escapes): Fix a buffer overflow. + * signal.c (resize_buffer): Fix a pointer aliasing warning. 2008-02-24 Antonio Diaz Diaz @@ -305,7 +332,7 @@ Dec 1993 Fran Copyright (C) 1993 François Pinard Copyright (C) 1994 Andrew Moore -Copyright (C) 2006-2021 Antonio Diaz Diaz. +Copyright (C) 2006-2022 Antonio Diaz Diaz. This file is a collection of facts, and thus it is not copyrightable, but just in case, you have unlimited permission to copy, distribute, and diff --git a/INSTALL b/INSTALL index f1df974..e696e85 100644 --- a/INSTALL +++ b/INSTALL @@ -2,7 +2,7 @@ Requirements ------------ You will need a C89 compiler and a C library compatible with POSIX. (gcc 3.3.6 or newer is recommended). -I use gcc 6.1.0 and 4.1.2, but the code should compile with any standards +I use gcc 6.1.0 and 3.3.6, but the code should compile with any standards compliant compiler. Gcc is available at http://gcc.gnu.org. @@ -59,7 +59,7 @@ After running 'configure', you can run 'make' and 'make install' as explained above. -Copyright (C) 2006-2021 Antonio Diaz Diaz. +Copyright (C) 2006-2022 Antonio Diaz Diaz. This file is free documentation: you have unlimited permission to copy, distribute, and modify it. diff --git a/Makefile.in b/Makefile.in index 620cd35..f716df4 100644 --- a/Makefile.in +++ b/Makefile.in @@ -20,7 +20,7 @@ objs = buffer.o carg_parser.o global.o io.o main.o main_loop.o regex.o signal.o all : $(progname) r$(progname) $(progname) : $(objs) - $(CC) $(LDFLAGS) $(CFLAGS) -o $@ $(objs) + $(CC) $(CFLAGS) $(LDFLAGS) -o $@ $(objs) r$(progname) : r$(progname).in cat $(VPATH)/r$(progname).in > $@ @@ -118,7 +118,6 @@ dist : doc $(DISTNAME)/Makefile.in \ $(DISTNAME)/NEWS \ $(DISTNAME)/README \ - $(DISTNAME)/TODO \ $(DISTNAME)/configure \ $(DISTNAME)/doc/$(progname).1 \ $(DISTNAME)/doc/$(pkgname).info \ diff --git a/NEWS b/NEWS index 7152d1a..b1ba354 100644 --- a/NEWS +++ b/NEWS @@ -1,10 +1,36 @@ -Changes in version 1.17: +Changes in version 1.18: -The commands 'q' and 'Q' now work in a global command. -(Reported by J. A. Harris). +The shell escape command (!) now flushes stdout so that the modified command +is always printed before being executed even if standard output is fully +buffered (for example, a file). (Reported by Sören Tempel). -The new option '-E, --extended-regexp' has been added. It tells ed to use -extended regular expressions instead of the basic regular expressions -mandated by POSIX. (Suggested by Shawn Wagner). +A couple of harmless memory leaks have been fixed. (They both happened just +before ed exits). (Reported by Xosé Vázquez Pérez). -Print the file name in case of read or write error. (Reported by Dan Jacobson). +The pointer returned by the function 'strip_escapes' is now checked. (It may +be null if memory is exhausted). + +The shell escape command (!) now removes the backslash from each escaped '%' +character within the text of the shell command line. +(Reported by Martin Thomsen). + +Case-insensitive regular expressions have been implemented as in GNU sed. + +Syntax errors in regular expressions, for example unmatched ( or \(, no +longer overwrite a previously compiled regular expression, preventing a +"No previous pattern" error. + +The option '--strip-trailing-cr', which removes carriage returns at end of +text lines, has been added. + +Loading a file now fails if a line is longer than INT_MAX bytes or if the +file contains more than INT_MAX lines (usually 2 Gi lines). (Instead of +overflowing line addresses). + +In interactive mode ed now sets final exit status to 1 if a fatal error +happens while reading the file passed in the command line. + +red now reports "Directory access restricted" instead of "Invalid filename" +when trying to edit a file outside of the current directory. + +The new chapter "The 's' Command" has been added to the manual. diff --git a/README b/README index 72edcf1..a858b83 100644 --- a/README +++ b/README @@ -124,7 +124,7 @@ or: Copyright (C) 1993, 1994 Andrew Moore -Copyright (C) 2006-2021 Antonio Diaz Diaz. +Copyright (C) 2006-2022 Antonio Diaz Diaz. This file is free documentation: you have unlimited permission to copy, distribute, and modify it. diff --git a/TODO b/TODO deleted file mode 100644 index bfc94fa..0000000 --- a/TODO +++ /dev/null @@ -1,8 +0,0 @@ -Some missing tests: -1) g/./s^@^@ - okay: NULs in commands -2) g/./s/^@/ - okay: NULs in patterns -3) ed -x - verify: 8-bit clean -4) ed - verify: long-line support -5) ed - verify: interactive/help mode -6) G/pat/ - verify: global interactive command -7) V/pat/ - verify: global interactive command diff --git a/buffer.c b/buffer.c index 9969019..a5031e6 100644 --- a/buffer.c +++ b/buffer.c @@ -1,7 +1,7 @@ /* buffer.c: scratch-file buffer routines for the ed line editor. */ /* GNU ed - The GNU line editor. Copyright (C) 1993, 1994 Andrew Moore, Talke Studio - Copyright (C) 2006-2021 Antonio Diaz Diaz. + Copyright (C) 2006-2022 Antonio Diaz Diaz. This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by @@ -76,6 +76,13 @@ static void insert_node( line_t * const lp, line_t * const prev ) } +/* to be called before add_line_node */ +static bool too_many_lines( void ) + { + if( last_addr_ < INT_MAX - 1 ) return false; + set_error_msg( "Too many lines in buffer" ); return true; + } + /* add a line node in the editor buffer after the given line */ static void add_line_node( line_t * const lp ) { @@ -103,7 +110,8 @@ static line_t * dup_line_node( line_t * const lp ) /* Insert text from stdin (or from command buffer if global) to after line n; stop when either a single period is read or at EOF. - Returns false if insertion fails. */ + Return false if insertion fails. +*/ bool append_lines( const char ** const ibufpp, const int addr, bool insert, const bool isglobal ) { @@ -196,6 +204,7 @@ bool copy_lines( const int first_addr, const int second_addr, const int addr ) for( ; n > 0; n = m, m = 0, np = search_line_node( current_addr_ + 1 ) ) for( ; n-- > 0; np = np->q_forw ) { + if( too_many_lines() ) return false; disable_interrupts(); lp = dup_line_node( np ); if( !lp ) { enable_interrupts(); return false; } @@ -412,6 +421,7 @@ bool put_lines( const int addr ) current_addr_ = addr; while( lp != &yank_buffer_head ) { + if( too_many_lines() ) return false; disable_interrupts(); p = dup_line_node( lp ); if( !p ) { enable_interrupts(); return false; } @@ -430,18 +440,21 @@ bool put_lines( const int addr ) } -/* write a line of text to the scratch file and add a line node to the - editor buffer; return a pointer to the end of the text, or 0 if error */ +/* Write a line of text to the scratch file and add a line node to the + editor buffer. + The text line stops at the first newline and may be shorter than size. + Return a pointer to the char following the newline in buf, or 0 if error. +*/ const char * put_sbuf_line( const char * const buf, const int size ) { const char * const p = (const char *) memchr( buf, '\n', size ); - line_t * lp; - int len; + if( !p ) + { set_error_msg( "internal error: unterminated line passed to put_sbuf_line" ); + return 0; } + const int len = p - buf; + if( too_many_lines() ) return 0; - if( !p ) { set_error_msg( "Line too long" ); return 0; } - len = p - buf; - /* out of position */ - if( seek_write ) + if( seek_write ) /* out of position */ { if( fseek( sfp, 0L, SEEK_END ) != 0 ) { @@ -459,7 +472,7 @@ const char * put_sbuf_line( const char * const buf, const int size ) set_error_msg( "Cannot write temp file" ); return 0; } - lp = dup_line_node( 0 ); + line_t * lp = dup_line_node( 0 ); if( !lp ) return 0; lp->pos = sfpos; lp->len = len; add_line_node( lp ); @@ -519,7 +532,7 @@ bool yank_lines( const int from, const int to ) static undo_t * ustack = 0; /* undo stack */ static int usize = 0; /* ustack size (in bytes) */ -static int u_ptr = 0; /* undo stack pointer */ +static int u_idx = 0; /* undo stack index */ static int u_current_addr = -1; /* if < 0, undo disabled */ static int u_last_addr = -1; /* if < 0, undo disabled */ static bool u_modified = false; @@ -527,11 +540,11 @@ static bool u_modified = false; void clear_undo_stack( void ) { - while( u_ptr-- ) - if( ustack[u_ptr].type == UDEL ) + while( u_idx-- ) + if( ustack[u_idx].type == UDEL ) { - line_t * const ep = ustack[u_ptr].tail->q_forw; - line_t * bp = ustack[u_ptr].head; + line_t * const ep = ustack[u_idx].tail->q_forw; + line_t * bp = ustack[u_idx].head; while( bp != ep ) { line_t * const lp = bp->q_forw; @@ -541,7 +554,7 @@ void clear_undo_stack( void ) bp = lp; } } - u_ptr = 0; + u_idx = 0; u_current_addr = current_addr_; u_last_addr = last_addr_; u_modified = modified_; @@ -556,40 +569,46 @@ void reset_undo_state( void ) } +static void free_undo_stack( void ) + { + if( ustack ) + { + clear_undo_stack(); + free( ustack ); + ustack = 0; + usize = u_idx = 0; + u_current_addr = u_last_addr = -1; + } + } + + /* return pointer to intialized undo node */ undo_t * push_undo_atom( const int type, const int from, const int to ) { - const int min_size = ( u_ptr + 1 ) * sizeof (undo_t); + const unsigned min_size = ( u_idx + 1 ) * sizeof (undo_t); + disable_interrupts(); - if( usize < min_size ) + if( (unsigned)usize < min_size ) { - const int new_size = ( min_size < 512 ? 512 : ( min_size / 512 ) * 1024 ); + if( min_size >= INT_MAX ) + { set_error_msg( "Undo stack too long" ); + free_undo_stack(); enable_interrupts(); return 0; } + const int new_size = ( ( min_size < 512 ) ? 512 : + ( min_size > INT_MAX / 2 ) ? INT_MAX : ( min_size / 512 ) * 1024 ); void * new_buf = 0; if( ustack ) new_buf = realloc( ustack, new_size ); else new_buf = malloc( new_size ); if( !new_buf ) - { - show_strerror( 0, errno ); - set_error_msg( mem_msg ); - if( ustack ) - { - clear_undo_stack(); - free( ustack ); - ustack = 0; - usize = u_ptr = 0; - u_current_addr = u_last_addr = -1; - } - enable_interrupts(); - return 0; - } + { show_strerror( 0, errno ); set_error_msg( mem_msg ); + free_undo_stack(); enable_interrupts(); return 0; } usize = new_size; ustack = (undo_t *)new_buf; } - ustack[u_ptr].type = type; - ustack[u_ptr].tail = search_line_node( to ); - ustack[u_ptr].head = search_line_node( from ); + ustack[u_idx].type = type; + ustack[u_idx].tail = search_line_node( to ); + ustack[u_idx].head = search_line_node( from ); enable_interrupts(); - return ustack + u_ptr++; + return ustack + u_idx++; } @@ -601,11 +620,11 @@ bool undo( const bool isglobal ) const int o_last_addr = last_addr_; const bool o_modified = modified_; - if( u_ptr <= 0 || u_current_addr < 0 || u_last_addr < 0 ) + if( u_idx <= 0 || u_current_addr < 0 || u_last_addr < 0 ) { set_error_msg( "Nothing to undo" ); return false; } search_line_node( 0 ); /* reset cached value */ disable_interrupts(); - for( n = u_ptr - 1; n >= 0; --n ) + for( n = u_idx - 1; n >= 0; --n ) { switch( ustack[n].type ) { @@ -623,10 +642,10 @@ bool undo( const bool isglobal ) ustack[n].type ^= 1; } /* reverse undo stack order */ - for( n = 0; 2 * n < u_ptr - 1; ++n ) + for( n = 0; 2 * n < u_idx - 1; ++n ) { undo_t tmp = ustack[n]; - ustack[n] = ustack[u_ptr-1-n]; ustack[u_ptr-1-n] = tmp; + ustack[n] = ustack[u_idx-1-n]; ustack[u_idx-1-n] = tmp; } if( isglobal ) clear_active_list(); current_addr_ = u_current_addr; u_current_addr = o_current_addr; diff --git a/carg_parser.c b/carg_parser.c index d0c05d5..181ba23 100644 --- a/carg_parser.c +++ b/carg_parser.c @@ -1,5 +1,5 @@ /* Arg_parser - POSIX/GNU command line argument parser. (C version) - Copyright (C) 2006-2021 Antonio Diaz Diaz. + Copyright (C) 2006-2022 Antonio Diaz Diaz. This library is free software. Redistribution and use in source and binary forms, with or without modification, are permitted provided @@ -32,10 +32,10 @@ static void * ap_resize_buffer( void * buf, const int min_size ) } -static char push_back_record( struct Arg_parser * const ap, - const int code, const char * const argument ) +static char push_back_record( struct Arg_parser * const ap, const int code, + const char * const long_name, + const char * const argument ) { - const int len = strlen( argument ); struct ap_Record * p; void * tmp = ap_resize_buffer( ap->data, ( ap->data_size + 1 ) * sizeof (struct ap_Record) ); @@ -43,11 +43,29 @@ static char push_back_record( struct Arg_parser * const ap, ap->data = (struct ap_Record *)tmp; p = &(ap->data[ap->data_size]); p->code = code; - p->argument = 0; - tmp = ap_resize_buffer( p->argument, len + 1 ); - if( !tmp ) return 0; - p->argument = (char *)tmp; - strncpy( p->argument, argument, len + 1 ); + if( long_name ) + { + const int len = strlen( long_name ); + p->parsed_name = (char *)malloc( len + 2 + 1 ); + if( !p->parsed_name ) return 0; + p->parsed_name[0] = p->parsed_name[1] = '-'; + strncpy( p->parsed_name + 2, long_name, len + 1 ); + } + else if( code > 0 && code < 256 ) + { + p->parsed_name = (char *)malloc( 2 + 1 ); + if( !p->parsed_name ) return 0; + p->parsed_name[0] = '-'; p->parsed_name[1] = code; p->parsed_name[2] = 0; + } + else p->parsed_name = 0; + if( argument ) + { + const int len = strlen( argument ); + p->argument = (char *)malloc( len + 1 ); + if( !p->argument ) { free( p->parsed_name ); return 0; } + strncpy( p->argument, argument, len + 1 ); + } + else p->argument = 0; ++ap->data_size; return 1; } @@ -68,12 +86,14 @@ static char add_error( struct Arg_parser * const ap, const char * const msg ) static void free_data( struct Arg_parser * const ap ) { int i; - for( i = 0; i < ap->data_size; ++i ) free( ap->data[i].argument ); + for( i = 0; i < ap->data_size; ++i ) + { free( ap->data[i].argument ); free( ap->data[i].parsed_name ); } if( ap->data ) { free( ap->data ); ap->data = 0; } ap->data_size = 0; } +/* Return 0 only if out of memory. */ static char parse_long_option( struct Arg_parser * const ap, const char * const opt, const char * const arg, const struct ap_Option options[], @@ -87,9 +107,10 @@ static char parse_long_option( struct Arg_parser * const ap, /* Test all long options for either exact match or abbreviated matches. */ for( i = 0; options[i].code != 0; ++i ) - if( options[i].name && strncmp( options[i].name, &opt[2], len ) == 0 ) + if( options[i].long_name && + strncmp( options[i].long_name, &opt[2], len ) == 0 ) { - if( strlen( options[i].name ) == len ) /* Exact match found */ + if( strlen( options[i].long_name ) == len ) /* Exact match found */ { index = i; exact = 1; break; } else if( index < 0 ) index = i; /* First nonexact match found */ else if( options[index].code != options[i].code || @@ -117,35 +138,39 @@ static char parse_long_option( struct Arg_parser * const ap, { if( options[index].has_arg == ap_no ) { - add_error( ap, "option '--" ); add_error( ap, options[index].name ); + add_error( ap, "option '--" ); add_error( ap, options[index].long_name ); add_error( ap, "' doesn't allow an argument" ); return 1; } if( options[index].has_arg == ap_yes && !opt[len+3] ) { - add_error( ap, "option '--" ); add_error( ap, options[index].name ); + add_error( ap, "option '--" ); add_error( ap, options[index].long_name ); add_error( ap, "' requires an argument" ); return 1; } - return push_back_record( ap, options[index].code, &opt[len+3] ); + return push_back_record( ap, options[index].code, + options[index].long_name, &opt[len+3] ); } if( options[index].has_arg == ap_yes ) { if( !arg || !arg[0] ) { - add_error( ap, "option '--" ); add_error( ap, options[index].name ); + add_error( ap, "option '--" ); add_error( ap, options[index].long_name ); add_error( ap, "' requires an argument" ); return 1; } ++*argindp; - return push_back_record( ap, options[index].code, arg ); + return push_back_record( ap, options[index].code, + options[index].long_name, arg ); } - return push_back_record( ap, options[index].code, "" ); + return push_back_record( ap, options[index].code, + options[index].long_name, 0 ); } +/* Return 0 only if out of memory. */ static char parse_short_option( struct Arg_parser * const ap, const char * const opt, const char * const arg, const struct ap_Option options[], @@ -156,13 +181,13 @@ static char parse_short_option( struct Arg_parser * const ap, while( cind > 0 ) { int index = -1, i; - const unsigned char code = opt[cind]; + const unsigned char c = opt[cind]; char code_str[2]; - code_str[0] = code; code_str[1] = 0; + code_str[0] = c; code_str[1] = 0; - if( code != 0 ) + if( c != 0 ) for( i = 0; options[i].code; ++i ) - if( code == options[i].code ) + if( c == options[i].code ) { index = i; break; } if( index < 0 ) @@ -176,7 +201,7 @@ static char parse_short_option( struct Arg_parser * const ap, if( options[index].has_arg != ap_no && cind > 0 && opt[cind] ) { - if( !push_back_record( ap, code, &opt[cind] ) ) return 0; + if( !push_back_record( ap, c, 0, &opt[cind] ) ) return 0; ++*argindp; cind = 0; } else if( options[index].has_arg == ap_yes ) @@ -188,9 +213,9 @@ static char parse_short_option( struct Arg_parser * const ap, return 1; } ++*argindp; cind = 0; - if( !push_back_record( ap, code, arg ) ) return 0; + if( !push_back_record( ap, c, 0, arg ) ) return 0; } - else if( !push_back_record( ap, code, "" ) ) return 0; + else if( !push_back_record( ap, c, 0, 0 ) ) return 0; } return 1; } @@ -203,7 +228,7 @@ char ap_init( struct Arg_parser * const ap, const char ** non_options = 0; /* skipped non-options */ int non_options_size = 0; /* number of skipped non-options */ int argind = 1; /* index in argv */ - int i; + char done = 0; /* false until success */ ap->data = 0; ap->error = 0; @@ -223,20 +248,20 @@ char ap_init( struct Arg_parser * const ap, if( ch2 == '-' ) { if( !argv[argind][2] ) { ++argind; break; } /* we found "--" */ - else if( !parse_long_option( ap, opt, arg, options, &argind ) ) return 0; + else if( !parse_long_option( ap, opt, arg, options, &argind ) ) goto out; } - else if( !parse_short_option( ap, opt, arg, options, &argind ) ) return 0; + else if( !parse_short_option( ap, opt, arg, options, &argind ) ) goto out; if( ap->error ) break; } else { if( in_order ) - { if( !push_back_record( ap, 0, argv[argind++] ) ) return 0; } + { if( !push_back_record( ap, 0, 0, argv[argind++] ) ) goto out; } else { void * tmp = ap_resize_buffer( non_options, ( non_options_size + 1 ) * sizeof *non_options ); - if( !tmp ) return 0; + if( !tmp ) goto out; non_options = (const char **)tmp; non_options[non_options_size++] = argv[argind++]; } @@ -245,13 +270,15 @@ char ap_init( struct Arg_parser * const ap, if( ap->error ) free_data( ap ); else { + int i; for( i = 0; i < non_options_size; ++i ) - if( !push_back_record( ap, 0, non_options[i] ) ) return 0; + if( !push_back_record( ap, 0, 0, non_options[i] ) ) goto out; while( argind < argc ) - if( !push_back_record( ap, 0, argv[argind++] ) ) return 0; + if( !push_back_record( ap, 0, 0, argv[argind++] ) ) goto out; } - if( non_options ) free( non_options ); - return 1; + done = 1; +out: if( non_options ) free( non_options ); + return done; } @@ -273,13 +300,20 @@ int ap_arguments( const struct Arg_parser * const ap ) int ap_code( const struct Arg_parser * const ap, const int i ) { - if( i >= 0 && i < ap_arguments( ap ) ) return ap->data[i].code; - else return 0; + if( i < 0 || i >= ap_arguments( ap ) ) return 0; + return ap->data[i].code; + } + + +const char * ap_parsed_name( const struct Arg_parser * const ap, const int i ) + { + if( i < 0 || i >= ap_arguments( ap ) || !ap->data[i].parsed_name ) return ""; + return ap->data[i].parsed_name; } const char * ap_argument( const struct Arg_parser * const ap, const int i ) { - if( i >= 0 && i < ap_arguments( ap ) ) return ap->data[i].argument; - else return ""; + if( i < 0 || i >= ap_arguments( ap ) || !ap->data[i].argument ) return ""; + return ap->data[i].argument; } diff --git a/carg_parser.h b/carg_parser.h index c5f2352..0c64861 100644 --- a/carg_parser.h +++ b/carg_parser.h @@ -1,5 +1,5 @@ /* Arg_parser - POSIX/GNU command line argument parser. (C version) - Copyright (C) 2006-2021 Antonio Diaz Diaz. + Copyright (C) 2006-2022 Antonio Diaz Diaz. This library is free software. Redistribution and use in source and binary forms, with or without modification, are permitted provided @@ -24,9 +24,9 @@ message. 'options' is an array of 'struct ap_Option' terminated by an element - containing a code which is zero. A null name means a short-only - option. A code value outside the unsigned char range means a - long-only option. + containing a code which is zero. A null long_name means a short-only + option. A code value outside the unsigned char range means a long-only + option. Arg_parser normally makes it appear as if all the option arguments were specified before all the non-option arguments for the purposes @@ -50,7 +50,7 @@ enum ap_Has_arg { ap_no, ap_yes, ap_maybe }; struct ap_Option { int code; /* Short option letter or code ( code != 0 ) */ - const char * name; /* Long option name (maybe null) */ + const char * long_name; /* Long option name (maybe null) */ enum ap_Has_arg has_arg; }; @@ -58,6 +58,7 @@ struct ap_Option struct ap_Record { int code; + char * parsed_name; char * argument; }; @@ -86,6 +87,9 @@ int ap_arguments( const struct Arg_parser * const ap ); Else ap_argument( i ) is the option's argument (or empty). */ int ap_code( const struct Arg_parser * const ap, const int i ); +/* Full name of the option parsed (short or long). */ +const char * ap_parsed_name( const struct Arg_parser * const ap, const int i ); + const char * ap_argument( const struct Arg_parser * const ap, const int i ); #ifdef __cplusplus diff --git a/configure b/configure index 24fcec9..3531bcd 100755 --- a/configure +++ b/configure @@ -1,12 +1,12 @@ #! /bin/sh # configure script for GNU ed - The GNU line editor -# Copyright (C) 2006-2021 Antonio Diaz Diaz. +# Copyright (C) 2006-2022 Antonio Diaz Diaz. # # This configure script is free software: you have unlimited permission # to copy, distribute, and modify it. pkgname=ed -pkgversion=1.17 +pkgversion=1.18 progname=ed srctrigger=doc/${pkgname}.texi @@ -172,7 +172,7 @@ echo "LDFLAGS = ${LDFLAGS}" rm -f Makefile cat > Makefile << EOF # Makefile for GNU ed - The GNU line editor -# Copyright (C) 2006-2021 Antonio Diaz Diaz. +# Copyright (C) 2006-2022 Antonio Diaz Diaz. # This file was generated automatically by configure. Don't edit. # # This Makefile is free software: you have unlimited permission diff --git a/doc/ed.1 b/doc/ed.1 index 300586c..73ead67 100644 --- a/doc/ed.1 +++ b/doc/ed.1 @@ -1,5 +1,5 @@ .\" DO NOT MODIFY THIS FILE! It was generated by help2man 1.47.16. -.TH ED "1" "January 2021" "GNU ed 1.17" "User Commands" +.TH ED "1" "February 2022" "GNU ed 1.18" "User Commands" .SH NAME ed \- line-oriented text editor .SH SYNOPSIS @@ -41,13 +41,16 @@ suppress diagnostics, byte counts and '!' prompt .TP \fB\-v\fR, \fB\-\-verbose\fR be verbose; equivalent to the 'H' command +.TP +\fB\-\-strip\-trailing\-cr\fR +strip carriage returns at end of text lines .PP Start edit by reading in 'file' if given. If 'file' begins with a '!', read output of shell command. .PP Exit status: 0 for a normal exit, 1 for environmental problems (file not found, invalid flags, I/O errors, etc), 2 to indicate a corrupt or -invalid input file, 3 for an internal consistency error (eg, bug) which +invalid input file, 3 for an internal consistency error (e.g., bug) which caused ed to panic. .SH "REPORTING BUGS" Report bugs to bug\-ed@gnu.org @@ -58,8 +61,8 @@ General help using GNU software: http://www.gnu.org/gethelp .SH COPYRIGHT Copyright \(co 1994 Andrew L. Moore. .br -Copyright \(co 2021 Antonio Diaz Diaz. -License GPLv3+: GNU GPL version 3 or later +Copyright \(co 2022 Antonio Diaz Diaz. +License GPLv2+: GNU GPL version 2 or later .br This is free software: you are free to change and redistribute it. There is NO WARRANTY, to the extent permitted by law. diff --git a/doc/ed.info b/doc/ed.info index 7be071a..b4510a1 100644 --- a/doc/ed.info +++ b/doc/ed.info @@ -5,7 +5,7 @@ START-INFO-DIR-ENTRY * Ed: (ed). The GNU line editor END-INFO-DIR-ENTRY - Copyright (C) 1993, 1994, 2006-2021 Free Software Foundation, Inc. + Copyright (C) 1993, 1994, 2006-2022 Free Software Foundation, Inc. Permission is granted to copy, distribute and/or modify this document under the terms of the GNU Free Documentation License, Version 1.3 or any @@ -18,7 +18,7 @@ File: ed.info, Node: Top, Next: Overview, Up: (dir) The GNU ed line editor ********************** -This manual is for GNU ed (version 1.17, 6 January 2021). +This manual is for GNU ed (version 1.18, 4 February 2022). * Menu: @@ -28,13 +28,14 @@ This manual is for GNU ed (version 1.17, 6 January 2021). * Line addressing:: Specifying lines/ranges in the buffer * Regular expressions:: Patterns for selecting text * Commands:: Commands recognized by GNU 'ed' +* The 's' Command:: Substitute command * Limitations:: Intrinsic limits of GNU 'ed' * Diagnostics:: GNU 'ed' error handling * Problems:: Reporting bugs * GNU Free Documentation License:: How you can copy and share this manual - Copyright (C) 1993, 1994, 2006-2021 Free Software Foundation, Inc. + Copyright (C) 1993, 1994, 2006-2022 Free Software Foundation, Inc. Permission is granted to copy, distribute and/or modify this document under the terms of the GNU Free Documentation License, Version 1.3 or any @@ -61,7 +62,8 @@ and P. J. Plauger's book "Software Tools in Pascal", Addison-Wesley, 1981. If invoked with a FILE argument, then a copy of FILE is read into the editor's buffer. Changes are made to this copy and not directly to FILE itself. Upon quitting 'ed', any changes not explicitly saved with a 'w' -command are lost. +command are lost. In interactive mode, a non-existing FILE is reported but +does not alter the exit status. Editing is done in two distinct modes: "command" and "input". When first invoked, 'ed' is in command mode. In this mode commands are read from the @@ -363,6 +365,13 @@ default filename is set to FILE only if it is not prefixed with a bang. Verbose mode; prints error explanations. This may be toggled on and off with the 'H' command. +'--strip-trailing-cr' + Strip the carriage returns at the end of text lines in DOS files. CRs + are removed only from the CR/LF (carriage return/line feed) pair + ending the line. CRs at other positions in the line, including a CR + finishing an unterminated line, are not removed. The CRs are not + restored when saving the buffer to a file. + Exit status: 0 if no errors occurred; otherwise >0. @@ -432,15 +441,17 @@ of addresses to a command that requires zero addresses. The current through last lines in the buffer. This is equivalent to the address range '.;$'. -'/RE/' +'/RE/[I]' The next line containing the regular expression RE. The search wraps to the beginning of the buffer and continues down to the current line, - if necessary. + if necessary. The suffix 'I' is a GNU extension which makes 'ed' match + RE in a case-insensitive manner. -'?RE?' +'?RE?[I]' The previous line containing the regular expression RE. The search wraps to the end of the buffer and continues up to the current line, if - necessary. + necessary. The suffix 'I' is a GNU extension which makes 'ed' match RE + in a case-insensitive manner. ''x' The apostrophe-x character pair addresses the line previously marked by @@ -463,8 +474,8 @@ separated by whitespace. Offsets are constructed as follows: It is not an error if an intermediate address value is negative or greater than the address of the last line in the buffer. It is an error if the final address value is negative or greater than the address of the last -line in the buffer. It is an error if a search for a RE fails to find a -matching line. +line in the buffer. It is an error if a search for a regular expression +fails to find a matching line.  File: ed.info, Node: Regular expressions, Next: Commands, Prev: Line addressing, Up: Top @@ -488,7 +499,13 @@ match is the one selected. If the regular expression permits a variable number of matching characters, the longest sequence starting at that point is matched. - A null RE is equivalent to the last RE encountered. + An empty regular expression is equivalent to the last regular expression +processed. Therefore '/RE/s//REPLACEMENT/' replaces RE with REPLACEMENT. + + As a GNU extension, a regular expression /RE/ may be followed by the +suffix 'I' which makes 'ed' match RE in a case-insensitive manner. Note +that the suffix is evaluated when the regular expression is compiled, thus +it is invalid to specify it together with the empty regular expression. The following symbols are used in constructing regular expressions using POSIX basic regular expression syntax: @@ -540,7 +557,7 @@ POSIX basic regular expression syntax: regular expression to the end of a line. Otherwise, it matches itself. '\(RE\)' - Defines a (possibly null) subexpression RE. Subexpressions may be + Defines a (possibly empty) subexpression RE. Subexpressions may be nested. A subsequent backreference of the form '\N', where N is a number in the range [1,9], expands to the text matched by the Nth subexpression. For example, the regular expression '\(a.c\)\1' matches @@ -554,7 +571,7 @@ POSIX basic regular expression syntax: of a regular expression or subexpression, then it matches itself. The '*' operator sometimes yields unexpected results. For example, the regular expression 'b*' matches the beginning of the string 'abbb', as - opposed to the substring 'bbb', since a null match is the only + opposed to the substring 'bbb', since an empty string is the only left-most match. '\{N,M\}' @@ -599,27 +616,28 @@ implementation in your system. regular expression or subexpression, then it matches a literal '+'. '\b' - Matches the beginning or ending (null string) of a word. Thus the + Matches the beginning or ending (empty string) of a word. Thus the regular expression '\bhello\b' is equivalent to '\'. However, '\b\b' is a valid regular expression whereas '\<\>' is not. '\B' - Matches (a null string) inside a word. + Matches (an empty string) inside a word. '\w' - Matches any character in a word. + Matches any word-constituent character (letters, digits, and the + underscore). '\W' - Matches any character not in a word. + Matches any character that is not a word-constituent.  -File: ed.info, Node: Commands, Next: Limitations, Prev: Regular expressions, Up: Top +File: ed.info, Node: Commands, Next: The 's' Command, Prev: Regular expressions, Up: Top 6 Commands ********** -All 'ed' commands are single characters, though some require additonal +All 'ed' commands are single characters, though some require additional parameters. If a command's parameters extend over several lines, then each line except for the last must be terminated with a backslash ('\'). @@ -687,17 +705,18 @@ parenthesis). Sets the default filename to FILE. If FILE is not specified, then the default unescaped filename is printed. -'(1,$)g/RE/COMMAND-LIST' +'(1,$)g/RE/[I]COMMAND-LIST' Global command. The global command makes two passes over the file. On the first pass, all the addressed lines matching a regular expression - RE are marked. Then, going sequentially from the beginning of the file - to the end of the file, the given COMMAND-LIST is executed for each - marked line, with the current address set to the address of that line. - Any line modified by the COMMAND-LIST is unmarked. The final value of - the current address is the value assigned by the last command in the - last COMMAND-LIST executed. If there were no matching lines, the - current address is unchanged. The execution of COMMAND-LIST stops on - the first error. + RE are marked. The suffix 'I' is a GNU extension which makes 'ed' + match RE in a case-insensitive manner. Then, going sequentially from + the beginning of the file to the end of the file, the given + COMMAND-LIST is executed for each marked line, with the current + address set to the address of that line. Any line modified by the + COMMAND-LIST is unmarked. The final value of the current address is + the value assigned by the last command in the last COMMAND-LIST + executed. If there were no matching lines, the current address is + unchanged. The execution of COMMAND-LIST stops on the first error. The first command of COMMAND-LIST must appear on the same line as the 'g' command. The other commands of COMMAND-LIST must appear on @@ -710,17 +729,18 @@ parenthesis). the command-line option '-G', then a newline in COMMAND-LIST is equivalent to a '.+1p' command. -'(1,$)G/RE/' +'(1,$)G/RE/[I]' Interactive global command. Interactively edits the addressed lines - matching a regular expression RE. For each matching line, the line is - printed, the current address is set, and the user is prompted to enter - a COMMAND-LIST. The final value of the current address is the value - assigned by the last command executed. If there were no matching - lines, the current address is unchanged. + matching a regular expression RE. The suffix 'I' is a GNU extension + which makes 'ed' match RE in a case-insensitive manner. For each + matching line, the line is printed, the current address is set, and + the user is prompted to enter a COMMAND-LIST. The final value of the + current address is the value assigned by the last command executed. If + there were no matching lines, the current address is unchanged. The format of COMMAND-LIST is the same as that of the 'g' command. A - newline alone acts as a null command list. A single '&' repeats the - last non-null command list. + newline alone acts as an empty command list. A single '&' repeats the + last non-empty command list. 'h' Help. Prints an explanation of the last error. @@ -801,52 +821,6 @@ parenthesis). command whose output is to be read, (*note shell escape command:: '!' below). In this case the default filename is unchanged. -'(.,.)s/RE/REPLACEMENT/' - Substitute command. Replaces text in the addressed lines matching a - regular expression RE with REPLACEMENT. By default, only the first - match in each line is replaced. The 's' command accepts any - combination of the suffixes 'g', 'COUNT', 'l', 'n', and 'p'. If the - 'g' (global) suffix is given, then every match is replaced. The - 'COUNT' suffix, where COUNT is a positive number, causes only the - COUNTth match to be replaced. 'g' and 'COUNT' can't be specified in - the same command. 'l', 'n', and 'p' are the usual print suffixes. It - is an error if no substitutions are performed on any of the addressed - lines. The current address is set to the address of the last line on - which a substitution occurred. If a line is split, a substitution is - considered to have occurred on each of the new lines. If no - substitution is performed, the current address is unchanged. The last - line modified is copied to the cut buffer. - - RE and REPLACEMENT may be delimited by any character other than - , and the characters used by the form of the 's' - command shown below. If the last delimiter is omitted, then the last - line affected is printed as if the print suffix 'p' were specified. - The last delimiter can't be omitted if the 's' command is part of a - 'g' or 'v' COMMAND-LIST and is not the last command in the list, - because the meaning of the following escaped newline would become - ambiguous. - - An unescaped '&' in REPLACEMENT is replaced by the currently matched - text. The character sequence '\M' where M is a number in the range - [1,9], is replaced by the Mth backreference expression of the matched - text. If the corresponding backreference expression does not match, - then the character sequence '\M' is replaced by the empty string. If - REPLACEMENT consists of a single '%', then REPLACEMENT from the last - substitution is used. - - A line can be split by including a newline escaped with a backslash - ('\') in REPLACEMENT. Each backslash in REPLACEMENT removes the - special meaning (if any) of the following character. - -'(.,.)s' - Repeats the last substitution. This form of the 's' command accepts - the 'g' and 'COUNT' suffixes described above, and any combination of - the suffixes 'p' and 'r'. The 'g' suffix toggles the global suffix of - the last substitution and resets COUNT to 1. The 'p' suffix toggles - the print suffixes of the last substitution. The 'r' suffix causes the - RE of the last search to be used instead of the RE of the last - substitution (if the search happened after the substitution). - '(.,.)t(.)' Copies (i.e., transfers) the addressed lines to after the right-hand destination address. If the destination address is '0' (zero), the @@ -860,11 +834,11 @@ parenthesis). single command by undo. 'u' is its own inverse; it can undo only the last command. -'(1,$)v/RE/COMMAND-LIST' +'(1,$)v/RE/[I]COMMAND-LIST' This is similar to the 'g' command except that it applies COMMAND-LIST to each of the addressed lines not matching the regular expression RE. -'(1,$)V/RE/' +'(1,$)V/RE/[I]' This is similar to the 'G' command except that it interactively edits the addressed lines not matching the regular expression RE. @@ -911,10 +885,11 @@ parenthesis). Shell escape command. Executes COMMAND via 'sh (1)'. If the first character of COMMAND is '!', then it is replaced by the text of the previous '!COMMAND'. Thus, '!!' repeats the previous '!COMMAND'. 'ed' - does not process COMMAND for backslash ('\') escapes. However, an - unescaped '%' is replaced by the default filename. When the shell - returns from execution, a '!' is printed to the standard output. The - current address is unchanged. + does not process COMMAND for backslash ('\') escapes. However, each + unescaped '%' is replaced with the default filename, and the backslash + is removed from each escaped '%'. When the shell returns from + execution, a '!' is printed to the standard output. The current + address is unchanged. '(.,.)#' Begins a comment; the rest of the line, up to a newline, is ignored. @@ -928,14 +903,86 @@ parenthesis). '(.+1)' Null command. An address alone prints the addressed line. A - alone is equivalent to '+1p'. The current address is set to the - address of the printed line. + alone is equivalent to '+1p'. The current address is set to the address + of the printed line. + + + +File: ed.info, Node: The 's' Command, Next: Limitations, Prev: Commands, Up: Top + +7 Substitute command +******************** + +The substitute command 's' replaces text in the addressed lines matching a +regular expression RE with REPLACEMENT. By default, only the first match in +each line is replaced. The syntax of the 's' command is: + + (.,.)s/RE/REPLACEMENT/[SUFFIXES] + + The 's' command accepts any combination of the following optional +suffixes: +'g' + 'global': replace every match in the line, not just the first. + +'COUNT' + A positive number causes only the COUNTth match to be replaced. 'g' + and 'COUNT' can't be specified in the same command. + +'l' +'n' +'p' + The usual print suffixes. *Note print suffixes::. + +'I' +'i' + The suffix 'I' is a GNU extension which makes 'ed' match RE in a + case-insensitive manner. + + + It is an error if no substitutions are performed on any of the addressed +lines. The current address is set to the address of the last line on which a +substitution occurred. If a line is split, a substitution is considered to +have occurred on each of the new lines. If no substitution is performed, the +current address is unchanged. The last line modified is copied to the cut +buffer. + + RE and REPLACEMENT may be delimited by any character other than , + and the characters used by the form of the 's' command shown +below. If the last delimiter is omitted, then the last line affected is +printed as if the print suffix 'p' were specified. The last delimiter can't +be omitted if the 's' command is part of a 'g' or 'v' COMMAND-LIST and is +not the last command in the list, because the meaning of the following +escaped newline would become ambiguous. + + An unescaped '&' in REPLACEMENT is replaced by the currently matched +text. The character sequence '\M' where M is a number in the range [1,9], +is replaced by the Mth backreference expression of the matched text. If the +corresponding backreference expression does not match, then the character +sequence '\M' is replaced by the empty string. If REPLACEMENT consists of a +single '%', then REPLACEMENT from the last substitution is used. + + A line can be split by including a newline escaped with a backslash +('\') in REPLACEMENT. Each backslash in REPLACEMENT removes the special +meaning (if any) of the following character. + + 'ed' can repeat the last substitution using the following alternative +syntax for the 's' command: + + (.,.)s[SUFFIXES] + + This form of the 's' command accepts the suffixes 'g' and 'COUNT' +described above, and any combination of the suffixes 'p' and 'r'. The +suffix 'g' toggles the global suffix of the last substitution and resets +COUNT to 1. The suffix 'p' toggles the print suffixes of the last +substitution. The suffix 'r' causes the RE of the last search to be used +instead of the RE of the last substitution (if the search happened after +the substitution).  -File: ed.info, Node: Limitations, Next: Diagnostics, Prev: Commands, Up: Top +File: ed.info, Node: Limitations, Next: Diagnostics, Prev: The 's' Command, Up: Top -7 Limitations +8 Limitations ************* If the terminal hangs up, 'ed' attempts to write the buffer to the file @@ -956,12 +1003,13 @@ prevents appending a newline to a binary file. In order to keep track of the text lines in the buffer, 'ed' uses a doubly linked list of structures containing the position and size of each line. This results in a per line overhead of 2 'pointer's, 1 'long int', -and 1 'int'. +and 1 'int'. The maximum line length is INT_MAX - 1 bytes. The maximum +number of lines is INT_MAX - 2 lines.  File: ed.info, Node: Diagnostics, Next: Problems, Prev: Limitations, Up: Top -8 Diagnostics +9 Diagnostics ************* When an error occurs, if 'ed''s input is from a regular file or here @@ -979,8 +1027,8 @@ succeeds, but any changes to the buffer are lost.  File: ed.info, Node: Problems, Next: GNU Free Documentation License, Prev: Diagnostics, Up: Top -9 Reporting bugs -**************** +10 Reporting bugs +***************** There are probably bugs in 'ed'. There are certainly errors and omissions in this manual. If you report them, they will get fixed. If you don't, no @@ -994,7 +1042,7 @@ eternity, if not longer.  File: ed.info, Node: GNU Free Documentation License, Prev: Problems, Up: Top -10 GNU Free Documentation License +11 GNU Free Documentation License ********************************* Version 1.3, 3 November 2008 @@ -1458,17 +1506,19 @@ use in free software.  Tag Table: Node: Top535 -Node: Overview1708 -Node: Introduction to line editing4172 -Node: Invoking ed11443 -Node: Line addressing13741 -Node: Regular expressions17443 -Node: Commands23168 -Ref: shell escape command37583 -Node: Limitations38605 -Node: Diagnostics39697 -Node: Problems40342 -Node: GNU Free Documentation License40875 +Node: Overview1764 +Node: Introduction to line editing4317 +Node: Invoking ed11588 +Node: Line addressing14245 +Node: Regular expressions18159 +Node: Commands24344 +Ref: print suffixes24679 +Ref: shell escape command36257 +Node: The 's' Command37340 +Node: Limitations40254 +Node: Diagnostics41449 +Node: Problems42094 +Node: GNU Free Documentation License42629  End Tag Table diff --git a/doc/ed.texi b/doc/ed.texi index a28cbae..2ad831a 100644 --- a/doc/ed.texi +++ b/doc/ed.texi @@ -6,8 +6,8 @@ @finalout @c %**end of header -@set UPDATED 6 January 2021 -@set VERSION 1.17 +@set UPDATED 4 February 2022 +@set VERSION 1.18 @dircategory Basics @direntry @@ -15,7 +15,7 @@ @end direntry @copying -Copyright @copyright{} 1993, 1994, 2006-2021 Free Software Foundation, Inc. +Copyright @copyright{} 1993, 1994, 2006-2022 Free Software Foundation, Inc. Permission is granted to copy, distribute and/or modify this document under the terms of the GNU Free Documentation License, Version 1.3 or @@ -51,6 +51,7 @@ This manual is for GNU ed (version @value{VERSION}, @value{UPDATED}). * Line addressing:: Specifying lines/ranges in the buffer * Regular expressions:: Patterns for selecting text * Commands:: Commands recognized by GNU @command{ed} +* The 's' Command:: Substitute command * Limitations:: Intrinsic limits of GNU @command{ed} * Diagnostics:: GNU @command{ed} error handling * Problems:: Reporting bugs @@ -80,7 +81,8 @@ P. J. Plauger's book "Software Tools in Pascal", Addison-Wesley, 1981. If invoked with a @var{file} argument, then a copy of @var{file} is read into the editor's buffer. Changes are made to this copy and not directly to @var{file} itself. Upon quitting @command{ed}, any changes not -explicitly saved with a @samp{w} command are lost. +explicitly saved with a @samp{w} command are lost. In interactive mode, a +non-existing @var{file} is reported but does not alter the exit status. Editing is done in two distinct modes: @dfn{command} and @dfn{input}. When first invoked, @command{ed} is in command mode. In this mode @@ -107,17 +109,17 @@ lines, and so on. It is possible to modify only a portion of a line by means of replacement, as in the example above. However even here, the @samp{s} command is applied to whole lines at a time. -In general, @command{ed} commands consist of zero or more line -addresses, followed by a single character command and possibly -additional parameters; i.e., commands have the structure: +In general, @command{ed} commands consist of zero or more line addresses, +followed by a single character command and possibly additional parameters; +i.e., commands have the structure: @example [@var{address}[,@var{address}]]@var{command}[@var{parameters}] @end example -The @var{address}es indicate the line or range of lines to be affected -by the command. If fewer addresses are given than the command accepts, -then default addresses are supplied. +The @var{address}es indicate the line or range of lines to be affected by +the command. If fewer addresses are given than the command accepts, then +default addresses are supplied. @node Introduction to line editing @@ -423,6 +425,13 @@ input is from a script. Verbose mode; prints error explanations. This may be toggled on and off with the @samp{H} command. +@item --strip-trailing-cr +Strip the carriage returns at the end of text lines in DOS files. CRs are +removed only from the CR/LF (carriage return/line feed) pair ending the +line. CRs at other positions in the line, including a CR finishing an +unterminated line, are not removed. The CRs are not restored when saving the +buffer to a file. + @end table Exit status: 0 if no errors occurred; otherwise >0. @@ -494,15 +503,17 @@ address range @samp{1,$}. The current through last lines in the buffer. This is equivalent to the address range @samp{.;$}. -@item /@var{re}/ +@item /@var{re}/[I] The next line containing the regular expression @var{re}. The search wraps to the beginning of the buffer and continues down to the current -line, if necessary. +line, if necessary. The suffix @samp{I} is a GNU extension which makes +@command{ed} match @var{re} in a case-insensitive manner. -@item ?@var{re}? +@item ?@var{re}?[I] The previous line containing the regular expression @var{re}. The search wraps to the end of the buffer and continues up to the current line, if -necessary. +necessary. The suffix @samp{I} is a GNU extension which makes @command{ed} +match @var{re} in a case-insensitive manner. @item 'x The apostrophe-x character pair addresses the line previously marked by @@ -528,40 +539,46 @@ A number adds the indicated number of lines to the address. @end itemize -It is not an error if an intermediate address value is negative or -greater than the address of the last line in the buffer. It is an error -if the final address value is negative or greater than the address of -the last line in the buffer. It is an error if a search for a @var{re} -fails to find a matching line. +It is not an error if an intermediate address value is negative or greater +than the address of the last line in the buffer. It is an error if the final +address value is negative or greater than the address of the last line in +the buffer. It is an error if a search for a regular expression fails to +find a matching line. @node Regular expressions @chapter Regular expressions -Regular expressions are patterns used in selecting text. For example, -the @command{ed} command +Regular expressions are patterns used in selecting text. For example, the +@command{ed} command @example g/@var{string}/ @end example @noindent -prints all lines containing @var{string}. Regular expressions are also -used by the @samp{s} command for selecting old text to be replaced with -new text. +prints all lines containing @var{string}. Regular expressions are also used +by the @samp{s} command for selecting old text to be replaced with new text. + +In addition to specifying string literals, regular expressions can represent +classes of strings. Strings thus represented are said to be matched by the +corresponding regular expression. If it is possible for a regular expression +to match several strings in a line, then the left-most match is the one +selected. If the regular expression permits a variable number of matching +characters, the longest sequence starting at that point is matched. -In addition to specifying string literals, regular expressions can -represent classes of strings. Strings thus represented are said to be -matched by the corresponding regular expression. If it is possible for a -regular expression to match several strings in a line, then the -left-most match is the one selected. If the regular expression permits a -variable number of matching characters, the longest sequence starting at -that point is matched. +An empty regular expression is equivalent to the last regular expression +processed. Therefore @samp{/@var{re}/s//@var{replacement}/} replaces +@var{re} with @var{replacement}. -A null @var{re} is equivalent to the last @var{re} encountered. +As a GNU extension, a regular expression /@var{re}/ may be followed by the +suffix @samp{I} which makes @command{ed} match @var{re} in a +case-insensitive manner. Note that the suffix is evaluated when the regular +expression is compiled, thus it is invalid to specify it together with the +empty regular expression. -The following symbols are used in constructing regular expressions -using POSIX basic regular expression syntax: +The following symbols are used in constructing regular expressions using +POSIX basic regular expression syntax: @table @code @@ -620,7 +637,7 @@ If @samp{$} is the last character of a regular expression, it anchors the regular expression to the end of a line. Otherwise, it matches itself. @item \(@var{re}\) -Defines a (possibly null) subexpression @var{re}. Subexpressions may be +Defines a (possibly empty) subexpression @var{re}. Subexpressions may be nested. A subsequent backreference of the form @samp{\@var{n}}, where @var{n} is a number in the range [1,9], expands to the text matched by the @var{n}th subexpression. For example, the regular expression @@ -634,8 +651,8 @@ regular expression or a subexpression. If @samp{*} is the first character of a regular expression or subexpression, then it matches itself. The @samp{*} operator sometimes yields unexpected results. For example, the regular expression @samp{b*} matches the beginning of the -string @samp{abbb}, as opposed to the substring @samp{bbb}, since a null -match is the only left-most match. +string @samp{abbb}, as opposed to the substring @samp{bbb}, since an empty +string is the only left-most match. @item \@{@var{n},@var{m}\@} @itemx \@{@var{n},\@} @@ -683,19 +700,18 @@ beginning of a regular expression or subexpression, then it matches a literal @samp{+}. @item \b -Matches the beginning or ending (null string) of a word. Thus the -regular expression @samp{\bhello\b} is equivalent to @samp{\}. -However, @samp{\b\b} is a valid regular expression whereas @samp{\<\>} -is not. +Matches the beginning or ending (empty string) of a word. Thus the regular +expression @samp{\bhello\b} is equivalent to @samp{\}. However, +@samp{\b\b} is a valid regular expression whereas @samp{\<\>} is not. @item \B -Matches (a null string) inside a word. +Matches (an empty string) inside a word. @item \w -Matches any character in a word. +Matches any word-constituent character (letters, digits, and the underscore). @item \W -Matches any character not in a word. +Matches any character that is not a word-constituent. @end table @@ -704,10 +720,11 @@ Matches any character not in a word. @chapter Commands All @command{ed} commands are single characters, though some require -additonal parameters. If a command's parameters extend over several -lines, then each line except for the last must be terminated with a -backslash (@samp{\}). +additional parameters. If a command's parameters extend over several lines, +then each line except for the last must be terminated with a backslash +(@samp{\}). +@anchor{print suffixes} In general, at most one command is allowed per line. However, most commands accept a print suffix, which is any of @samp{p} (print), @samp{l} (list), or @samp{n} (enumerate), to print the last line @@ -775,17 +792,18 @@ command, except that unwritten changes are discarded without warning. Sets the default filename to @var{file}. If @var{file} is not specified, then the default unescaped filename is printed. -@item (1,$)g/@var{re}/@var{command-list} +@item (1,$)g/@var{re}/[I]@var{command-list} Global command. The global command makes two passes over the file. On the first pass, all the addressed lines matching a regular expression @var{re} -are marked. Then, going sequentially from the beginning of the file to the -end of the file, the given @var{command-list} is executed for each marked -line, with the current address set to the address of that line. Any line -modified by the @var{command-list} is unmarked. The final value of the -current address is the value assigned by the last command in the last -@var{command-list} executed. If there were no matching lines, the current -address is unchanged. The execution of @var{command-list} stops on the first -error. +are marked. The suffix @samp{I} is a GNU extension which makes @command{ed} +match @var{re} in a case-insensitive manner. Then, going sequentially from +the beginning of the file to the end of the file, the given +@var{command-list} is executed for each marked line, with the current +address set to the address of that line. Any line modified by the +@var{command-list} is unmarked. The final value of the current address is +the value assigned by the last command in the last @var{command-list} +executed. If there were no matching lines, the current address is unchanged. +The execution of @var{command-list} stops on the first error. The first command of @var{command-list} must appear on the same line as the @samp{g} command. The other commands of @var{command-list} must appear on @@ -798,17 +816,18 @@ newline alone in @var{command-list} is equivalent to a @samp{p} command. If @command{ed} is invoked with the command-line option @samp{-G}, then a newline in @var{command-list} is equivalent to a @samp{.+1p} command. -@item (1,$)G/@var{re}/ +@item (1,$)G/@var{re}/[I] Interactive global command. Interactively edits the addressed lines -matching a regular expression @var{re}. For each matching line, the line -is printed, the current address is set, and the user is prompted to -enter a @var{command-list}. The final value of the current address is -the value assigned by the last command executed. If there were no -matching lines, the current address is unchanged. +matching a regular expression @var{re}. The suffix @samp{I} is a GNU +extension which makes @command{ed} match @var{re} in a case-insensitive +manner. For each matching line, the line is printed, the current address is +set, and the user is prompted to enter a @var{command-list}. The final value +of the current address is the value assigned by the last command executed. +If there were no matching lines, the current address is unchanged. The format of @var{command-list} is the same as that of the @samp{g} -command. A newline alone acts as a null command list. A single @samp{&} -repeats the last non-null command list. +command. A newline alone acts as an empty command list. A single @samp{&} +repeats the last non-empty command list. @item h Help. Prints an explanation of the last error. @@ -889,53 +908,6 @@ If @var{file} is prefixed with a bang (!), then it is interpreted as a shell command whose output is to be read, (@pxref{shell escape command} @samp{!} below). In this case the default filename is unchanged. -@item (.,.)s/@var{re}/@var{replacement}/ -Substitute command. Replaces text in the addressed lines matching a regular -expression @var{re} with @var{replacement}. By default, only the first match -in each line is replaced. The @samp{s} command accepts any combination of -the suffixes @samp{g}, @samp{@var{count}}, @samp{l}, @samp{n}, and @samp{p}. -If the @samp{g} (global) suffix is given, then every match is replaced. The -@samp{@var{count}} suffix, where @var{count} is a positive number, causes -only the @var{count}th match to be replaced. @samp{g} and @samp{@var{count}} -can't be specified in the same command. @samp{l}, @samp{n}, and @samp{p} are -the usual print suffixes. It is an error if no substitutions are performed -on any of the addressed lines. The current address is set to the address of -the last line on which a substitution occurred. If a line is split, a -substitution is considered to have occurred on each of the new lines. If no -substitution is performed, the current address is unchanged. The last line -modified is copied to the cut buffer. - -@var{re} and @var{replacement} may be delimited by any character other -than @key{space}, @key{newline} and the characters used by the form of -the @samp{s} command shown below. If the last delimiter is omitted, then -the last line affected is printed as if the print suffix @samp{p} were -specified. The last delimiter can't be omitted if the @samp{s} command -is part of a @samp{g} or @samp{v} @var{command-list} and is not the last -command in the list, because the meaning of the following escaped -newline would become ambiguous. - -An unescaped @samp{&} in @var{replacement} is replaced by the currently -matched text. The character sequence @samp{\@var{m}} where @var{m} is a -number in the range [1,9], is replaced by the @var{m}th backreference -expression of the matched text. If the corresponding backreference -expression does not match, then the character sequence @samp{\@var{m}} is -replaced by the empty string. If @var{replacement} consists of a single -@samp{%}, then @var{replacement} from the last substitution is used. - -A line can be split by including a newline escaped with a backslash -(@samp{\}) in @var{replacement}. Each backslash in @var{replacement} -removes the special meaning (if any) of the following character. - -@item (.,.)s -Repeats the last substitution. This form of the @samp{s} command accepts -the @samp{g} and @samp{@var{count}} suffixes described above, and any -combination of the suffixes @samp{p} and @samp{r}. The @samp{g} suffix -toggles the global suffix of the last substitution and resets -@var{count} to 1. The @samp{p} suffix toggles the print suffixes of the -last substitution. The @samp{r} suffix causes the @var{re} of the last -search to be used instead of the @var{re} of the last substitution (if -the search happened after the substitution). - @item (.,.)t(.) Copies (i.e., transfers) the addressed lines to after the right-hand destination address. If the destination address is @samp{0} (zero), the @@ -949,12 +921,12 @@ global commands @samp{g}, @samp{G}, @samp{v}, and @samp{V} are treated as a single command by undo. @samp{u} is its own inverse; it can undo only the last command. -@item (1,$)v/@var{re}/@var{command-list} +@item (1,$)v/@var{re}/[I]@var{command-list} This is similar to the @samp{g} command except that it applies @var{command-list} to each of the addressed lines not matching the regular expression @var{re}. -@item (1,$)V/@var{re}/ +@item (1,$)V/@var{re}/[I] This is similar to the @samp{G} command except that it interactively edits the addressed lines not matching the regular expression @var{re}. @@ -999,14 +971,14 @@ address of the last line printed. @anchor{shell escape command} @item !@var{command} -Shell escape command. Executes @var{command} via @command{sh (1)}. If -the first character of @var{command} is @samp{!}, then it is replaced by -the text of the previous @samp{!@var{command}}. Thus, @samp{!!} repeats -the previous @samp{!@var{command}}. @command{ed} does not process -@var{command} for backslash (@samp{\}) escapes. However, an unescaped -@samp{%} is replaced by the default filename. When the shell returns -from execution, a @samp{!} is printed to the standard output. The -current address is unchanged. +Shell escape command. Executes @var{command} via @command{sh (1)}. If the +first character of @var{command} is @samp{!}, then it is replaced by the +text of the previous @samp{!@var{command}}. Thus, @samp{!!} repeats the +previous @samp{!@var{command}}. @command{ed} does not process @var{command} +for backslash (@samp{\}) escapes. However, each unescaped @samp{%} is +replaced with the default filename, and the backslash is removed from each +escaped @samp{%}. When the shell returns from execution, a @samp{!} is +printed to the standard output. The current address is unchanged. @item (.,.)# Begins a comment; the rest of the line, up to a newline, is ignored. If a @@ -1018,13 +990,93 @@ Prints the line number of the addressed line. The current address is unchanged. @item (.+1)@key{newline} -Null command. An address alone prints the addressed line. A -@key{newline} alone is equivalent to @samp{+1p}. The current address is -set to the address of the printed line. +Null command. An address alone prints the addressed line. A @key{newline} +alone is equivalent to @samp{+1p}. The current address is set to the address +of the printed line. @end table +@node The 's' Command +@chapter Substitute command + +The substitute command @samp{s} replaces text in the addressed lines +matching a regular expression @var{re} with @var{replacement}. By default, +only the first match in each line is replaced. The syntax of the @samp{s} +command is: + +@example +(.,.)s/@var{re}/@var{replacement}/[@var{suffixes}] +@end example + +The @samp{s} command accepts any combination of the following optional +suffixes: + +@table @code + +@item g +@samp{global}: replace every match in the line, not just the first. + +@item @var{count} +A positive number causes only the @var{count}th match to be replaced. +@samp{g} and @samp{@var{count}} can't be specified in the same command. + +@item l +@itemx n +@itemx p +The usual print suffixes. @xref{print suffixes}. + +@item I +@itemx i +The suffix @samp{I} is a GNU extension which makes @command{ed} match +@var{re} in a case-insensitive manner. + +@end table + +It is an error if no substitutions are performed on any of the addressed +lines. The current address is set to the address of the last line on which a +substitution occurred. If a line is split, a substitution is considered to +have occurred on each of the new lines. If no substitution is performed, the +current address is unchanged. The last line modified is copied to the cut +buffer. + +@var{re} and @var{replacement} may be delimited by any character other +than @key{space}, @key{newline} and the characters used by the form of +the @samp{s} command shown below. If the last delimiter is omitted, then +the last line affected is printed as if the print suffix @samp{p} were +specified. The last delimiter can't be omitted if the @samp{s} command +is part of a @samp{g} or @samp{v} @var{command-list} and is not the last +command in the list, because the meaning of the following escaped +newline would become ambiguous. + +An unescaped @samp{&} in @var{replacement} is replaced by the currently +matched text. The character sequence @samp{\@var{m}} where @var{m} is a +number in the range [1,9], is replaced by the @var{m}th backreference +expression of the matched text. If the corresponding backreference +expression does not match, then the character sequence @samp{\@var{m}} is +replaced by the empty string. If @var{replacement} consists of a single +@samp{%}, then @var{replacement} from the last substitution is used. + +A line can be split by including a newline escaped with a backslash +(@samp{\}) in @var{replacement}. Each backslash in @var{replacement} +removes the special meaning (if any) of the following character. + +@command{ed} can repeat the last substitution using the following +alternative syntax for the @samp{s} command: + +@example +(.,.)s[@var{suffixes}] +@end example + +This form of the @samp{s} command accepts the suffixes @samp{g} and +@samp{@var{count}} described above, and any combination of the suffixes +@samp{p} and @samp{r}. The suffix @samp{g} toggles the global suffix of the +last substitution and resets @var{count} to 1. The suffix @samp{p} toggles +the print suffixes of the last substitution. The suffix @samp{r} causes the +@var{re} of the last search to be used instead of the @var{re} of the last +substitution (if the search happened after the substitution). + + @node Limitations @chapter Limitations @@ -1045,8 +1097,9 @@ writing prevents appending a newline to a binary file. In order to keep track of the text lines in the buffer, @command{ed} uses a doubly linked list of structures containing the position and size of each -line. This results in a per line overhead of 2 @samp{pointer}s, 1 @samp{long -int}, and 1 @samp{int}. +line. This results in a per line overhead of @w{2 @samp{pointer}s}, +@w{1 @samp{long int}}, and @w{1 @samp{int}}. The maximum line length is +@w{INT_MAX - 1} bytes. The maximum number of lines is @w{INT_MAX - 2} lines. @node Diagnostics diff --git a/ed.h b/ed.h index a495ede..db0b4a6 100644 --- a/ed.h +++ b/ed.h @@ -1,7 +1,7 @@ /* Global declarations for the ed editor. */ /* GNU ed - The GNU line editor. Copyright (C) 1993, 1994 Andrew Moore, Talke Studio - Copyright (C) 2006-2021 Antonio Diaz Diaz. + Copyright (C) 2006-2022 Antonio Diaz Diaz. This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by @@ -24,9 +24,9 @@ typedef enum Bool bool; enum Pflags /* print suffixes */ { - GLS = 0x01, /* list after command */ - GNP = 0x02, /* enumerate after command */ - GPR = 0x04 /* print after command */ + pf_l = 0x01, /* list after command */ + pf_n = 0x02, /* enumerate after command */ + pf_p = 0x04 /* print after command */ }; @@ -49,13 +49,14 @@ typedef struct undo_t; #ifndef max -#define max( a,b ) ( (( a ) > ( b )) ? ( a ) : ( b ) ) +#define max( a, b ) ( (( a ) > ( b )) ? ( a ) : ( b ) ) #endif #ifndef min -#define min( a,b ) ( (( a ) < ( b )) ? ( a ) : ( b ) ) +#define min( a, b ) ( (( a ) < ( b )) ? ( a ) : ( b ) ) #endif static const char * const mem_msg = "Memory exhausted"; +static const char * const no_prev_subst = "No previous substitution"; /* defined in buffer.c */ bool append_lines( const char ** const ibufpp, const int addr, @@ -115,11 +116,12 @@ bool may_access_filename( const char * const name ); bool restricted( void ); bool scripted( void ); void show_strerror( const char * const filename, const int errcode ); +bool strip_cr( void ); bool traditional( void ); /* defined in main_loop.c */ void invalid_address( void ); -int main_loop( const bool loose ); +int main_loop( const bool initial_error, const bool loose ); bool set_def_filename( const char * const s ); void set_error_msg( const char * const msg ); bool set_prompt( const char * const s ); @@ -129,17 +131,19 @@ void unmark_line_node( const line_t * const lp ); /* defined in regex.c */ bool build_active_list( const char ** const ibufpp, const int first_addr, const int second_addr, const bool match ); +const char * get_pattern_for_s( const char ** const ibufpp ); bool extract_replacement( const char ** const ibufpp, const bool isglobal ); -int next_matching_node_addr( const char ** const ibufpp, const bool forward ); +int next_matching_node_addr( const char ** const ibufpp ); bool search_and_replace( const int first_addr, const int second_addr, const int snum, const bool isglobal ); -bool set_subst_regex( const char ** const ibufpp ); +bool set_subst_regex( const char * const pat, const bool ignore_case ); +bool replace_subst_re_by_search_re( void ); bool subst_regex( void ); /* defined in signal.c */ void disable_interrupts( void ); void enable_interrupts( void ); -bool resize_buffer( char ** const buf, int * const size, const int min_size ); +bool resize_buffer( char ** const buf, int * const size, const unsigned min_size ); void set_signals( void ); void set_window_lines( const int lines ); const char * strip_escapes( const char * p ); diff --git a/global.c b/global.c index c4bcf06..4572e18 100644 --- a/global.c +++ b/global.c @@ -1,7 +1,7 @@ /* global.c: global command routines for the ed line editor */ /* GNU ed - The GNU line editor. Copyright (C) 1993, 1994 Andrew Moore, Talke Studio - Copyright (C) 2006-2021 Antonio Diaz Diaz. + Copyright (C) 2006-2022 Antonio Diaz Diaz. This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by @@ -18,6 +18,7 @@ */ #include +#include #include #include #include @@ -28,8 +29,8 @@ static const line_t **active_list = 0; /* list of lines active in a global command */ static int active_size = 0; /* size (in bytes) of active_list */ static int active_len = 0; /* number of lines in active_list */ -static int active_ptr = 0; /* active_list index ( non-decreasing ) */ -static int active_ndx = 0; /* active_list index ( modulo active_last ) */ +static int active_idx = 0; /* active_list index ( non-decreasing ) */ +static int active_idxm = 0; /* active_list index ( modulo active_len ) */ /* clear the global-active list */ @@ -38,7 +39,7 @@ void clear_active_list( void ) disable_interrupts(); if( active_list ) free( active_list ); active_list = 0; - active_size = active_len = active_ptr = active_ndx = 0; + active_size = active_len = active_idx = active_idxm = 0; enable_interrupts(); } @@ -46,30 +47,29 @@ void clear_active_list( void ) /* return the next global-active line node */ const line_t * next_active_node( void ) { - while( active_ptr < active_len && !active_list[active_ptr] ) - ++active_ptr; - return ( active_ptr < active_len ) ? active_list[active_ptr++] : 0; + while( active_idx < active_len && !active_list[active_idx] ) + ++active_idx; + return ( active_idx < active_len ) ? active_list[active_idx++] : 0; } /* add a line node to the global-active list */ bool set_active_node( const line_t * const lp ) { - const int min_size = ( active_len + 1 ) * sizeof (line_t **); - if( active_size < min_size ) + const unsigned min_size = ( active_len + 1 ) * sizeof (line_t **); + if( (unsigned)active_size < min_size ) { - const int new_size = ( min_size < 512 ? 512 : ( min_size / 512 ) * 1024 ); + if( min_size >= INT_MAX ) + { set_error_msg( "Too many matching lines" ); return false; } + const int new_size = ( ( min_size < 512 ) ? 512 : + ( min_size > INT_MAX / 2 ) ? INT_MAX : ( min_size / 512 ) * 1024 ); void * new_buf = 0; disable_interrupts(); if( active_list ) new_buf = realloc( active_list, new_size ); else new_buf = malloc( new_size ); if( !new_buf ) - { - show_strerror( 0, errno ); - set_error_msg( mem_msg ); - enable_interrupts(); - return false; - } + { show_strerror( 0, errno ); + set_error_msg( mem_msg ); enable_interrupts(); return false; } active_size = new_size; active_list = (const line_t **)new_buf; enable_interrupts(); @@ -87,9 +87,9 @@ void unset_active_nodes( const line_t * bp, const line_t * const ep ) int i; for( i = 0; i < active_len; ++i ) { - if( ++active_ndx >= active_len ) active_ndx = 0; - if( active_list[active_ndx] == bp ) - { active_list[active_ndx] = 0; break; } + if( ++active_idxm >= active_len ) active_idxm = 0; + if( active_list[active_idxm] == bp ) + { active_list[active_idxm] = 0; break; } } bp = bp->q_forw; } diff --git a/io.c b/io.c index 702702e..2f9bd59 100644 --- a/io.c +++ b/io.c @@ -1,7 +1,7 @@ /* io.c: i/o routines for the ed line editor */ /* GNU ed - The GNU line editor. Copyright (C) 1993, 1994 Andrew Moore, Talke Studio - Copyright (C) 2006-2021 Antonio Diaz Diaz. + Copyright (C) 2006-2022 Antonio Diaz Diaz. This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by @@ -46,11 +46,11 @@ static void print_line( const char * p, int len, const int pflags ) const char escchars[] = "abfnrtv"; int col = 0; - if( pflags & GNP ) { printf( "%d\t", current_addr() ); col = 8; } + if( pflags & pf_n ) { printf( "%d\t", current_addr() ); col = 8; } while( --len >= 0 ) { const unsigned char ch = *p++; - if( !( pflags & GLS ) ) putchar( ch ); + if( !( pflags & pf_l ) ) putchar( ch ); else { if( ++col > window_columns() ) { col = 1; fputs( "\\\n", stdout ); } @@ -72,7 +72,7 @@ static void print_line( const char * p, int len, const int pflags ) } } } - if( !traditional() && ( pflags & GLS ) ) putchar('$'); + if( !traditional() && ( pflags & pf_l ) ) putchar('$'); putchar('\n'); } @@ -145,8 +145,9 @@ bool get_extended_line( const char ** const ibufpp, int * const lenp, /* Read a line of text from stdin. Incomplete lines (lacking the trailing newline) are discarded. - Returns pointer to buffer and line size (including trailing newline), - or 0 if error, or *sizep = 0 if EOF */ + Return pointer to buffer and line size (including trailing newline), + or 0 if error, or *sizep = 0 if EOF. +*/ const char * get_stdin_line( int * const sizep ) { static char * buf = 0; @@ -185,8 +186,9 @@ const char * get_stdin_line( int * const sizep ) /* Read a line of text from a stream. - Returns pointer to buffer and line size (including trailing newline - if it exists and is not added now) */ + Return pointer to buffer and line size (including trailing newline + if it exists and is not added now). +*/ static const char * read_stream_line( const char * const filename, FILE * const fp, int * const sizep, bool * const newline_addedp ) @@ -200,7 +202,10 @@ static const char * read_stream_line( const char * const filename, if( !resize_buffer( &buf, &bufsz, i + 2 ) ) return 0; c = getc( fp ); if( c == EOF ) break; buf[i++] = c; - if( !c ) set_binary(); else if( c == '\n' ) break; + if( !c ) set_binary(); + else if( c == '\n' ) /* remove CR only from CR/LF pairs */ + { if( strip_cr() && i > 1 && buf[i-2] == '\r' ) { buf[i-2] = '\n'; --i; } + break; } } buf[i] = 0; if( c == EOF ) @@ -268,7 +273,9 @@ static long read_stream( const char * const filename, FILE * const fp, } -/* read a named file/pipe into the buffer; return line count, or -1 if error */ +/* Read a named file/pipe into the buffer. + Return line count, -1 if file not found, -2 if fatal error. +*/ int read_file( const char * const filename, const int addr ) { FILE * fp; @@ -276,7 +283,12 @@ int read_file( const char * const filename, const int addr ) int ret; if( *filename == '!' ) fp = popen( filename + 1, "r" ); - else fp = fopen( strip_escapes( filename ), "r" ); + else + { + const char * const stripped_name = strip_escapes( filename ); + if( !stripped_name ) return -2; + fp = fopen( stripped_name, "r" ); + } if( !fp ) { show_strerror( filename, errno ); @@ -285,12 +297,12 @@ int read_file( const char * const filename, const int addr ) } size = read_stream( filename, fp, addr ); if( *filename == '!' ) ret = pclose( fp ); else ret = fclose( fp ); - if( size < 0 ) return -1; + if( size < 0 ) return -2; if( ret != 0 ) { show_strerror( filename, errno ); set_error_msg( "Cannot close input file" ); - return -1; + return -2; } if( !scripted() ) printf( "%lu\n", size ); return current_addr() - addr; @@ -335,7 +347,12 @@ int write_file( const char * const filename, const char * const mode, int ret; if( *filename == '!' ) fp = popen( filename + 1, "w" ); - else fp = fopen( strip_escapes( filename ), mode ); + else + { + const char * const stripped_name = strip_escapes( filename ); + if( !stripped_name ) return -1; + fp = fopen( stripped_name, mode ); + } if( !fp ) { show_strerror( filename, errno ); diff --git a/main.c b/main.c index e95d703..1e38ca0 100644 --- a/main.c +++ b/main.c @@ -1,5 +1,5 @@ /* GNU ed - The GNU line editor. - Copyright (C) 2006-2021 Antonio Diaz Diaz. + Copyright (C) 2006-2022 Antonio Diaz Diaz. This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by @@ -18,7 +18,7 @@ Exit status: 0 for a normal exit, 1 for environmental problems (file not found, invalid flags, I/O errors, etc), 2 to indicate a corrupt or invalid input file, 3 for an internal consistency error - (eg, bug) which caused ed to panic. + (e.g., bug) which caused ed to panic. */ /* * CREDITS @@ -43,19 +43,21 @@ static const char * const program_name = "ed"; -static const char * const program_year = "2021"; +static const char * const program_year = "2022"; static const char * invocation_name = "ed"; /* default value */ static bool extended_regexp_ = false; /* if set, use EREs */ static bool restricted_ = false; /* if set, run in restricted mode */ static bool scripted_ = false; /* if set, suppress diagnostics, byte counts and '!' prompt */ +static bool strip_cr_ = false; /* if set, strip trailing CRs */ static bool traditional_ = false; /* if set, be backwards compatible */ /* Access functions for command line flags. */ bool extended_regexp( void ) { return extended_regexp_; } bool restricted( void ) { return restricted_; } bool scripted( void ) { return scripted_; } +bool strip_cr( void ) { return strip_cr_; } bool traditional( void ) { return traditional_; } @@ -79,11 +81,12 @@ static void show_help( void ) " -r, --restricted run in restricted mode\n" " -s, --quiet, --silent suppress diagnostics, byte counts and '!' prompt\n" " -v, --verbose be verbose; equivalent to the 'H' command\n" + " --strip-trailing-cr strip carriage returns at end of text lines\n" "\nStart edit by reading in 'file' if given.\n" "If 'file' begins with a '!', read output of shell command.\n" "\nExit status: 0 for a normal exit, 1 for environmental problems (file\n" "not found, invalid flags, I/O errors, etc), 2 to indicate a corrupt or\n" - "invalid input file, 3 for an internal consistency error (eg, bug) which\n" + "invalid input file, 3 for an internal consistency error (e.g., bug) which\n" "caused ed to panic.\n" "\nReport bugs to bug-ed@gnu.org\n" "Ed home page: http://www.gnu.org/software/ed/ed.html\n" @@ -96,7 +99,7 @@ static void show_version( void ) printf( "GNU %s %s\n", program_name, PROGVERSION ); printf( "Copyright (C) 1994 Andrew L. Moore.\n" "Copyright (C) %s Antonio Diaz Diaz.\n", program_year ); - printf( "License GPLv3+: GNU GPL version 3 or later \n" + printf( "License GPLv2+: GNU GPL version 2 or later \n" "This is free software: you are free to change and redistribute it.\n" "There is NO WARRANTY, to the extent permitted by law.\n" ); } @@ -134,11 +137,12 @@ bool is_regular_file( const int fd ) bool may_access_filename( const char * const name ) { - if( restricted_ && - ( *name == '!' || strcmp( name, ".." ) == 0 || strchr( name, '/' ) ) ) + if( restricted_ ) { - set_error_msg( "Shell access restricted" ); - return false; + if( name[0] == '!' ) + { set_error_msg( "Shell access restricted" ); return false; } + if( strcmp( name, ".." ) == 0 || strchr( name, '/' ) ) + { set_error_msg( "Directory access restricted" ); return false; } } return true; } @@ -147,20 +151,23 @@ bool may_access_filename( const char * const name ) int main( const int argc, const char * const argv[] ) { int argind; + bool initial_error = false; /* fatal error reading file */ bool loose = false; + enum { opt_cr = 256 }; const struct ap_Option options[] = { - { 'E', "extended-regexp", ap_no }, - { 'G', "traditional", ap_no }, - { 'h', "help", ap_no }, - { 'l', "loose-exit-status", ap_no }, - { 'p', "prompt", ap_yes }, - { 'r', "restricted", ap_no }, - { 's', "quiet", ap_no }, - { 's', "silent", ap_no }, - { 'v', "verbose", ap_no }, - { 'V', "version", ap_no }, - { 0 , 0, ap_no } }; + { 'E', "extended-regexp", ap_no }, + { 'G', "traditional", ap_no }, + { 'h', "help", ap_no }, + { 'l', "loose-exit-status", ap_no }, + { 'p', "prompt", ap_yes }, + { 'r', "restricted", ap_no }, + { 's', "quiet", ap_no }, + { 's', "silent", ap_no }, + { 'v', "verbose", ap_no }, + { 'V', "version", ap_no }, + { opt_cr, "strip-trailing-cr", ap_no }, + { 0, 0, ap_no } }; struct Arg_parser parser; if( argc > 0 ) invocation_name = argv[0]; @@ -186,6 +193,7 @@ int main( const int argc, const char * const argv[] ) case 's': scripted_ = true; break; case 'v': set_verbose(); break; case 'V': show_version(); return 0; + case opt_cr: strip_cr_ = true; break; default : show_error( "internal error: uncaught option.", 0, false ); return 3; } @@ -200,19 +208,20 @@ int main( const int argc, const char * const argv[] ) if( strcmp( arg, "-" ) == 0 ) { scripted_ = true; ++argind; continue; } if( may_access_filename( arg ) ) { - if( read_file( arg, 0 ) < 0 && is_regular_file( 0 ) ) - return 2; - else if( arg[0] != '!' && !set_def_filename( arg ) ) return 1; + const int ret = read_file( arg, 0 ); + if( ret < 0 && is_regular_file( 0 ) ) return 2; + if( arg[0] != '!' && !set_def_filename( arg ) ) return 1; + if( ret == -2 ) initial_error = true; } else { - fputs( "?\n", stdout ); - if( arg[0] ) set_error_msg( "Invalid filename" ); if( is_regular_file( 0 ) ) return 2; + initial_error = true; } break; } ap_free( &parser ); - return main_loop( loose ); + if( initial_error ) fputs( "?\n", stdout ); + return main_loop( initial_error, loose ); } diff --git a/main_loop.c b/main_loop.c index 9485b5e..61b8dd0 100644 --- a/main_loop.c +++ b/main_loop.c @@ -1,6 +1,6 @@ /* GNU ed - The GNU line editor. Copyright (C) 1993, 1994 Andrew Moore, Talke Studio - Copyright (C) 2006-2021 Antonio Diaz Diaz. + Copyright (C) 2006-2022 Antonio Diaz Diaz. This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by @@ -31,7 +31,8 @@ enum Status { QUIT = -1, ERR = -2, EMOD = -3, FATAL = -4 }; static const char * const inv_com_suf = "Invalid command suffix"; static const char * const inv_mark_ch = "Invalid mark character"; -static const char * const no_cur_fn = "No current filename"; +static const char * const no_cur_fn = "No current filename"; +static const char * const no_prev_com = "No previous command"; static const char * def_filename = ""; /* default filename */ static char errmsg[80] = ""; /* error message buffer */ static const char * prompt_str = "*"; /* command prompt */ @@ -105,7 +106,7 @@ static int get_marked_node_addr( int c ) } -/* Returns pointer to copy of shell command in the command buffer */ +/* return pointer to copy of shell command in the command buffer */ static const char * get_shell_command( const char ** const ibufpp ) { static char * buf = 0; /* temporary buffer */ @@ -114,42 +115,46 @@ static const char * get_shell_command( const char ** const ibufpp ) static int shcmdsz = 0; /* shell command buffer size */ static int shcmdlen = 0; /* shell command length */ int i = 0, len = 0; - bool replacement = false; + bool replacement = false; /* true if '!' or '%' are replaced */ if( restricted() ) { set_error_msg( "Shell access restricted" ); return 0; } if( !get_extended_line( ibufpp, &len, true ) ) return 0; if( !resize_buffer( &buf, &bufsz, len + 1 ) ) return 0; if( **ibufpp != '!' ) buf[i++] = '!'; /* prefix command w/ bang */ - else + else /* replace '!' with the previous command */ { if( shcmdlen <= 0 || ( traditional() && !shcmd[1] ) ) - { set_error_msg( "No previous command" ); return 0; } + { set_error_msg( no_prev_com ); return 0; } memcpy( buf, shcmd, shcmdlen ); /* bufsz >= shcmdlen */ i += shcmdlen; ++*ibufpp; replacement = true; } while( **ibufpp != '\n' ) { - if( **ibufpp == '%' ) + if( **ibufpp == '%' ) /* replace '%' with the default filename */ { const char * p; if( !def_filename[0] ) { set_error_msg( no_cur_fn ); return 0; } p = strip_escapes( def_filename ); + if( !p ) return 0; len = strlen( p ); if( !resize_buffer( &buf, &bufsz, i + len ) ) return 0; memcpy( buf + i, p, len ); i += len; ++*ibufpp; replacement = true; } - else + else /* copy char or escape sequence unescaping any '%' */ { + char ch = *(*ibufpp)++; if( !resize_buffer( &buf, &bufsz, i + 2 ) ) return 0; - if( ( buf[i++] = *(*ibufpp)++ ) == '\\' ) buf[i++] = *(*ibufpp)++; + if( ch != '\\' ) { buf[i++] = ch; continue; } /* normal char */ + ch = *(*ibufpp)++; if( ch != '%' ) buf[i++] = '\\'; + buf[i++] = ch; } } while( **ibufpp == '\n' ) ++*ibufpp; /* skip newline */ if( !resize_buffer( &shcmd, &shcmdsz, i + 1 ) ) return 0; memcpy( shcmd, buf, i ); shcmd[i] = 0; shcmdlen = i; - if( replacement ) printf( "%s\n", shcmd + 1 ); + if( replacement ) { printf( "%s\n", shcmd + 1 ); fflush( stdout ); } return shcmd; } @@ -161,7 +166,7 @@ static const char * skip_blanks( const char * p ) } -/* Returns pointer to copy of filename in the command buffer */ +/* return pointer to copy of filename in the command buffer */ static const char * get_filename( const char ** const ibufpp, const bool traditional_f_command ) { @@ -217,9 +222,10 @@ static bool parse_int( int * const i, const char * const str, /* Get line addresses from the command buffer until an invalid address - is seen. Returns the number of addresses read, or -1 if error. + is seen. Return the number of addresses read, or -1 if error. If no addresses are found, both addresses are set to the current address. - If one address is found, both addresses are set to that address. */ + If one address is found, both addresses are set to that address. +*/ static int extract_addresses( const char ** const ibufpp ) { bool first = true; /* true == addr, false == offset */ @@ -257,9 +263,8 @@ static int extract_addresses( const char ** const ibufpp ) break; case '/': case '?': if( !first ) { invalid_address(); return -1; }; - second_addr = next_matching_node_addr( ibufpp, ch == '/' ); + second_addr = next_matching_node_addr( ibufpp ); if( second_addr < 0 ) return -1; - if( ch == **ibufpp ) ++*ibufpp; /* remove delimiter */ first = false; break; case '\'':if( !first ) { invalid_address(); return -1; }; first = false; ++*ibufpp; @@ -344,9 +349,28 @@ static bool check_second_addr( const int addr, const int addr_cnt ) /* verify the command suffixes in the command buffer */ static bool get_command_suffix( const char ** const ibufpp, - int * const pflagsp, int * const snump ) + int * const pflagsp ) { - bool nos_or_rep = !snump; /* not s command or repeated g/count */ + while( true ) + { + const unsigned char ch = **ibufpp; + if( ch == 'l' ) { if( *pflagsp & pf_l ) break; else *pflagsp |= pf_l; } + else if( ch == 'n' ) { if( *pflagsp & pf_n ) break; else *pflagsp |= pf_n; } + else if( ch == 'p' ) { if( *pflagsp & pf_p ) break; else *pflagsp |= pf_p; } + else break; + ++*ibufpp; + } + if( *(*ibufpp)++ != '\n' ) { set_error_msg( inv_com_suf ); return false; } + return true; + } + + +/* verify the command suffixes for command s in the command buffer */ +static bool get_command_s_suffix( const char ** const ibufpp, + int * const pflagsp, int * const snump, + bool * const ignore_casep ) + { + bool rep = false; /* repeated g/count */ bool error = false; while( true ) { @@ -354,15 +378,17 @@ static bool get_command_suffix( const char ** const ibufpp, if( ch >= '1' && ch <= '9' ) { int n = 0; - if( nos_or_rep || !parse_int( &n, *ibufpp, ibufpp ) || n <= 0 ) + if( rep || !parse_int( &n, *ibufpp, ibufpp ) || n <= 0 ) { error = true; break; } - nos_or_rep = true; *snump = n; continue; + rep = true; *snump = n; continue; } else if( ch == 'g' ) - { if( nos_or_rep ) break; else { nos_or_rep = true; *snump = 0; } } - else if( ch == 'l' ) { if( *pflagsp & GLS ) break; else *pflagsp |= GLS; } - else if( ch == 'n' ) { if( *pflagsp & GNP ) break; else *pflagsp |= GNP; } - else if( ch == 'p' ) { if( *pflagsp & GPR ) break; else *pflagsp |= GPR; } + { if( rep ) break; else { rep = true; *snump = 0; } } + else if( ch == 'i' || ch == 'I' ) + { if( *ignore_casep ) break; else *ignore_casep = true; } + else if( ch == 'l' ) { if( *pflagsp & pf_l ) break; else *pflagsp |= pf_l; } + else if( ch == 'n' ) { if( *pflagsp & pf_n ) break; else *pflagsp |= pf_n; } + else if( ch == 'p' ) { if( *pflagsp & pf_p ) break; else *pflagsp |= pf_p; } else break; ++*ibufpp; } @@ -390,13 +416,13 @@ static bool command_s( const char ** const ibufpp, int * const pflagsp, const int addr_cnt, const bool isglobal ) { static int pflags = 0; /* print suffixes */ - static int gmask = GPR; /* the print suffixes to be toggled */ + static int pmask = pf_p; /* the print suffixes to be toggled */ static int snum = 1; /* > 0 count, <= 0 global substitute */ enum Sflags { - SGG = 0x01, /* complement previous global substitute suffix */ - SGP = 0x02, /* complement previous print suffix */ - SGR = 0x04, /* use regex of last search (if newer) */ - SGF = 0x08 + sf_g = 0x01, /* complement previous global substitute suffix */ + sf_p = 0x02, /* complement previous print suffix */ + sf_r = 0x04, /* use regex of last search (if newer) */ + sf_none = 0x08 /* make sflags != 0 if no flags at all */ } sflags = 0; /* if sflags != 0, repeat last substitution */ if( !check_addr_range2( addr_cnt ) ) return false; @@ -405,41 +431,48 @@ static bool command_s( const char ** const ibufpp, int * const pflagsp, if( **ibufpp >= '1' && **ibufpp <= '9' ) { int n = 0; - if( ( sflags & SGG ) || !parse_int( &n, *ibufpp, ibufpp ) || n <= 0 ) + if( ( sflags & sf_g ) || !parse_int( &n, *ibufpp, ibufpp ) || n <= 0 ) error = true; else - { sflags |= SGG; snum = n; } + { sflags |= sf_g; snum = n; } } else switch( **ibufpp ) { - case '\n':sflags |= SGF; break; - case 'g': if( sflags & SGG ) error = true; - else { sflags |= SGG; snum = !snum; ++*ibufpp; } + case '\n':sflags |= sf_none; break; + case 'g': if( sflags & sf_g ) error = true; + else { sflags |= sf_g; snum = !snum; ++*ibufpp; } break; - case 'p': if( sflags & SGP ) error = true; - else { sflags |= SGP; ++*ibufpp; } break; - case 'r': if( sflags & SGR ) error = true; - else { sflags |= SGR; ++*ibufpp; } break; + case 'p': if( sflags & sf_p ) error = true; + else { sflags |= sf_p; ++*ibufpp; } break; + case 'r': if( sflags & sf_r ) error = true; + else { sflags |= sf_r; ++*ibufpp; } break; default : if( sflags ) error = true; } if( error ) { set_error_msg( inv_com_suf ); return false; } } while( sflags && **ibufpp != '\n' ); - if( sflags && !subst_regex() ) - { set_error_msg( "No previous substitution" ); return false; } - if( ( !sflags || ( sflags & SGR ) ) && !set_subst_regex( ibufpp ) ) - return false; - if( !sflags ) + if( sflags ) { + if( !subst_regex() ) { set_error_msg( no_prev_subst ); return false; } + if( ( sflags & sf_r ) && !replace_subst_re_by_search_re() ) return false; + if( sflags & sf_p ) pflags ^= pmask; + } + else /* don't compile RE until suffix 'I' is parsed */ + { + const char * pat = get_pattern_for_s( ibufpp ); + if( !pat ) return false; const char delimiter = **ibufpp; - pflags = 0; snum = 1; if( !extract_replacement( ibufpp, isglobal ) ) return false; - if( **ibufpp == '\n' ) pflags = GPR; /* omitted last delimiter */ - else if( **ibufpp == delimiter ) ++*ibufpp; /* skip delimiter */ - if( !get_command_suffix( ibufpp, &pflags, &snum ) ) return false; - gmask = pflags & ( GPR | GLS | GNP ); if( gmask == 0 ) gmask = GPR; + pflags = 0; snum = 1; + bool ignore_case = false; + if( **ibufpp == '\n' ) pflags = pf_p; /* omitted last delimiter */ + else + { if( **ibufpp == delimiter ) ++*ibufpp; /* skip delimiter */ + if( !get_command_s_suffix( ibufpp, &pflags, &snum, &ignore_case ) ) + return false; } + pmask = pflags & ( pf_l | pf_n | pf_p ); if( pmask == 0 ) pmask = pf_p; + if( !set_subst_regex( pat, ignore_case ) ) return false; } - else if( sflags & SGP ) pflags ^= gmask; *pflagsp = pflags; if( !isglobal ) clear_undo_stack(); if( !search_and_replace( first_addr, second_addr, snum, isglobal ) ) @@ -465,13 +498,13 @@ static int exec_command( const char ** const ibufpp, const int prev_status, c = *(*ibufpp)++; switch( c ) { - case 'a': if( !get_command_suffix( ibufpp, &pflags, 0 ) ) return ERR; + case 'a': if( !get_command_suffix( ibufpp, &pflags ) ) return ERR; if( !isglobal ) clear_undo_stack(); if( !append_lines( ibufpp, second_addr, false, isglobal ) ) return ERR; break; case 'c': if( !check_addr_range2( addr_cnt ) || - !get_command_suffix( ibufpp, &pflags, 0 ) ) return ERR; + !get_command_suffix( ibufpp, &pflags ) ) return ERR; if( !isglobal ) clear_undo_stack(); if( !delete_lines( first_addr, second_addr, isglobal ) || !append_lines( ibufpp, current_addr(), @@ -479,7 +512,7 @@ static int exec_command( const char ** const ibufpp, const int prev_status, return ERR; break; case 'd': if( !check_addr_range2( addr_cnt ) || - !get_command_suffix( ibufpp, &pflags, 0 ) ) return ERR; + !get_command_suffix( ibufpp, &pflags ) ) return ERR; if( !isglobal ) clear_undo_stack(); if( !delete_lines( first_addr, second_addr, isglobal ) ) return ERR; @@ -504,7 +537,11 @@ static int exec_command( const char ** const ibufpp, const int prev_status, if( fnp[0] == '!' ) { set_error_msg( "Invalid redirection" ); return ERR; } if( fnp[0] && !set_def_filename( fnp ) ) return ERR; - printf( "%s\n", strip_escapes( def_filename ) ); + { + const char * const stripped_name = strip_escapes( def_filename ); + if( !stripped_name ) return ERR; + printf( "%s\n", stripped_name ); + } break; case 'g': case 'v': @@ -516,38 +553,38 @@ static int exec_command( const char ** const ibufpp, const int prev_status, !build_active_list( ibufpp, first_addr, second_addr, n ) ) return ERR; n = ( c == 'G' || c == 'V' ); /* interactive */ - if( n && !get_command_suffix( ibufpp, &pflags, 0 ) ) return ERR; + if( n && !get_command_suffix( ibufpp, &pflags ) ) return ERR; n = exec_global( ibufpp, pflags, n ); if( n != 0 ) return n; break; case 'h': case 'H': if( unexpected_address( addr_cnt ) || - !get_command_suffix( ibufpp, &pflags, 0 ) ) return ERR; + !get_command_suffix( ibufpp, &pflags ) ) return ERR; if( c == 'H' ) verbose = !verbose; if( ( c == 'h' || verbose ) && errmsg[0] ) printf( "%s\n", errmsg ); break; - case 'i': if( !get_command_suffix( ibufpp, &pflags, 0 ) ) return ERR; + case 'i': if( !get_command_suffix( ibufpp, &pflags ) ) return ERR; if( !isglobal ) clear_undo_stack(); if( !append_lines( ibufpp, second_addr, true, isglobal ) ) return ERR; break; case 'j': if( !check_addr_range( current_addr(), current_addr() + 1, addr_cnt ) || - !get_command_suffix( ibufpp, &pflags, 0 ) ) return ERR; + !get_command_suffix( ibufpp, &pflags ) ) return ERR; if( !isglobal ) clear_undo_stack(); if( first_addr < second_addr && !join_lines( first_addr, second_addr, isglobal ) ) return ERR; break; case 'k': n = *(*ibufpp)++; if( second_addr == 0 ) { invalid_address(); return ERR; } - if( !get_command_suffix( ibufpp, &pflags, 0 ) || + if( !get_command_suffix( ibufpp, &pflags ) || !mark_line_node( search_line_node( second_addr ), n ) ) return ERR; break; - case 'l': - case 'n': - case 'p': if( c == 'l' ) n = GLS; else if( c == 'n' ) n = GNP; else n = GPR; - if( !check_addr_range2( addr_cnt ) || - !get_command_suffix( ibufpp, &pflags, 0 ) || + case 'l': n = pf_l; goto pflabel; + case 'n': n = pf_n; goto pflabel; + case 'p': n = pf_p; +pflabel: if( !check_addr_range2( addr_cnt ) || + !get_command_suffix( ibufpp, &pflags ) || !print_lines( first_addr, second_addr, pflags | n ) ) return ERR; pflags = 0; @@ -556,7 +593,7 @@ static int exec_command( const char ** const ibufpp, const int prev_status, !get_third_addr( ibufpp, &addr ) ) return ERR; if( addr >= first_addr && addr < second_addr ) { set_error_msg( "Invalid destination" ); return ERR; } - if( !get_command_suffix( ibufpp, &pflags, 0 ) ) return ERR; + if( !get_command_suffix( ibufpp, &pflags ) ) return ERR; if( !isglobal ) clear_undo_stack(); if( !move_lines( first_addr, second_addr, addr, isglobal ) ) return ERR; @@ -564,7 +601,7 @@ static int exec_command( const char ** const ibufpp, const int prev_status, case 'P': case 'q': case 'Q': if( unexpected_address( addr_cnt ) || - !get_command_suffix( ibufpp, &pflags, 0 ) ) return ERR; + !get_command_suffix( ibufpp, &pflags ) ) return ERR; if( c == 'P' ) prompt_on = !prompt_on; else if( c == 'q' && modified() && prev_status != EMOD ) return EMOD; @@ -586,12 +623,12 @@ static int exec_command( const char ** const ibufpp, const int prev_status, break; case 't': if( !check_addr_range2( addr_cnt ) || !get_third_addr( ibufpp, &addr ) || - !get_command_suffix( ibufpp, &pflags, 0 ) ) return ERR; + !get_command_suffix( ibufpp, &pflags ) ) return ERR; if( !isglobal ) clear_undo_stack(); if( !copy_lines( first_addr, second_addr, addr ) ) return ERR; break; case 'u': if( unexpected_address( addr_cnt ) || - !get_command_suffix( ibufpp, &pflags, 0 ) || + !get_command_suffix( ibufpp, &pflags ) || !undo( isglobal ) ) return ERR; break; case 'w': @@ -616,12 +653,12 @@ static int exec_command( const char ** const ibufpp, const int prev_status, break; case 'x': if( second_addr < 0 || second_addr > last_addr() ) { invalid_address(); return ERR; } - if( !get_command_suffix( ibufpp, &pflags, 0 ) ) return ERR; + if( !get_command_suffix( ibufpp, &pflags ) ) return ERR; if( !isglobal ) clear_undo_stack(); if( !put_lines( second_addr ) ) return ERR; break; case 'y': if( !check_addr_range2( addr_cnt ) || - !get_command_suffix( ibufpp, &pflags, 0 ) || + !get_command_suffix( ibufpp, &pflags ) || !yank_lines( first_addr, second_addr ) ) return ERR; break; case 'z': if( !check_second_addr( current_addr() + !isglobal, addr_cnt ) ) @@ -629,13 +666,13 @@ static int exec_command( const char ** const ibufpp, const int prev_status, if( **ibufpp > '0' && **ibufpp <= '9' ) { if( parse_int( &n, *ibufpp, ibufpp ) ) set_window_lines( n ); else return ERR; } - if( !get_command_suffix( ibufpp, &pflags, 0 ) || + if( !get_command_suffix( ibufpp, &pflags ) || !print_lines( second_addr, min( last_addr(), second_addr + window_lines() - 1 ), pflags ) ) return ERR; pflags = 0; break; - case '=': if( !get_command_suffix( ibufpp, &pflags, 0 ) ) return ERR; + case '=': if( !get_command_suffix( ibufpp, &pflags ) ) return ERR; printf( "%d\n", addr_cnt ? second_addr : last_addr() ); break; case '!': if( unexpected_address( addr_cnt ) ) return ERR; @@ -695,7 +732,7 @@ static int exec_global( const char ** const ibufpp, const int pflags, if( len <= 0 ) return ERR; /* EOF */ if( len == 1 && strcmp( *ibufpp, "\n" ) == 0 ) continue; if( len == 2 && strcmp( *ibufpp, "&\n" ) == 0 ) - { if( !cmd ) { set_error_msg( "No previous command" ); return ERR; } } + { if( !cmd ) { set_error_msg( no_prev_com ); return ERR; } } else { if( !get_extended_line( ibufpp, &len, false ) || @@ -721,7 +758,7 @@ static void script_error( void ) } -int main_loop( const bool loose ) +int main_loop( const bool initial_error, const bool loose ) { extern jmp_buf jmp_state; const char * ibufp; /* pointer to command buffer */ @@ -731,7 +768,8 @@ int main_loop( const bool loose ) disable_interrupts(); set_signals(); status = setjmp( jmp_state ); - if( !status ) enable_interrupts(); + if( status == 0 ) /* direct invocation of setjmp */ + { enable_interrupts(); if( initial_error ) { status = -1; err_status = 1; } } else { status = -1; fputs( "\n?\n", stdout ); set_error_msg( "Interrupt" ); } while( true ) diff --git a/regex.c b/regex.c index 3f88966..9b38120 100644 --- a/regex.c +++ b/regex.c @@ -1,7 +1,7 @@ /* regex.c: regular expression interface routines for the ed line editor. */ /* GNU ed - The GNU line editor. Copyright (C) 1993, 1994 Andrew Moore, Talke Studio - Copyright (C) 2006-2021 Antonio Diaz Diaz. + Copyright (C) 2006-2022 Antonio Diaz Diaz. This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by @@ -27,16 +27,20 @@ #include "ed.h" +static const char * const inv_i_suf = "Suffix 'I' not allowed on empty regexp"; static const char * const inv_pat_del = "Invalid pattern delimiter"; -static const char * const no_match = "No match"; -static regex_t * subst_regex_ = 0; /* regex of previous substitution */ +static const char * const mis_pat_del = "Missing pattern delimiter"; +static const char * const no_match = "No match"; +static const char * const no_prev_pat = "No previous pattern"; +static regex_t * last_regexp = 0; /* pointer to last regex found */ +static regex_t * subst_regexp = 0; /* regex of last substitution */ -static char * rbuf = 0; /* replacement buffer */ -static int rbufsz = 0; /* replacement buffer size */ -static int rlen = 0; /* replacement length */ +static char * rbuf = 0; /* replacement buffer */ +static int rbufsz = 0; /* replacement buffer size */ +static int rlen = 0; /* replacement length */ -bool subst_regex( void ) { return subst_regex_ != 0; } +bool subst_regex( void ) { return subst_regexp != 0; } /* translate characters in a string */ @@ -75,7 +79,9 @@ static const char * parse_char_class( const char * p ) } -/* copy a pattern string from the command buffer; return pointer to the copy */ +/* Copy a pattern string from the command buffer. If successful, return a + pointer to the copy and point *ibufpp to the closing delimiter or final + newline. */ static char * extract_pattern( const char ** const ibufpp, const char delimiter ) { static char * buf = 0; @@ -104,75 +110,124 @@ static char * extract_pattern( const char ** const ibufpp, const char delimiter } +/* Return pointer to compiled regex (last_regexp), different from subst_regexp. + Return 0 if error. +*/ +static regex_t * compile_regex( const char * const pat, const bool ignore_case ) + { + static regex_t store[3]; /* space for three compiled regexes */ + regex_t * exp; + int n; + + for( n = 0; n < 3; ++n ) + if( ( exp = &store[n] ) != last_regexp && exp != subst_regexp ) break; + const int cflags = ( extended_regexp() ? REG_EXTENDED : 0 ) | + ( ignore_case ? REG_ICASE : 0 ); + n = regcomp( exp, pat, cflags ); + if( n ) + { + char buf[80]; + regerror( n, last_regexp, buf, sizeof buf ); + set_error_msg( buf ); + return 0; + } + /* free last_regexp if compiled and different from subst_regexp */ + if( last_regexp && last_regexp != subst_regexp ) regfree( last_regexp ); + last_regexp = exp; + return last_regexp; + } + + /* return pointer to compiled regex from command buffer, or to previous compiled regex if empty RE. return 0 if error */ -static regex_t * get_compiled_regex( const char ** const ibufpp, - const bool test_delimiter ) +static regex_t * get_compiled_regex( const char ** const ibufpp ) { - static regex_t store[2]; /* space for two compiled regexes */ - static regex_t * exp = 0; - const char * pat; const char delimiter = **ibufpp; - int n; - if( delimiter == ' ' ) { set_error_msg( inv_pat_del ); return 0; } - if( delimiter == '\n' || *++*ibufpp == delimiter || - ( **ibufpp == '\n' && !test_delimiter ) ) + if( delimiter == ' ' || delimiter == '\n' ) + { set_error_msg( inv_pat_del ); return 0; } + if( *++*ibufpp == delimiter || **ibufpp == '\n' ) /* empty RE */ { - if( !exp ) set_error_msg( "No previous pattern" ); - return exp; + if( !last_regexp ) { set_error_msg( no_prev_pat ); return 0; } + if( **ibufpp == delimiter && *++*ibufpp == 'I' ) /* remove delimiter */ + { set_error_msg( inv_i_suf ); return 0; } + return last_regexp; } - pat = extract_pattern( ibufpp, delimiter ); - if( !pat ) return 0; - if( test_delimiter && delimiter != **ibufpp ) - { set_error_msg( "Missing pattern delimiter" ); return 0; } - /* exp compiled && not copied */ - if( exp && exp != subst_regex_ ) regfree( exp ); - else exp = ( &store[0] != subst_regex_ ) ? &store[0] : &store[1]; - n = regcomp( exp, pat, extended_regexp() ? REG_EXTENDED : 0 ); - if( n ) + else { - char buf[80]; - regerror( n, exp, buf, sizeof buf ); - set_error_msg( buf ); - exp = 0; + const char * const pat = extract_pattern( ibufpp, delimiter ); + if( !pat ) return 0; + bool ignore_case = false; + if( **ibufpp == delimiter && *++*ibufpp == 'I' ) /* remove delimiter */ + { ignore_case = true; ++*ibufpp; } /* remove suffix */ + return compile_regex( pat, ignore_case ); + } + } + + +/* Extract RE pattern (may be empty) from the command buffer. + Return 0 if error. +*/ +const char * get_pattern_for_s( const char ** const ibufpp ) + { + const char delimiter = **ibufpp; + + if( delimiter == ' ' || delimiter == '\n' ) + { set_error_msg( inv_pat_del ); return 0; } + if( *++*ibufpp == delimiter ) /* empty RE */ + { + if( !last_regexp ) { set_error_msg( no_prev_pat ); return 0; } + return ""; } - return exp; + const char * const pat = extract_pattern( ibufpp, delimiter ); + if( !pat ) return 0; + if( **ibufpp != delimiter ) { set_error_msg( mis_pat_del ); return 0; } + return pat; } -bool set_subst_regex( const char ** const ibufpp ) +bool set_subst_regex( const char * const pat, const bool ignore_case ) { - regex_t * exp; + if( !pat ) return false; + if( !*pat && ignore_case ) { set_error_msg( inv_i_suf ); return false; } disable_interrupts(); - exp = get_compiled_regex( ibufpp, true ); - if( exp && exp != subst_regex_ ) + regex_t * exp = *pat ? compile_regex( pat, ignore_case ) : last_regexp; + if( exp && exp != subst_regexp ) { - if( subst_regex_ ) regfree( subst_regex_ ); - subst_regex_ = exp; + if( subst_regexp ) regfree( subst_regexp ); + subst_regexp = exp; } enable_interrupts(); return ( exp ? true : false ); } -/* add line matching a regular expression to the global-active list */ +/* set subst_regexp to last RE found */ +bool replace_subst_re_by_search_re( void ) + { + if( !last_regexp ) { set_error_msg( no_prev_pat ); return false; } + if( last_regexp != subst_regexp ) + { + disable_interrupts(); + if( subst_regexp ) regfree( subst_regexp ); + subst_regexp = last_regexp; + enable_interrupts(); + } + return true; + } + + +/* add lines matching a regular expression to the global-active list */ bool build_active_list( const char ** const ibufpp, const int first_addr, const int second_addr, const bool match ) { - const regex_t * exp; - const line_t * lp; int addr; - const char delimiter = **ibufpp; - if( delimiter == ' ' || delimiter == '\n' ) - { set_error_msg( inv_pat_del ); return false; } - exp = get_compiled_regex( ibufpp, false ); + const regex_t * const exp = get_compiled_regex( ibufpp ); if( !exp ) return false; - if( **ibufpp == delimiter ) ++*ibufpp; clear_active_list(); - lp = search_line_node( first_addr ); + const line_t * lp = search_line_node( first_addr ); for( addr = first_addr; addr <= second_addr; ++addr, lp = lp->q_forw ) { char * const s = get_sbuf_line( lp ); @@ -187,9 +242,10 @@ bool build_active_list( const char ** const ibufpp, const int first_addr, /* return the address of the next line matching a regular expression in a given direction. wrap around begin/end of editor buffer if necessary */ -int next_matching_node_addr( const char ** const ibufpp, const bool forward ) +int next_matching_node_addr( const char ** const ibufpp ) { - const regex_t * const exp = get_compiled_regex( ibufpp, false ); + const bool forward = ( **ibufpp == '/' ); + const regex_t * const exp = get_compiled_regex( ibufpp ); int addr = current_addr(); if( !exp ) return -1; @@ -219,15 +275,14 @@ bool extract_replacement( const char ** const ibufpp, const bool isglobal ) int i = 0; const char delimiter = **ibufpp; - if( delimiter == '\n' ) - { set_error_msg( "Missing pattern delimiter" ); return false; } + if( delimiter == '\n' ) { set_error_msg( mis_pat_del ); return false; } ++*ibufpp; if( **ibufpp == '%' && /* replacement is a single '%' */ ( (*ibufpp)[1] == delimiter || ( (*ibufpp)[1] == '\n' && ( !isglobal || (*ibufpp)[2] == 0 ) ) ) ) { ++*ibufpp; - if( !rbuf ) { set_error_msg( "No previous substitution" ); return false; } + if( !rbuf ) { set_error_msg( no_prev_subst ); return false; } return true; } while( **ibufpp != delimiter ) @@ -270,14 +325,14 @@ static int replace_matched_text( char ** txtbufp, int * const txtbufszp, if( rbuf[i] == '&' ) { int j = rm[0].rm_so; int k = rm[0].rm_eo; - if( !resize_buffer( txtbufp, txtbufszp, offset + k - j ) ) return -1; + if( !resize_buffer( txtbufp, txtbufszp, offset - j + k ) ) return -1; while( j < k ) (*txtbufp)[offset++] = txt[j++]; } else if( rbuf[i] == '\\' && rbuf[++i] >= '1' && rbuf[i] <= '9' && ( n = rbuf[i] - '0' ) <= re_nsub ) { int j = rm[n].rm_so; int k = rm[n].rm_eo; - if( !resize_buffer( txtbufp, txtbufszp, offset + k - j ) ) return -1; + if( !resize_buffer( txtbufp, txtbufszp, offset - j + k ) ) return -1; while( j < k ) (*txtbufp)[offset++] = txt[j++]; } else /* preceding 'if' skipped escaping backslashes */ @@ -308,7 +363,7 @@ static int line_replace( char ** txtbufp, int * const txtbufszp, if( !txt ) return -1; if( isbinary() ) nul_to_newline( txt, lp->len ); eot = txt + lp->len; - if( !regexec( subst_regex_, txt, se_max, rm, 0 ) ) + if( !regexec( subst_regexp, txt, se_max, rm, 0 ) ) { int matchno = 0; bool infloop = false; @@ -320,7 +375,7 @@ static int line_replace( char ** txtbufp, int * const txtbufszp, if( isbinary() ) newline_to_nul( txt, rm[0].rm_eo ); memcpy( *txtbufp + offset, txt, i ); offset += i; offset = replace_matched_text( txtbufp, txtbufszp, txt, rm, offset, - subst_regex_->re_nsub ); + subst_regexp->re_nsub ); if( offset < 0 ) return -1; } else @@ -336,7 +391,7 @@ static int line_replace( char ** txtbufp, int * const txtbufszp, else { set_error_msg( "Infinite substitution loop" ); return -1; } } } while( *txt && ( !changed || global ) && - !regexec( subst_regex_, txt, se_max, rm, REG_NOTBOL ) ); + !regexec( subst_regexp, txt, se_max, rm, REG_NOTBOL ) ); i = eot - txt; if( !resize_buffer( txtbufp, txtbufszp, offset + i + 2 ) ) return -1; if( isbinary() ) newline_to_nul( txt, i ); diff --git a/signal.c b/signal.c index 3a8df9f..4f3a11a 100644 --- a/signal.c +++ b/signal.c @@ -1,7 +1,7 @@ /* signal.c: signal and miscellaneous routines for the ed line editor. */ /* GNU ed - The GNU line editor. Copyright (C) 1993, 1994 Andrew Moore, Talke Studio - Copyright (C) 2006-2021 Antonio Diaz Diaz. + Copyright (C) 2006-2022 Antonio Diaz Diaz. This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by @@ -19,6 +19,7 @@ #include #include +#include #include #include #include @@ -41,30 +42,23 @@ static bool sigint_pending = false; static void sighup_handler( int signum ) { if( signum ) {} /* keep compiler happy */ - if( mutex ) sighup_pending = true; - else - { - const char hb[] = "ed.hup"; - sighup_pending = false; - if( last_addr() && modified() && - write_file( hb, "w", 1, last_addr() ) < 0 ) - { - char * const s = getenv( "HOME" ); - const int len = ( s ? strlen( s ) : 0 ); - const int need_slash = ( ( !len || s[len-1] != '/' ) ? 1 : 0 ); - char * const hup = ( ( len + need_slash + (int)sizeof hb < path_max( 0 ) ) ? - (char *) malloc( len + need_slash + sizeof hb ) : 0 ); - if( len && hup ) /* hup filename */ - { - memcpy( hup, s, len ); - if( need_slash ) hup[len] = '/'; - memcpy( hup + len + need_slash, hb, sizeof hb ); - if( write_file( hup, "w", 1, last_addr() ) >= 0 ) exit( 0 ); - } - exit( 1 ); /* hup file write failed */ - } - exit( 0 ); - } + if( mutex ) { sighup_pending = true; return; } + sighup_pending = false; + const char hb[] = "ed.hup"; + if( last_addr() <= 0 || !modified() || + write_file( hb, "w", 1, last_addr() ) >= 0 ) exit( 0 ); + char * const s = getenv( "HOME" ); + if( !s || !s[0] ) exit( 1 ); + const int len = strlen( s ); + const int need_slash = s[len-1] != '/'; + char * const hup = ( len + need_slash + (int)sizeof hb < path_max( 0 ) ) ? + (char *)malloc( len + need_slash + sizeof hb ) : 0; + if( !hup ) exit( 1 ); /* hup file name */ + memcpy( hup, s, len ); + if( need_slash ) hup[len] = '/'; + memcpy( hup + len + need_slash, hb, sizeof hb ); + if( write_file( hup, "w", 1, last_addr() ) >= 0 ) exit( 0 ); + exit( 1 ); /* hup file write failed */ } @@ -146,22 +140,21 @@ int window_lines( void ) { return window_lines_; } /* assure at least a minimum size for buffer 'buf' */ -bool resize_buffer( char ** const buf, int * const size, const int min_size ) +bool resize_buffer( char ** const buf, int * const size, const unsigned min_size ) { - if( *size < min_size ) + if( (unsigned)*size < min_size ) { - const int new_size = ( min_size < 512 ? 512 : ( min_size / 512 ) * 1024 ); + if( min_size >= INT_MAX ) + { set_error_msg( "Line too long" ); return false; } + const int new_size = ( ( min_size < 512 ) ? 512 : + ( min_size > INT_MAX / 2 ) ? INT_MAX : ( min_size / 512 ) * 1024 ); void * new_buf = 0; disable_interrupts(); if( *buf ) new_buf = realloc( *buf, new_size ); else new_buf = malloc( new_size ); if( !new_buf ) - { - show_strerror( 0, errno ); - set_error_msg( mem_msg ); - enable_interrupts(); - return false; - } + { show_strerror( 0, errno ); + set_error_msg( mem_msg ); enable_interrupts(); return false; } *size = new_size; *buf = (char *)new_buf; enable_interrupts(); @@ -180,7 +173,6 @@ const char * strip_escapes( const char * p ) if( !resize_buffer( &buf, &bufsz, len + 1 ) ) return 0; /* assert: no trailing escape */ - while( ( buf[i++] = ( (*p == '\\' ) ? *++p : *p ) ) ) - ++p; + while( ( buf[i++] = ( ( *p == '\\' ) ? *++p : *p ) ) ) ++p; return buf; } diff --git a/testsuite/check.sh b/testsuite/check.sh index ac00006..a876571 100755 --- a/testsuite/check.sh +++ b/testsuite/check.sh @@ -1,6 +1,6 @@ #! /bin/sh # check script for GNU ed - The GNU line editor -# Copyright (C) 2006-2021 Antonio Diaz Diaz. +# Copyright (C) 2006-2022 Antonio Diaz Diaz. # # This script is free software; you have unlimited permission # to copy, distribute, and modify it. diff --git a/testsuite/d.ed b/testsuite/d.ed index 77eb36e..de81cb5 100644 --- a/testsuite/d.ed +++ b/testsuite/d.ed @@ -6,6 +6,10 @@ H u u +3,+4d +/And/Id +//d +??d +?All?Id # to be undone 1,$d u diff --git a/testsuite/d.r b/testsuite/d.r index 59e352f..46ece6b 100644 --- a/testsuite/d.r +++ b/testsuite/d.r @@ -1,7 +1,3 @@ -This natural inequality of the two powers of population and of me appears insurmountable in the way to the perfectibility of society. -All other arguments are of slight and subordinate consideration in comparison of this. I see no way by which man can escape from the weight agrarian regulations in their utmost extent, could remove the pressure -of it even for a single century. And it appears, therefore, to be -decisive against the possible existence of a society, all the members of diff --git a/testsuite/g.ed b/testsuite/g.ed index 0781e61..5514868 100644 --- a/testsuite/g.ed +++ b/testsuite/g.ed @@ -24,14 +24,14 @@ hello world\ # don't change current address if no match g/xxx/1d ;j -g/heLp! world//caos/d\ +g/help! world/I/caos/d\ -;/order/;d # split lines g/./s/hello world/hello\ world/ # use replacement from last substitution g/./s/animated/%/ -g/./s/difficulty/% +g/./Is/difficulty/% # to be undone g/./s//x/g u diff --git a/testsuite/g4.err b/testsuite/g4.err new file mode 100644 index 0000000..946fc58 --- /dev/null +++ b/testsuite/g4.err @@ -0,0 +1,4 @@ +H +/./ +g//Id +w out.ro diff --git a/testsuite/s.ed b/testsuite/s.ed index 7e1da83..9efded3 100644 --- a/testsuite/s.ed +++ b/testsuite/s.ed @@ -19,6 +19,9 @@ s/\([^ ][^ ]*\)/(\1)/pg /\(No\)/sr /\(.\)/sgpr ,s&$&$& +# set last regex to subst regex +//p +# use last regex as subst regex 5s//%/lg ,s%^%^% 5i diff --git a/testsuite/s22.err b/testsuite/s22.err new file mode 100644 index 0000000..ee575fb --- /dev/null +++ b/testsuite/s22.err @@ -0,0 +1,4 @@ +H +/./ +s//x/I +w out.ro -- 2.7.4