From a3ac830e34b2e7add84762375fed34584b11a53b Mon Sep 17 00:00:00 2001 From: Packit Bot Date: May 04 2021 22:17:02 +0000 Subject: ed-1.14.2 base --- diff --git a/AUTHORS b/AUTHORS new file mode 100644 index 0000000..26c3a0f --- /dev/null +++ b/AUTHORS @@ -0,0 +1,25 @@ +Since 2006 GNU ed is maintained by Antonio Diaz Diaz. + +Before version 0.3, GNU ed and its man page were written and maintained +(sic) by Andrew L. Moore. + +The original info page and GNUification of the code were graciously +provided by Fran�ois Pinard. + +------------------- + +GNU ed THANKS file - last updated on 15 November 1994. + +GNU ed originated with the editor algorithm from Brian W. Kernighan & +P. J. Plauger's wonderful book "Software Tools in Pascal", Addison-Wesley, +1981. GNU ed has also benefitted from the contributions of numerous people +who reported problems, suggested various improvements or submitted actual +code. Among these are the following: + +Eric Backus +Karl Berry +Theo Deraadt +Kaveh R. Ghazi +Mike Haertel +Fran�ois Pinard +Rodney Ruddock diff --git a/COPYING b/COPYING new file mode 100644 index 0000000..b27ad83 --- /dev/null +++ b/COPYING @@ -0,0 +1,674 @@ + GNU GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + 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 +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. + + 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. + + 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. + + 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 +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 +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 +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 + + 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 +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 +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + 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 + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . + +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: + + Copyright (C) + This program 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 +. diff --git a/ChangeLog b/ChangeLog new file mode 100644 index 0000000..68ce50d --- /dev/null +++ b/ChangeLog @@ -0,0 +1,273 @@ +2017-02-22 Antonio Diaz Diaz + + * Version 1.14.2 released. + * main.c (show_strerror) Revert to using '!scripted' instead of + 'verbose' to suppress diagnostics. + +2017-01-10 Antonio Diaz Diaz + + * Version 1.14.1 released. + * Print counts, messages, '?' and '!' to stdout instead of stderr. + * buffer.c (append_lines): Fixed current address after empty 'i'. + * regex.c (set_subst_regex): Treat missing delimiters consistently. + (extract_replacement): Don't replace 'a' with '%' in 's/a/%'. + Fixed infinite loop with EOF in the middle of a replacement. + Don't accept newlines in replacement in a global command. + Last delimiter can't be omitted if not last in command list. + (search_and_replace): Set current address to last line modified. + * main_loop.c (extract_addresses): Fixed address offsets; + '3 ---- 2' was calculated as -2 instead of 1. + Accept ranges with the first address omitted. + (exec_command): Fixed current address after empty replacement + text in 'c' command. + Don't clear the modified status after writing the buffer to a + shell command. (Reported by J�r�me Frgacic). + (get_command_suffix): Don't allow repeated print suffixes. + (command_s): Accept suffixes in any order. + Don't allow multiple count suffixes. + 'sp' now toggles all print suffixes. + (main_loop): Make EOF on stdin behave as a 'q' command. + * ed.texi: Fixed the description of commands 'acegijkmqrsuw'. + Documented that ed allows any combination of print suffixes. + * testsuite: Improved most tests. Simplified bug reporting. + * configure: Avoid warning on some shells when testing for gcc. + * Makefile.in: Detect the existence of install-info. + +2016-01-24 Antonio Diaz Diaz + + * Version 1.13 released. + * buffer.c (put_sbuf_line): Fixed a memory leak. + * io.c (read_file, write_file): Close file on error. + (Both issues reported by C�dric Picard). + +2015-07-04 Antonio Diaz Diaz + + * Version 1.12 released. + * ed.texi: Removed extra spaces from some commands. + +2015-03-30 Antonio Diaz Diaz + + * Version 1.11 released. + * main_loop.c (exec_command): Fixed 'z' command. + (zN printed N + 1 lines). + * ed.texi: Documented the window size used by the 'z' command. + * Makefile.in: Added new targets 'install*-compress'. + * Restored 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. + +2014-01-22 Antonio Diaz Diaz + + * Version 1.10 released. + * ed.texinfo: Renamed to ed.texi. + +2013-06-18 Antonio Diaz Diaz + + * Version 1.9 released. + * check.sh: Don't feed shell scripts to ed. + * configure: Options now accept a separate argument. + +2013-04-23 Antonio Diaz Diaz + + * Version 1.8 released. + * io.c (get_tty_line): Removed "double EOF" behavior. + +2012-10-09 Antonio Diaz Diaz + + * Version 1.7 released. + * main.c (main): Set invocation_name before calling show_error. + * Changed quote characters in messages as advised by GNU Standards. + * ed.texinfo: Fixed description of address offsets. + * ed.texinfo: Fixed a link to the Bash manual. + * configure: 'datadir' renamed to 'datarootdir'. + * Makefile.in: Added new target 'install-bin'. + +2012-01-01 Antonio Diaz Diaz + + * Version 1.6 released. + * io.c (put_tty_line): Null characters where incorrectly + shown by the 'l' command. (Reported by Martin Guy). + * io.c (read_stream): Corrected the condition deciding when to + show the message "Newline appended". + * main_loop.c (exec_command): The 'modified' flag is now set + when reading a non-empty file into an empty buffer. + * regex.c (translit_text): Fixed typo that prevented using NUL + characters in regular expressions. + * main_loop.c (exec_command): Return ERR if 'system' can't + create a shell process. + * main_loop.c (main_loop): Flush stdout/stderr before reading a + new command. + * buffer.c (put_sbuf_line): Added size parameter. + * ed.1: Man page is now generated with 'help2man'. + * ed.1: All command-line options are now documented in the man page. + * Restored copyright notices of Andrew L. Moore. It seems Andrew + granted some permissions but never assigned copyright to the FSF. + +2010-08-30 Antonio Diaz Diaz + + * Version 1.5 released. + * buffer.c (append_lines): Fixed 'a', 'c' and 'i' commands. + (When used in a global command list, the commands following + them in the list were ignored). + * main_loop.c (exec_command): Fixed 'e' command. + (It quitted when invoked a second time with a modified buffer). + * main.c: Added new option '--restricted'. + * 'red' has been converted to a script invoking 'ed --restricted'. + * Description of ed in the manual has been changed. + * testsuite: Modified some tests and removed obsolete posix tests. + * main_loop.c: 'ibufp' variable made local to main_loop. + * Defined type bool to make clear which functions and variables + are Boolean. + * Added 'const' to all pointer declarations accepting it. + * regex.c (replace_matching_text): Make se_max an enum. + * signal.c: Include termios.h + * Converted C99 style comments '//' to C89 style comments '/* */'. + * ed.texinfo: Fixed an erratum. + * Changed copyright holder from Andrew, Antonio to the FSF. + +2009-07-10 Antonio Diaz Diaz + + * Version 1.4 released. + * buffer.c, main_loop.c: Undo now restores the modified status. + * regex.c (search_and_replace): Fixed a race condition with user + interrupt. + * signal.c: Added functions resize_line_buffer and + resize_undo_buffer to definitively fix the aliasing warnings. + * Some minor corrections have been made to the manual. + +2009-05-24 Antonio Diaz Diaz + + * Version 1.3 released. + * carg_parser.c (ap_resize_buffer): An aliasing related segfault + that only occurs when overoptimizing with GCC on some + architectures (alpha, sparc) has been (hopefully) fixed. + * signal.c (resize_buffer): Likewise. + +2009-01-31 Antonio Diaz Diaz + + * Version 1.2 released. + * configure: Locale has been fixed to 'C'. + * Makefile.in: Man page is now installed by default. + * 'make install-info' should now work on Debian and OS X. + * ed.texinfo: License updated to GFDL version 1.3 or later. + +2008-10-14 Antonio Diaz Diaz + + * Version 1.1 released. + * configure: Quote arguments stored in config.status. + +2008-08-21 Antonio Diaz Diaz + + * Version 1.0 released. + * configure: Added option '--program-prefix'. + * signal.c (strip_escapes): Buffer overflow fixed. + * signal.c (resize_buffer): Pointer aliasing warning fixed. + +2008-02-24 Antonio Diaz Diaz + + * Version 0.9 released. + * signal.c (sighup_handler): Return 0 if no error. + * Arg_parser updated to 1.1. + +2007-08-18 Antonio Diaz Diaz + + * Version 0.8 released. + * check.sh: Testsuite exits unsuccesfully in case of error. + * ed.1: Fixed some minor problems in the manual page. + * ed.texinfo: Added 21kB of legalese (fdl.texinfo). + +2007-07-18 Antonio Diaz Diaz + + * Version 0.7 released. + * buffer.c (dec_addr): Now returns correct address when wrapping. + +2007-06-29 Antonio Diaz Diaz + + * Version 0.6 released. + * License updated to GPL version 3 or later. + * signal.c (sigwinch_handler, set_signal): + Fixed two minor compatibility problems. + * main_loop.c (main_loop): + Fixed an infinite loop when reading an empty script. + +2007-03-09 Antonio Diaz Diaz + + * Version 0.5 released. + * main_loop.c (next_addr): '%' reimplemented as it was in ed 0.2. + +2007-01-15 Antonio Diaz Diaz + + * Version 0.4 released. + * Fixed some minor problems in the testsuite. + +2006-11-11 Antonio Diaz Diaz + + * Version 0.3 released. + * buffer.c (open_sbuf): Fixed symlink vulnerability using 'tmpfile'. + * signal.c: Fixed signal handling for SIGINT. + * main_loop.c (exec_command): Fixed 'c' and 'i' commands with + address 0. + * The pause mode has been removed. + * main.c: Added new options '--loose-exit-status' and '--verbose'. + * carg_parser.c: New argument parser that replaces 'getopt_long'. + * 'configure' and 'Makefile.in' have been replaced. + * Removed recursive make for testsuite. + * Created directory 'doc'. + * Removed all pre ISO C89 code. + * Removed all global variables. + * ed.texinfo: Added the changes from Andrew and some mine. + +Sun Jun 26 22:21:59 1994 Andrew Moore + + * GNU ed 0.2 release. + + * main.c (yank_lines): Added yank buffer. + A range of lines may be cut ('d') to or yanked ('y') from + a yank buffer. Lines in the buffer may be put ('x') + after the addressed line (. by default). + + * main.c (display_lines): Page output of listed ('l') lines + if isatty(0). + + * main.c (main): Replaced isatty(0) with is_regular_file(). + Errors in piped scripts, as opposed to regular scripts or + here documents, do not force ed to exit. + + * Capitilize error messages per the standard. + +Wed Jun 22 01:06:11 1994 Andrew Moore + + * ed.h: Generic definition of INT_MAX + + * signal.c: Added #ifndef SIG_ERR + +Tue Apr 19 10:52:51 1994 Andrew Moore + + * Version 0.1. Initial release for GNU. + + * main.c (exec_command): Add comment command '#'. + +Mon Mar 21 21:58:11 PST 1994 Andrew Moore + + * Use umask 077 to open buffer file. + +Sat Mar 19 14:06:52 PST 1994 Andrew Moore + + * Removed problematic DES and insque support. + +Wed Jan 19 20:42:50 PST 1994 Andrew Moore + + * Added reliable signal(2) for SysV. + +Dec 1993 Fran�ois Pinard + + * GNUified ed. + + +Copyright (C) 1993 Fran�ois Pinard +Copyright (C) 1994 Andrew Moore +Copyright (C) 2006-2017 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 +modify it. diff --git a/INSTALL b/INSTALL new file mode 100644 index 0000000..444069b --- /dev/null +++ b/INSTALL @@ -0,0 +1,64 @@ +Requirements +------------ +You will need a C compiler and a C library compatible with GNU libc. +I use gcc 5.3.0 and 4.1.2, but the code should compile with any +standards compliant compiler. +Gcc is available at http://gcc.gnu.org. + + +Procedure +--------- +1. Unpack the archive if you have not done so already: + + tar -xf ed[version].tar.lz +or + lzip -cd ed[version].tar.lz | tar -xf - + +This creates the directory ./ed[version] containing the source from +the main archive. + +2. Change to ed directory and run configure. + (Try 'configure --help' for usage instructions). + + cd ed[version] + ./configure + +3. Run make. + + make + +4. Optionally, type 'make check' to run the tests that come with ed. + +5. Type 'make install' to install the program and any data files and + documentation. + + Or type 'make install-compress', which additionally compresses the + info manual and the man page after installation. (Installing + compressed docs may become the default in the future). + + You can install only the program, the info manual or the man page by + typing 'make install-bin', 'make install-info' or 'make install-man' + respectively. + + +Another way +----------- +You can also compile ed into a separate directory. +To do this, you must use a version of 'make' that supports the 'VPATH' +variable, such as GNU 'make'. 'cd' to the directory where you want the +object files and executables to go and run the 'configure' script. +'configure' automatically checks for the source code in '.', in '..' and +in the directory that 'configure' is in. + +'configure' recognizes the option '--srcdir=DIR' to control where to +look for the sources. Usually 'configure' can determine that directory +automatically. + +After running 'configure', you can run 'make' and 'make install' as +explained above. + + +Copyright (C) 2006-2017 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 new file mode 100644 index 0000000..18be552 --- /dev/null +++ b/Makefile.in @@ -0,0 +1,142 @@ + +DISTNAME = $(pkgname)-$(pkgversion) +INSTALL = install +INSTALL_PROGRAM = $(INSTALL) -m 755 +INSTALL_SCRIPT = $(INSTALL) -m 755 +INSTALL_DATA = $(INSTALL) -m 644 +INSTALL_DIR = $(INSTALL) -d -m 755 +SHELL = /bin/sh +CAN_RUN_INSTALLINFO = $(SHELL) -c "install-info --version" > /dev/null 2>&1 + +objs = buffer.o carg_parser.o global.o io.o main.o main_loop.o regex.o signal.o + + +.PHONY : all install install-bin install-info install-man \ + install-strip install-compress install-strip-compress \ + install-bin-strip install-info-compress install-man-compress \ + uninstall uninstall-bin uninstall-info uninstall-man \ + doc info man check dist clean distclean + +all : $(progname) r$(progname) + +$(progname) : $(objs) + $(CC) $(LDFLAGS) $(CFLAGS) -o $@ $(objs) + +r$(progname) : r$(progname).in + cat $(VPATH)/r$(progname).in > $@ + chmod a+x $@ + +main.o : main.c + $(CC) $(CPPFLAGS) $(CFLAGS) -DPROGVERSION=\"$(pkgversion)\" -c -o $@ $< + +%.o : %.c + $(CC) $(CPPFLAGS) $(CFLAGS) -c -o $@ $< + +$(objs) : Makefile ed.h +carg_parser.o : carg_parser.h +main.o : carg_parser.h + + +doc : info man + +info : $(VPATH)/doc/$(pkgname).info + +$(VPATH)/doc/$(pkgname).info : $(VPATH)/doc/$(pkgname).texi + cd $(VPATH)/doc && makeinfo $(pkgname).texi + +man : $(VPATH)/doc/$(progname).1 + +$(VPATH)/doc/$(progname).1 : $(progname) + help2man -n 'line-oriented text editor' -o $@ ./$(progname) + +Makefile : $(VPATH)/configure $(VPATH)/Makefile.in + ./config.status + +check : all + @$(VPATH)/testsuite/check.sh $(VPATH)/testsuite $(pkgversion) + +install : install-bin install-info install-man +install-strip : install-bin-strip install-info install-man +install-compress : install-bin install-info-compress install-man-compress +install-strip-compress : install-bin-strip install-info-compress install-man-compress + +install-bin : all + if [ ! -d "$(DESTDIR)$(bindir)" ] ; then $(INSTALL_DIR) "$(DESTDIR)$(bindir)" ; fi + $(INSTALL_PROGRAM) ./$(progname) "$(DESTDIR)$(bindir)/$(program_prefix)$(progname)" + $(INSTALL_SCRIPT) ./r$(progname) "$(DESTDIR)$(bindir)/$(program_prefix)r$(progname)" + +install-bin-strip : all + $(MAKE) INSTALL_PROGRAM='$(INSTALL_PROGRAM) -s' install-bin + +install-info : + if [ ! -d "$(DESTDIR)$(infodir)" ] ; then $(INSTALL_DIR) "$(DESTDIR)$(infodir)" ; fi + -rm -f "$(DESTDIR)$(infodir)/$(pkgname).info"* + $(INSTALL_DATA) $(VPATH)/doc/$(pkgname).info "$(DESTDIR)$(infodir)/$(program_prefix)$(pkgname).info" + -if $(CAN_RUN_INSTALLINFO) ; then \ + install-info --info-dir="$(DESTDIR)$(infodir)" "$(DESTDIR)$(infodir)/$(program_prefix)$(pkgname).info" ; \ + fi + +install-info-compress : install-info + lzip -v -9 "$(DESTDIR)$(infodir)/$(pkgname).info" + +install-man : + if [ ! -d "$(DESTDIR)$(mandir)/man1" ] ; then $(INSTALL_DIR) "$(DESTDIR)$(mandir)/man1" ; fi + -rm -f "$(DESTDIR)$(mandir)/man1/$(program_prefix)$(progname).1"* + -rm -f "$(DESTDIR)$(mandir)/man1/$(program_prefix)r$(progname).1"* + $(INSTALL_DATA) $(VPATH)/doc/$(progname).1 "$(DESTDIR)$(mandir)/man1/$(program_prefix)$(progname).1" + cd "$(DESTDIR)$(mandir)/man1" && ln -s "$(program_prefix)$(progname).1" "$(program_prefix)r$(progname).1" + +install-man-compress : install-man + lzip -v -9 "$(DESTDIR)$(mandir)/man1/$(program_prefix)$(progname).1" + -rm -f "$(DESTDIR)$(mandir)/man1/$(program_prefix)r$(progname).1"* + cd "$(DESTDIR)$(mandir)/man1" && ln -s "$(program_prefix)$(progname).1.lz" "$(program_prefix)r$(progname).1.lz" + +uninstall : uninstall-man uninstall-info uninstall-bin + +uninstall-bin : + -rm -f "$(DESTDIR)$(bindir)/$(program_prefix)$(progname)" + -rm -f "$(DESTDIR)$(bindir)/$(program_prefix)r$(progname)" + +uninstall-info : + -if $(CAN_RUN_INSTALLINFO) ; then \ + install-info --info-dir="$(DESTDIR)$(infodir)" --remove "$(DESTDIR)$(infodir)/$(program_prefix)$(pkgname).info" ; \ + fi + -rm -f "$(DESTDIR)$(infodir)/$(program_prefix)$(pkgname).info"* + +uninstall-man : + -rm -f "$(DESTDIR)$(mandir)/man1/$(program_prefix)$(progname).1"* + -rm -f "$(DESTDIR)$(mandir)/man1/$(program_prefix)r$(progname).1"* + +dist : doc + ln -sf $(VPATH) $(DISTNAME) + tar -Hustar --owner=root --group=root -cvf $(DISTNAME).tar \ + $(DISTNAME)/AUTHORS \ + $(DISTNAME)/COPYING \ + $(DISTNAME)/ChangeLog \ + $(DISTNAME)/INSTALL \ + $(DISTNAME)/Makefile.in \ + $(DISTNAME)/NEWS \ + $(DISTNAME)/README \ + $(DISTNAME)/TODO \ + $(DISTNAME)/configure \ + $(DISTNAME)/doc/$(progname).1 \ + $(DISTNAME)/doc/$(pkgname).info \ + $(DISTNAME)/doc/$(pkgname).texi \ + $(DISTNAME)/doc/fdl.texi \ + $(DISTNAME)/r$(progname).in \ + $(DISTNAME)/*.h \ + $(DISTNAME)/*.c \ + $(DISTNAME)/testsuite/check.sh \ + $(DISTNAME)/testsuite/test.bin \ + $(DISTNAME)/testsuite/test.txt \ + $(DISTNAME)/testsuite/*.ed \ + $(DISTNAME)/testsuite/*.r \ + $(DISTNAME)/testsuite/*.err + rm -f $(DISTNAME) + lzip -v -9 $(DISTNAME).tar + +clean : + -rm -f $(progname) r$(progname) $(objs) + +distclean : clean + -rm -f Makefile config.status *.tar *.tar.lz diff --git a/NEWS b/NEWS new file mode 100644 index 0000000..4ee028f --- /dev/null +++ b/NEWS @@ -0,0 +1,68 @@ +Changes in version 1.14: + +Version 1.14 is the largest bug hunt ever attempted in GNU ed. Other +goals of version 1.14 are to complete the documentation and to remove +any gratuitous incompatibilities with the POSIX standard. Thanks to Ori +Avtalion for initiating all this with a couple bug reports. ;-) + +Byte counts, informative messages, command error messages, and the '?' +and '!' prompts are now written to stdout instead of to stderr. The +standard error (stderr) is now used only for diagnostic messages. + +The current address is now correctly set to the addressed line after an +empty insert command. + +Fixed inconsistent behavior of the substitute command. It incorrectly +reported 'Invalid pattern delimiter' when the two last delimiters were +omitted after a null regular expression. Now it consistently reports +'Missing pattern delimiter' if the two last delimiters are omitted after +any regular expression (null or not). + +'s/a/%' has been fixed. It incorrectly replaced 'a' with '%' instead of +using the replacement from the last substitution. + +An infinite loop, happening when EOF was found in the middle of a +replacement string, has been fixed. + +Ed no longer accepts newlines in the replacement of a 's' command if it +is part of the command list of a global command, because in this case +the meaning of the newline becomes ambiguous. For the same reason, the +last delimiter can't be omitted if the 's' command is not the last +command in the command list. + +The substitute command now correctly sets the current address to the +address of the last line on which a substitution occurred, and leaves it +unchanged if no substitution is performed. + +A bug in the calculation of address offsets has been fixed. '3 ---- 2' +was calculated as address -2 instead of the correct address 1. + +Address ranges with the first address omitted are now accepted. + +The current address is now correctly set to the addressed line (or to +the new last line if at EOF) after an empty replacement text in the +change command. + +Repeated print suffixes are now rejected. It has been documented that ed +allows any combination of non-repeated print suffixes and combines their +effects. + +The substitute command now accepts suffixes in any order. + +The 'repeat substitution' command now rejects multiple count suffixes. + +The 'p' suffix of the 'repeat substitution' command now toggles all the +print suffixes of the last substitution. + +End of file on standard input now behaves as a 'q' command. + +The modified status is no longer cleared after writing the buffer to the +standard input of a shell command. (Reported by J�r�me Frgacic). + +The descriptions of the 'a', 'c', 'e', 'g', 'i', 'j', 'k', 'm', 'q', +'r', 's', 'u' and 'w' commands in the manual have been fixed. + +Most tests in the testsuite have been improved. Bug reporting has been +simplified; only the failed logs and results are kept in the test +directory, which can then be (tarred, compressed, and) attached to the +bug report. diff --git a/README b/README new file mode 100644 index 0000000..02ca109 --- /dev/null +++ b/README @@ -0,0 +1,137 @@ +Description + +GNU ed is a line-oriented text editor. It is used to create, display, +modify and otherwise manipulate text files, both interactively and via +shell scripts. A restricted version of ed, red, can only edit files in +the current directory and cannot execute shell commands. Ed is the +"standard" text editor in the sense that it is the original editor for +Unix, and thus widely available. For most purposes, however, it is +superseded by full-screen editors such as GNU Emacs or GNU Moe. + +Extensions to and deviations from the POSIX standard are described below. + +See the file INSTALL for compilation and installation instructions. + +Try "ed --help" for usage instructions. + +Report bugs to bug-ed@gnu.org + +Ed home page: http://www.gnu.org/software/ed/ed.html + +For a description of the ed algorithm, see Kernighan and Plauger's book +"Software Tools in Pascal", Addison-Wesley, 1981. + + +GNU ed(1) is not strictly POSIX compliant, as described in the +POSIX 1003.1-2004 document. The following is a summary of omissions +and extensions to, and deviations from, the POSIX standard. + +OMISSIONS +--------- + * Locale(3) is not supported. + +EXTENSIONS +---------- + * Though GNU ed is not a stream editor, it can be used to edit binary files. + To assist in binary editing, when a file containing at least one ASCII + NUL character is written, a newline is not appended if it did not + already contain one upon reading. In particular, reading /dev/null + prior to writing prevents appending a newline to a binary file. + + For example, to create a file with GNU ed containing a single NUL character: + $ ed file + a + ^@ + . + r /dev/null + wq + + Similarly, to remove a newline from the end of binary 'file': + $ ed file + r /dev/null + wq + + * BSD commands have been implemented wherever they do not conflict with + the POSIX standard. The BSD-ism's included are: + * 's' (i.e., s[1-9rgp]*) to repeat a previous substitution, + * 'W' for appending text to an existing file, + * 'wq' for exiting after a write, and + * 'z' for scrolling through the buffer. + + * The POSIX interactive global commands 'G' and 'V' are extended to + support multiple commands, including 'a', 'i' and 'c'. The command + format is the same as for the global commands 'g' and 'v', i.e., one + command per line with each line, except for the last, ending in a + backslash (\). + + * The file commands 'E', 'e', 'r', 'W' and 'w' process a + argument for backslash escapes; i.e., any character preceded by a + backslash is interpreted literally. If the first character of a + argument is a bang (!), then the rest of the line is + interpreted as a shell command, and no escape processing is + performed by GNU ed. + + * For SunOS ed(1) compatibility, GNU ed runs in restricted mode if invoked + as red. This limits editing of files in the local directory only and + prohibits shell commands. + +DEVIATIONS +---------- + * To support the BSD 's' command (see EXTENSIONS above), substitution + patterns cannot be delimited by the digits '1' to '9' or by the + characters 'r', 'g' and 'p'. In contrast, POSIX specifies that any + character except space and newline can be used as a delimiter. + + * Since the behavior of 'u' (undo) within a 'g' (global) command list is + not specified by POSIX, GNU ed follows the behavior of the SunOS ed: + undo forces a global command list to be executed only once, rather than + for each line matching a global pattern. In addtion, each instance of + 'u' within a global command undoes all previous commands (including + undo's) in the command list. This seems the best way, since the + alternatives are either too complicated to implement or too confusing + to use. + + * The 'm' (move) command within a 'g' command list also follows the SunOS + ed implementation: any moved lines are removed from the global command's + 'active' list. + + * For backwards compatibility, errors in piped scripts do not force ed + to exit. POSIX only specifies ed's response for input via regular + files (including here documents) or tty's. + + +TESTSUITE +--------- +The files in the 'testsuite' directory with extensions '.ed', '.r', and +'.err' are used for testing ed. To run the tests, configure the package +and type 'make check' from the build directory. The tests do not +exhaustively verify POSIX compliance nor do they verify correct 8-bit or +long line support. + +The test file extensions have the following meanings: +.ed Ed script - a list of ed commands. +.r Result - the expected output after processing data via an ed + script. +.err Error - invalid ed commands that should generate an error. + +The output of the .ed scripts is written to files with .o extension and +compared with their corresponding .r result files. The .err scripts +should exit with non-zero status without altering the contents of the +buffer. + +If any test fails, the error messages look like: + + *** The script u.ed exited abnormally *** +or: + *** Output u.o of script u.ed is incorrect *** + + +Copyright (C) 1993, 1994 Andrew Moore +Copyright (C) 2006-2017 Antonio Diaz Diaz. + +This file is free documentation: you have unlimited permission to copy, +distribute and modify it. + +The file Makefile.in is a data file used by configure to produce the +Makefile. It has the same copyright owner and permissions that configure +itself. diff --git a/TODO b/TODO new file mode 100644 index 0000000..bfc94fa --- /dev/null +++ b/TODO @@ -0,0 +1,8 @@ +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 new file mode 100644 index 0000000..18137d9 --- /dev/null +++ b/buffer.c @@ -0,0 +1,628 @@ +/* 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-2017 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 + 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, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . +*/ + +#include +#include +#include +#include +#include +#include +#include +#include + +#include "ed.h" + + +static int current_addr_ = 0; /* current address in editor buffer */ +static int last_addr_ = 0; /* last address in editor buffer */ +static bool isbinary_ = false; /* if set, buffer contains ASCII NULs */ +static bool modified_ = false; /* if set, buffer modified since last write */ + +static bool seek_write = false; /* seek before writing */ +static FILE * sfp = 0; /* scratch file pointer */ +static long sfpos = 0; /* scratch file position */ +static line_t buffer_head; /* editor buffer ( linked list of line_t )*/ +static line_t yank_buffer_head; + + +int current_addr( void ) { return current_addr_; } +int inc_current_addr( void ) + { if( ++current_addr_ > last_addr_ ) current_addr_ = last_addr_; + return current_addr_; } +void set_current_addr( const int addr ) { current_addr_ = addr; } + +int last_addr( void ) { return last_addr_; } + +bool isbinary( void ) { return isbinary_; } +void set_binary( void ) { isbinary_ = true; } + +bool modified( void ) { return modified_; } +void set_modified( const bool m ) { modified_ = m; } + + +int inc_addr( int addr ) + { if( ++addr > last_addr_ ) addr = 0; return addr; } + +int dec_addr( int addr ) + { if( --addr < 0 ) addr = last_addr_; return addr; } + + +/* link next and previous nodes */ +static void link_nodes( line_t * const prev, line_t * const next ) + { prev->q_forw = next; next->q_back = prev; } + + +/* insert line node into circular queue after previous */ +static void insert_node( line_t * const lp, line_t * const prev ) + { + link_nodes( lp, prev->q_forw ); + link_nodes( prev, lp ); + } + + +/* add a line node in the editor buffer after the given line */ +static void add_line_node( line_t * const lp ) + { + line_t * const prev = search_line_node( current_addr_ ); + insert_node( lp, prev ); + ++current_addr_; + ++last_addr_; + } + + +/* return a pointer to a copy of a line node, or to a new node if lp == 0 */ +static line_t * dup_line_node( line_t * const lp ) + { + line_t * const p = (line_t *) malloc( sizeof (line_t) ); + if( !p ) + { + show_strerror( 0, errno ); + set_error_msg( "Memory exhausted" ); + return 0; + } + if( lp ) { p->pos = lp->pos; p->len = lp->len; } + return p; + } + + +/* Insert text from stdin (or from command buffer if global) to after + line n; stop when either a single period is read or EOF. + Returns false if insertion fails. */ +bool append_lines( const char ** const ibufpp, const int addr, + bool insert, const bool isglobal ) + { + int size = 0; + undo_t * up = 0; + current_addr_ = addr; + + while( true ) + { + if( !isglobal ) + { + *ibufpp = get_stdin_line( &size ); + if( !*ibufpp ) return false; /* error */ + if( size <= 0 ) return true; /* EOF */ + } + else + { + if( !**ibufpp ) return true; + for( size = 0; (*ibufpp)[size++] != '\n'; ) ; + } + if( size == 2 && **ibufpp == '.' ) { *ibufpp += size; return true; } + disable_interrupts(); + if( insert ) { insert = false; if( current_addr_ > 0 ) --current_addr_; } + if( !put_sbuf_line( *ibufpp, size ) ) + { enable_interrupts(); return false; } + if( up ) up->tail = search_line_node( current_addr_ ); + else + { + up = push_undo_atom( UADD, current_addr_, current_addr_ ); + if( !up ) { enable_interrupts(); return false; } + } + *ibufpp += size; + modified_ = true; + enable_interrupts(); + } + } + + +static void clear_yank_buffer( void ) + { + line_t * lp = yank_buffer_head.q_forw; + + disable_interrupts(); + while( lp != &yank_buffer_head ) + { + line_t * const p = lp->q_forw; + link_nodes( lp->q_back, lp->q_forw ); + free( lp ); + lp = p; + } + enable_interrupts(); + } + + +/* close scratch file */ +bool close_sbuf( void ) + { + clear_yank_buffer(); + clear_undo_stack(); + if( sfp ) + { + if( fclose( sfp ) != 0 ) + { + show_strerror( 0, errno ); + set_error_msg( "Cannot close temp file" ); + return false; + } + sfp = 0; + } + sfpos = 0; + seek_write = false; + return true; + } + + +/* copy a range of lines; return false if error */ +bool copy_lines( const int first_addr, const int second_addr, const int addr ) + { + line_t *lp, *np = search_line_node( first_addr ); + undo_t * up = 0; + int n = second_addr - first_addr + 1; + int m = 0; + + current_addr_ = addr; + if( addr >= first_addr && addr < second_addr ) + { + n = addr - first_addr + 1; + m = second_addr - addr; + } + for( ; n > 0; n = m, m = 0, np = search_line_node( current_addr_ + 1 ) ) + for( ; n-- > 0; np = np->q_forw ) + { + disable_interrupts(); + lp = dup_line_node( np ); + if( !lp ) { enable_interrupts(); return false; } + add_line_node( lp ); + if( up ) up->tail = lp; + else + { + up = push_undo_atom( UADD, current_addr_, current_addr_ ); + if( !up ) { enable_interrupts(); return false; } + } + modified_ = true; + enable_interrupts(); + } + return true; + } + + +/* delete a range of lines */ +bool delete_lines( const int from, const int to, const bool isglobal ) + { + line_t *n, *p; + + if( !yank_lines( from, to ) ) return false; + disable_interrupts(); + if( !push_undo_atom( UDEL, from, to ) ) + { enable_interrupts(); return false; } + n = search_line_node( inc_addr( to ) ); + p = search_line_node( from - 1 ); /* this search_line_node last! */ + if( isglobal ) unset_active_nodes( p->q_forw, n ); + link_nodes( p, n ); + last_addr_ -= to - from + 1; + current_addr_ = min( from, last_addr_ ); + modified_ = true; + enable_interrupts(); + return true; + } + + +/* return line number of pointer */ +int get_line_node_addr( const line_t * const lp ) + { + const line_t * p = &buffer_head; + int addr = 0; + + while( p != lp && ( p = p->q_forw ) != &buffer_head ) ++addr; + if( addr && p == &buffer_head ) + { set_error_msg( "Invalid address" ); return -1; } + return addr; + } + + +/* get a line of text from the scratch file; return pointer to the text */ +char * get_sbuf_line( const line_t * const lp ) + { + static char * buf = 0; + static int bufsz = 0; + int len; + + if( lp == &buffer_head ) return 0; + seek_write = true; /* force seek on write */ + /* out of position */ + if( sfpos != lp->pos ) + { + sfpos = lp->pos; + if( fseek( sfp, sfpos, SEEK_SET ) != 0 ) + { + show_strerror( 0, errno ); + set_error_msg( "Cannot seek temp file" ); + return 0; + } + } + len = lp->len; + if( !resize_buffer( &buf, &bufsz, len + 1 ) ) return 0; + if( (int)fread( buf, 1, len, sfp ) != len ) + { + show_strerror( 0, errno ); + set_error_msg( "Cannot read temp file" ); + return 0; + } + sfpos += len; /* update file position */ + buf[len] = 0; + return buf; + } + + +/* open scratch buffer; initialize line queue */ +bool init_buffers( void ) + { + /* Read stdin one character at a time to avoid i/o contention + with shell escapes invoked by nonterminal input, e.g., + ed - <len ) ) return false; + memcpy( buf + size, s, bp->len ); + size += bp->len; + bp = bp->q_forw; + } + if( !resize_buffer( &buf, &bufsz, size + 2 ) ) return false; + buf[size++] = '\n'; + buf[size++] = 0; + if( !delete_lines( from, to, isglobal ) ) return false; + current_addr_ = from - 1; + disable_interrupts(); + if( !put_sbuf_line( buf, size ) || + !push_undo_atom( UADD, current_addr_, current_addr_ ) ) + { enable_interrupts(); return false; } + modified_ = true; + enable_interrupts(); + return true; + } + + +/* move a range of lines */ +bool move_lines( const int first_addr, const int second_addr, const int addr, + const bool isglobal ) + { + line_t *b1, *a1, *b2, *a2; + int n = inc_addr( second_addr ); + int p = first_addr - 1; + + disable_interrupts(); + if( addr == first_addr - 1 || addr == second_addr ) + { + a2 = search_line_node( n ); + b2 = search_line_node( p ); + current_addr_ = second_addr; + } + else if( !push_undo_atom( UMOV, p, n ) || + !push_undo_atom( UMOV, addr, inc_addr( addr ) ) ) + { enable_interrupts(); return false; } + else + { + a1 = search_line_node( n ); + if( addr < first_addr ) + { + b1 = search_line_node( p ); + b2 = search_line_node( addr ); /* this search_line_node last! */ + } + else + { + b2 = search_line_node( addr ); + b1 = search_line_node( p ); /* this search_line_node last! */ + } + a2 = b2->q_forw; + link_nodes( b2, b1->q_forw ); + link_nodes( a1->q_back, a2 ); + link_nodes( b1, a1 ); + current_addr_ = addr + ( ( addr < first_addr ) ? + second_addr - first_addr + 1 : 0 ); + } + if( isglobal ) unset_active_nodes( b2->q_forw, a2 ); + modified_ = true; + enable_interrupts(); + return true; + } + + +/* open scratch file */ +bool open_sbuf( void ) + { + isbinary_ = false; reset_unterminated_line(); + sfp = tmpfile(); + if( !sfp ) + { + show_strerror( 0, errno ); + set_error_msg( "Cannot open temp file" ); + return false; + } + return true; + } + + +int path_max( const char * filename ) + { + long result; + if( !filename ) filename = "/"; + errno = 0; + result = pathconf( filename, _PC_PATH_MAX ); + if( result < 0 ) { if( errno ) result = 256; else result = 1024; } + else if( result < 256 ) result = 256; + return result; + } + + +/* append lines from the yank buffer */ +bool put_lines( const int addr ) + { + undo_t * up = 0; + line_t *p, *lp = yank_buffer_head.q_forw; + + if( lp == &yank_buffer_head ) + { set_error_msg( "Nothing to put" ); return false; } + current_addr_ = addr; + while( lp != &yank_buffer_head ) + { + disable_interrupts(); + p = dup_line_node( lp ); + if( !p ) { enable_interrupts(); return false; } + add_line_node( p ); + if( up ) up->tail = p; + else + { + up = push_undo_atom( UADD, current_addr_, current_addr_ ); + if( !up ) { enable_interrupts(); return false; } + } + modified_ = true; + lp = lp->q_forw; + enable_interrupts(); + } + return true; + } + + +/* 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 */ +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( "Line too long" ); return 0; } + len = p - buf; + /* out of position */ + if( seek_write ) + { + if( fseek( sfp, 0L, SEEK_END ) != 0 ) + { + show_strerror( 0, errno ); + set_error_msg( "Cannot seek temp file" ); + return 0; + } + sfpos = ftell( sfp ); + seek_write = false; + } + if( (int)fwrite( buf, 1, len, sfp ) != len ) /* assert: interrupts disabled */ + { + sfpos = -1; + show_strerror( 0, errno ); + set_error_msg( "Cannot write temp file" ); + return 0; + } + lp = dup_line_node( 0 ); + if( !lp ) return 0; + lp->pos = sfpos; lp->len = len; + add_line_node( lp ); + sfpos += len; /* update file position */ + return p + 1; + } + + +/* return pointer to a line node in the editor buffer */ +line_t * search_line_node( const int addr ) + { + static line_t * lp = &buffer_head; + static int o_addr = 0; + + disable_interrupts(); + if( o_addr < addr ) + { + if( o_addr + last_addr_ >= 2 * addr ) + while( o_addr < addr ) { ++o_addr; lp = lp->q_forw; } + else + { + lp = buffer_head.q_back; o_addr = last_addr_; + while( o_addr > addr ) { --o_addr; lp = lp->q_back; } + } + } + else if( o_addr <= 2 * addr ) + while( o_addr > addr ) { --o_addr; lp = lp->q_back; } + else + { lp = &buffer_head; o_addr = 0; + while( o_addr < addr ) { ++o_addr; lp = lp->q_forw; } } + enable_interrupts(); + return lp; + } + + +/* copy a range of lines to the cut buffer */ +bool yank_lines( const int from, const int to ) + { + line_t * const ep = search_line_node( inc_addr( to ) ); + line_t * bp = search_line_node( from ); + line_t * lp = &yank_buffer_head; + line_t * p; + + clear_yank_buffer(); + while( bp != ep ) + { + disable_interrupts(); + p = dup_line_node( bp ); + if( !p ) { enable_interrupts(); return false; } + insert_node( p, lp ); + bp = bp->q_forw; lp = p; + enable_interrupts(); + } + return true; + } + + +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_current_addr = -1; /* if < 0, undo disabled */ +static int u_last_addr = -1; /* if < 0, undo disabled */ +static bool u_modified = false; + + +void clear_undo_stack( void ) + { + while( u_ptr-- ) + if( ustack[u_ptr].type == UDEL ) + { + line_t * const ep = ustack[u_ptr].tail->q_forw; + line_t * bp = ustack[u_ptr].head; + while( bp != ep ) + { + line_t * const lp = bp->q_forw; + unmark_line_node( bp ); + unmark_unterminated_line( bp ); + free( bp ); + bp = lp; + } + } + u_ptr = 0; + u_current_addr = current_addr_; + u_last_addr = last_addr_; + u_modified = modified_; + } + + +void reset_undo_state( void ) + { + clear_undo_stack(); + u_current_addr = u_last_addr = -1; + u_modified = false; + } + + +/* return pointer to intialized undo node */ +undo_t * push_undo_atom( const int type, const int from, const int to ) + { + disable_interrupts(); + if( !resize_undo_buffer( &ustack, &usize, ( u_ptr + 1 ) * sizeof (undo_t) ) ) + { + show_strerror( 0, errno ); + set_error_msg( "Memory exhausted" ); + if( ustack ) + { + clear_undo_stack(); + free( ustack ); + ustack = 0; + usize = u_ptr = 0; + u_current_addr = u_last_addr = -1; + } + enable_interrupts(); + return 0; + } + enable_interrupts(); + ustack[u_ptr].type = type; + ustack[u_ptr].tail = search_line_node( to ); + ustack[u_ptr].head = search_line_node( from ); + return ustack + u_ptr++; + } + + +/* undo last change to the editor buffer */ +bool undo( const bool isglobal ) + { + int n; + const int o_current_addr = current_addr_; + const int o_last_addr = last_addr_; + const bool o_modified = modified_; + + if( u_ptr <= 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 ) + { + switch( ustack[n].type ) + { + case UADD: link_nodes( ustack[n].head->q_back, ustack[n].tail->q_forw ); + break; + case UDEL: link_nodes( ustack[n].head->q_back, ustack[n].head ); + link_nodes( ustack[n].tail, ustack[n].tail->q_forw ); + break; + case UMOV: + case VMOV: link_nodes( ustack[n-1].head, ustack[n].head->q_forw ); + link_nodes( ustack[n].tail->q_back, ustack[n-1].tail ); + link_nodes( ustack[n].head, ustack[n].tail ); --n; + break; + } + ustack[n].type ^= 1; + } + /* reverse undo stack order */ + for( n = 0; 2 * n < u_ptr - 1; ++n ) + { + undo_t tmp = ustack[n]; + ustack[n] = ustack[u_ptr-1-n]; ustack[u_ptr-1-n] = tmp; + } + if( isglobal ) clear_active_list(); + current_addr_ = u_current_addr; u_current_addr = o_current_addr; + last_addr_ = u_last_addr; u_last_addr = o_last_addr; + modified_ = u_modified; u_modified = o_modified; + enable_interrupts(); + return true; + } diff --git a/carg_parser.c b/carg_parser.c new file mode 100644 index 0000000..6850643 --- /dev/null +++ b/carg_parser.c @@ -0,0 +1,285 @@ +/* Arg_parser - POSIX/GNU command line argument parser. (C version) + Copyright (C) 2006-2017 Antonio Diaz Diaz. + + This library is free software. Redistribution and use in source and + binary forms, with or without modification, are permitted provided + that the following conditions are met: + + 1. Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + + 2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. +*/ + +#include +#include + +#include "carg_parser.h" + + +/* assure at least a minimum size for buffer 'buf' */ +static void * ap_resize_buffer( void * buf, const int min_size ) + { + if( buf ) buf = realloc( buf, min_size ); + else buf = malloc( min_size ); + return buf; + } + + +static char push_back_record( struct Arg_parser * const ap, + const int code, 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) ); + if( !tmp ) return 0; + 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 ); + ++ap->data_size; + return 1; + } + + +static char add_error( struct Arg_parser * const ap, const char * const msg ) + { + const int len = strlen( msg ); + void * tmp = ap_resize_buffer( ap->error, ap->error_size + len + 1 ); + if( !tmp ) return 0; + ap->error = (char *)tmp; + strncpy( ap->error + ap->error_size, msg, len + 1 ); + ap->error_size += len; + return 1; + } + + +static void free_data( struct Arg_parser * const ap ) + { + int i; + for( i = 0; i < ap->data_size; ++i ) free( ap->data[i].argument ); + if( ap->data ) { free( ap->data ); ap->data = 0; } + ap->data_size = 0; + } + + +static char parse_long_option( struct Arg_parser * const ap, + const char * const opt, const char * const arg, + const struct ap_Option options[], + int * const argindp ) + { + unsigned len; + int index = -1, i; + char exact = 0, ambig = 0; + + for( len = 0; opt[len+2] && opt[len+2] != '='; ++len ) ; + + /* 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( strlen( options[i].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 || + options[index].has_arg != options[i].has_arg ) + ambig = 1; /* Second or later nonexact match found */ + } + + if( ambig && !exact ) + { + add_error( ap, "option '" ); add_error( ap, opt ); + add_error( ap, "' is ambiguous" ); + return 1; + } + + if( index < 0 ) /* nothing found */ + { + add_error( ap, "unrecognized option '" ); add_error( ap, opt ); + add_error( ap, "'" ); + return 1; + } + + ++*argindp; + + if( opt[len+2] ) /* '--=' syntax */ + { + if( options[index].has_arg == ap_no ) + { + add_error( ap, "option '--" ); add_error( ap, options[index].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, "' requires an argument" ); + return 1; + } + return push_back_record( ap, options[index].code, &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, "' requires an argument" ); + return 1; + } + ++*argindp; + return push_back_record( ap, options[index].code, arg ); + } + + return push_back_record( ap, options[index].code, "" ); + } + + +static char parse_short_option( struct Arg_parser * const ap, + const char * const opt, const char * const arg, + const struct ap_Option options[], + int * const argindp ) + { + int cind = 1; /* character index in opt */ + + while( cind > 0 ) + { + int index = -1, i; + const unsigned char code = opt[cind]; + char code_str[2]; + code_str[0] = code; code_str[1] = 0; + + if( code != 0 ) + for( i = 0; options[i].code; ++i ) + if( code == options[i].code ) + { index = i; break; } + + if( index < 0 ) + { + add_error( ap, "invalid option -- '" ); add_error( ap, code_str ); + add_error( ap, "'" ); + return 1; + } + + if( opt[++cind] == 0 ) { ++*argindp; cind = 0; } /* opt finished */ + + if( options[index].has_arg != ap_no && cind > 0 && opt[cind] ) + { + if( !push_back_record( ap, code, &opt[cind] ) ) return 0; + ++*argindp; cind = 0; + } + else if( options[index].has_arg == ap_yes ) + { + if( !arg || !arg[0] ) + { + add_error( ap, "option requires an argument -- '" ); + add_error( ap, code_str ); add_error( ap, "'" ); + return 1; + } + ++*argindp; cind = 0; + if( !push_back_record( ap, code, arg ) ) return 0; + } + else if( !push_back_record( ap, code, "" ) ) return 0; + } + return 1; + } + + +char ap_init( struct Arg_parser * const ap, + const int argc, const char * const argv[], + const struct ap_Option options[], const char in_order ) + { + 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; + + ap->data = 0; + ap->error = 0; + ap->data_size = 0; + ap->error_size = 0; + if( argc < 2 || !argv || !options ) return 1; + + while( argind < argc ) + { + const unsigned char ch1 = argv[argind][0]; + const unsigned char ch2 = ch1 ? argv[argind][1] : 0; + + if( ch1 == '-' && ch2 ) /* we found an option */ + { + const char * const opt = argv[argind]; + const char * const arg = ( argind + 1 < argc ) ? argv[argind+1] : 0; + 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_short_option( ap, opt, arg, options, &argind ) ) return 0; + if( ap->error ) break; + } + else + { + if( in_order ) + { if( !push_back_record( ap, 0, argv[argind++] ) ) return 0; } + else + { + void * tmp = ap_resize_buffer( non_options, + ( non_options_size + 1 ) * sizeof *non_options ); + if( !tmp ) return 0; + non_options = (const char **)tmp; + non_options[non_options_size++] = argv[argind++]; + } + } + } + if( ap->error ) free_data( ap ); + else + { + for( i = 0; i < non_options_size; ++i ) + if( !push_back_record( ap, 0, non_options[i] ) ) return 0; + while( argind < argc ) + if( !push_back_record( ap, 0, argv[argind++] ) ) return 0; + } + if( non_options ) free( non_options ); + return 1; + } + + +void ap_free( struct Arg_parser * const ap ) + { + free_data( ap ); + if( ap->error ) { free( ap->error ); ap->error = 0; } + ap->error_size = 0; + } + + +const char * ap_error( const struct Arg_parser * const ap ) + { return ap->error; } + + +int ap_arguments( const struct Arg_parser * const ap ) + { return ap->data_size; } + + +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; + } + + +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 ""; + } diff --git a/carg_parser.h b/carg_parser.h new file mode 100644 index 0000000..c4ce31d --- /dev/null +++ b/carg_parser.h @@ -0,0 +1,93 @@ +/* Arg_parser - POSIX/GNU command line argument parser. (C version) + Copyright (C) 2006-2017 Antonio Diaz Diaz. + + This library is free software. Redistribution and use in source and + binary forms, with or without modification, are permitted provided + that the following conditions are met: + + 1. Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + + 2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. +*/ + +/* Arg_parser reads the arguments in 'argv' and creates a number of + option codes, option arguments and non-option arguments. + + In case of error, 'ap_error' returns a non-null pointer to an error + 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. + + Arg_parser normally makes it appear as if all the option arguments + were specified before all the non-option arguments for the purposes + of parsing, even if the user of your program intermixed option and + non-option arguments. If you want the arguments in the exact order + the user typed them, call 'ap_init' with 'in_order' = true. + + The argument '--' terminates all options; any following arguments are + treated as non-option arguments, even if they begin with a hyphen. + + The syntax for optional option arguments is '-' + (without whitespace), or '--='. +*/ + +#ifdef __cplusplus +extern "C" { +#endif + +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) */ + enum ap_Has_arg has_arg; + }; + + +struct ap_Record + { + int code; + char * argument; + }; + + +struct Arg_parser + { + struct ap_Record * data; + char * error; + int data_size; + int error_size; + }; + + +char ap_init( struct Arg_parser * const ap, + const int argc, const char * const argv[], + const struct ap_Option options[], const char in_order ); + +void ap_free( struct Arg_parser * const ap ); + +const char * ap_error( const struct Arg_parser * const ap ); + + /* The number of arguments parsed (may be different from argc) */ +int ap_arguments( const struct Arg_parser * const ap ); + + /* If ap_code( i ) is 0, ap_argument( i ) is a non-option. + Else ap_argument( i ) is the option's argument (or empty). */ +int ap_code( const struct Arg_parser * const ap, const int i ); + +const char * ap_argument( const struct Arg_parser * const ap, const int i ); + +#ifdef __cplusplus +} +#endif diff --git a/configure b/configure new file mode 100755 index 0000000..4237efb --- /dev/null +++ b/configure @@ -0,0 +1,200 @@ +#! /bin/sh +# configure script for GNU ed - The GNU line editor +# Copyright (C) 2006-2017 Antonio Diaz Diaz. +# +# This configure script is free software: you have unlimited permission +# to copy, distribute and modify it. + +pkgname=ed +pkgversion=1.14.2 +progname=ed +srctrigger=doc/${pkgname}.texi + +# clear some things potentially inherited from environment. +LC_ALL=C +export LC_ALL +srcdir= +prefix=/usr/local +exec_prefix='$(prefix)' +bindir='$(exec_prefix)/bin' +datarootdir='$(prefix)/share' +infodir='$(datarootdir)/info' +mandir='$(datarootdir)/man' +program_prefix= +CC=gcc +CPPFLAGS= +CFLAGS='-Wall -W -O2' +LDFLAGS= + +# checking whether we are using GNU C. +/bin/sh -c "${CC} --version" > /dev/null 2>&1 || + { + CC=cc + CFLAGS=-O2 + } + +# Loop over all args +args= +no_create= +while [ $# != 0 ] ; do + + # Get the first arg, and shuffle + option=$1 ; arg2=no + shift + + # Add the argument quoted to args + args="${args} \"${option}\"" + + # Split out the argument for options that take them + case ${option} in + *=*) optarg=`echo ${option} | sed -e 's,^[^=]*=,,;s,/$,,'` ;; + esac + + # Process the options + case ${option} in + --help | -h) + echo "Usage: $0 [OPTION]... [VAR=VALUE]..." + echo + echo "To assign makefile variables (e.g., CC, CFLAGS...), specify them as" + echo "arguments to configure in the form VAR=VALUE." + echo + echo "Options: [defaults in brackets]" + echo " -h, --help display this help and exit" + echo " -V, --version output version information and exit" + echo " --srcdir=DIR find the sources in DIR [. or ..]" + echo " --prefix=DIR install into DIR [${prefix}]" + echo " --exec-prefix=DIR base directory for arch-dependent files [${exec_prefix}]" + echo " --bindir=DIR user executables directory [${bindir}]" + echo " --datarootdir=DIR base directory for doc and data [${datarootdir}]" + echo " --infodir=DIR info files directory [${infodir}]" + echo " --mandir=DIR man pages directory [${mandir}]" + echo " --program-prefix=NAME install program and documentation prefixed with NAME" + echo " CC=COMPILER C compiler to use [${CC}]" + echo " CPPFLAGS=OPTIONS command line options for the preprocessor [${CPPFLAGS}]" + echo " CFLAGS=OPTIONS command line options for the C compiler [${CFLAGS}]" + echo " LDFLAGS=OPTIONS command line options for the linker [${LDFLAGS}]" + echo + exit 0 ;; + --version | -V) + echo "Configure script for GNU ${pkgname} version ${pkgversion}" + exit 0 ;; + --srcdir) srcdir=$1 ; arg2=yes ;; + --prefix) prefix=$1 ; arg2=yes ;; + --exec-prefix) exec_prefix=$1 ; arg2=yes ;; + --bindir) bindir=$1 ; arg2=yes ;; + --datarootdir) datarootdir=$1 ; arg2=yes ;; + --infodir) infodir=$1 ; arg2=yes ;; + --mandir) mandir=$1 ; arg2=yes ;; + --program-prefix) program_prefix=$1 ; arg2=yes ;; + + --srcdir=*) srcdir=${optarg} ;; + --prefix=*) prefix=${optarg} ;; + --exec-prefix=*) exec_prefix=${optarg} ;; + --bindir=*) bindir=${optarg} ;; + --datarootdir=*) datarootdir=${optarg} ;; + --infodir=*) infodir=${optarg} ;; + --mandir=*) mandir=${optarg} ;; + --program-prefix=*) program_prefix=${optarg} ;; + --no-create) no_create=yes ;; + + CC=*) CC=${optarg} ;; + CPPFLAGS=*) CPPFLAGS=${optarg} ;; + CFLAGS=*) CFLAGS=${optarg} ;; + LDFLAGS=*) LDFLAGS=${optarg} ;; + + --*) + echo "configure: WARNING: unrecognized option: '${option}'" 1>&2 ;; + *=* | *-*-*) ;; + *) + echo "configure: unrecognized option: '${option}'" 1>&2 + echo "Try 'configure --help' for more information." 1>&2 + exit 1 ;; + esac + + # Check if the option took a separate argument + if [ "${arg2}" = yes ] ; then + if [ $# != 0 ] ; then args="${args} \"$1\"" ; shift + else echo "configure: Missing argument to '${option}'" 1>&2 + exit 1 + fi + fi +done + +# Find the source files, if location was not specified. +srcdirtext= +if [ -z "${srcdir}" ] ; then + srcdirtext="or . or .." ; srcdir=. + if [ ! -r "${srcdir}/${srctrigger}" ] ; then srcdir=.. ; fi + if [ ! -r "${srcdir}/${srctrigger}" ] ; then + ## the sed command below emulates the dirname command + srcdir=`echo $0 | sed -e 's,[^/]*$,,;s,/$,,;s,^$,.,'` + fi +fi + +if [ ! -r "${srcdir}/${srctrigger}" ] ; then + echo "configure: Can't find sources in ${srcdir} ${srcdirtext}" 1>&2 + echo "configure: (At least ${srctrigger} is missing)." 1>&2 + exit 1 +fi + +# Set srcdir to . if that's what it is. +if [ "`pwd`" = "`cd "${srcdir}" ; pwd`" ] ; then srcdir=. ; fi + +echo +if [ -z "${no_create}" ] ; then + echo "creating config.status" + rm -f config.status + cat > config.status << EOF +#! /bin/sh +# This file was generated automatically by configure. Don't edit. +# Run this file to recreate the current configuration. +# +# This script is free software: you have unlimited permission +# to copy, distribute and modify it. + +exec /bin/sh $0 ${args} --no-create +EOF + chmod +x config.status +fi + +echo "creating Makefile" +echo "VPATH = ${srcdir}" +echo "prefix = ${prefix}" +echo "exec_prefix = ${exec_prefix}" +echo "bindir = ${bindir}" +echo "datarootdir = ${datarootdir}" +echo "infodir = ${infodir}" +echo "mandir = ${mandir}" +echo "program_prefix = ${program_prefix}" +echo "CC = ${CC}" +echo "CPPFLAGS = ${CPPFLAGS}" +echo "CFLAGS = ${CFLAGS}" +echo "LDFLAGS = ${LDFLAGS}" +rm -f Makefile +cat > Makefile << EOF +# Makefile for GNU ed - The GNU line editor +# Copyright (C) 2006-2017 Antonio Diaz Diaz. +# This file was generated automatically by configure. Don't edit. +# +# This Makefile is free software: you have unlimited permission +# to copy, distribute and modify it. + +pkgname = ${pkgname} +pkgversion = ${pkgversion} +progname = ${progname} +VPATH = ${srcdir} +prefix = ${prefix} +exec_prefix = ${exec_prefix} +bindir = ${bindir} +datarootdir = ${datarootdir} +infodir = ${infodir} +mandir = ${mandir} +program_prefix = ${program_prefix} +CC = ${CC} +CPPFLAGS = ${CPPFLAGS} +CFLAGS = ${CFLAGS} +LDFLAGS = ${LDFLAGS} +EOF +cat "${srcdir}/Makefile.in" >> Makefile + +echo "OK. Now you can run make." diff --git a/doc/ed.1 b/doc/ed.1 new file mode 100644 index 0000000..66e1331 --- /dev/null +++ b/doc/ed.1 @@ -0,0 +1,68 @@ +.\" DO NOT MODIFY THIS FILE! It was generated by help2man 1.46.1. +.TH ED "1" "February 2017" "ed 1.14.2" "User Commands" +.SH NAME +ed \- line-oriented text editor +.SH SYNOPSIS +.B ed +[\fI\,options\/\fR] [\fI\,file\/\fR] +.SH DESCRIPTION +GNU Ed \- The GNU line editor. +.SH OPTIONS +.TP +\fB\-h\fR, \fB\-\-help\fR +display this help and exit +.TP +\fB\-V\fR, \fB\-\-version\fR +output version information and exit +.TP +\fB\-G\fR, \fB\-\-traditional\fR +run in compatibility mode +.TP +\fB\-l\fR, \fB\-\-loose\-exit\-status\fR +exit with 0 status even if a command fails +.TP +\fB\-p\fR, \fB\-\-prompt\fR=\fI\,STRING\/\fR +use STRING as an interactive prompt +.TP +\fB\-r\fR, \fB\-\-restricted\fR +run in restricted mode +.TP +\fB\-s\fR, \fB\-\-quiet\fR, \fB\-\-silent\fR +suppress diagnostics, byte counts and '!' prompt +.TP +\fB\-v\fR, \fB\-\-verbose\fR +be verbose; equivalent to the 'H' command +.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 +caused ed to panic. +.SH "REPORTING BUGS" +Report bugs to bug\-ed@gnu.org +.br +Ed home page: http://www.gnu.org/software/ed/ed.html +.br +General help using GNU software: http://www.gnu.org/gethelp +.SH COPYRIGHT +Copyright \(co 1994 Andrew L. Moore. +.br +Copyright \(co 2017 Antonio Diaz Diaz. +License GPLv3+: GNU GPL version 3 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. +.SH "SEE ALSO" +The full documentation for +.B ed +is maintained as a Texinfo manual. If the +.B info +and +.B ed +programs are properly installed at your site, the command +.IP +.B info ed +.PP +should give you access to the complete manual. diff --git a/doc/ed.info b/doc/ed.info new file mode 100644 index 0000000..7a5575f --- /dev/null +++ b/doc/ed.info @@ -0,0 +1,1497 @@ +This is ed.info, produced by makeinfo version 4.13+ from ed.texi. + +INFO-DIR-SECTION Basics +START-INFO-DIR-ENTRY +* Ed: (ed). The GNU line editor +END-INFO-DIR-ENTRY + + Copyright (C) 1993, 1994, 2006-2017 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 later version published by the Free Software Foundation; with no +Invariant Sections, no Front-Cover Texts, and no Back-Cover Texts. + + +File: ed.info, Node: Top, Next: Overview, Up: (dir) + +The GNU ed line editor +********************** + +This manual is for GNU ed (version 1.14.2, 22 February 2017). + + + GNU ed is a line-oriented text editor. It is used to create, display, +modify and otherwise manipulate text files, both interactively and via +shell scripts. A restricted version of ed, red, can only edit files in +the current directory and cannot execute shell commands. Ed is the +"standard" text editor in the sense that it is the original editor for +Unix, and thus widely available. For most purposes, however, it is +superseded by full-screen editors such as GNU Emacs or GNU Moe. + +* Menu: + +* Overview:: Overview of the 'ed' command +* Introduction to line editing:: Getting started with GNU 'ed' +* Invoking ed:: Command line interface +* Line addressing:: Specifying lines/ranges in the buffer +* Regular expressions:: Patterns for selecting text +* Commands:: Commands recognized by GNU 'ed' +* 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-2017 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 later version published by the Free Software Foundation; with no +Invariant Sections, no Front-Cover Texts, and no Back-Cover Texts. + + +File: ed.info, Node: Overview, Next: Introduction to line editing, Prev: Top, Up: Top + +1 Overview +********** + +'ed' is a line-oriented text editor. It is used to create, display, +modify and otherwise manipulate text files. 'red' is a restricted 'ed': +it can only edit files in the current directory and cannot execute +shell commands. + + 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. + + 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 standard input and executed to manipulate the contents of the +editor buffer. A typical command might look like: + + ,s/OLD/NEW/g + + which replaces all occurences of the string OLD with NEW. + + When an input command, such as 'a' (append), 'i' (insert) or 'c' +(change), is given, 'ed' enters input mode. This is the primary means +of adding text to a file. In this mode, no commands are available; +instead, the standard input is written directly to the editor buffer. A +"line" consists of the text up to and including a character. +Input mode is terminated by entering a single period ('.') on a line. + + All 'ed' commands operate on whole lines or ranges of lines; e.g., +the 'd' command deletes lines; the 'm' command moves 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 's' +command is applied to whole lines at a time. + + In general, '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: + + [ADDRESS[,ADDRESS]]COMMAND[PARAMETERS] + + The ADDRESSes 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. + + +File: ed.info, Node: Introduction to line editing, Next: Invoking ed, Prev: Overview, Up: Top + +2 Introduction to line editing +****************************** + +'ed' was created, along with the Unix operating system, by Ken Thompson +and Dennis Ritchie. It is the refinement of its more complex, +programmable predecessor, 'QED', to which Thompson and Ritchie had +already added pattern matching capabilities (*note Regular +expressions::). + + For the purposes of this tutorial, a working knowledge of the Unix +shell 'sh' and the Unix file system is recommended, since 'ed' is +designed to interact closely with them. (*Note GNU bash manual: +(bash)Top, for details about bash). + + The principal difference between line editors and display editors is +that display editors provide instant feedback to user commands, whereas +line editors require sometimes lengthy input before any effects are +seen. The advantage of instant feedback, of course, is that if a mistake +is made, it can be corrected immediately, before more damage is done. +Editing in 'ed' requires more strategy and forethought; but if you are +up to the task, it can be quite efficient. + + Much of the 'ed' command syntax is shared with other Unix utilities. + + As with the shell, (the carriage-return key) enters a line +of input. So when we speak of "entering" a command or some text in +'ed', is implied at the end of each line. Prior to typing +, corrections to the line may be made by typing either + to erase characters backwards, or -u (i.e., hold +the CONTROL key and type u) to erase the whole line. + + When 'ed' first opens, it expects to be told what to do but doesn't +prompt us like the shell. So let's begin by telling 'ed' to do so with +the

("prompt") command: + + $ ed + P + * + + By default, 'ed' uses asterisk ('*') as command prompt to avoid +confusion with the shell command prompt ('$'). + + We can run Unix shell ('sh') commands from inside 'ed' by prefixing +them with (exclamation mark, aka "bang"). For example: + + *!date + Mon Jun 26 10:08:41 PDT 2006 + ! + *!for s in hello world; do echo $s; done + hello + world + ! + * + + So far, this is no different from running commands in the Unix shell. +But let's say we want to edit the output of a command, or save it to a +file. First we must capture the command output to a temporary location +called a "buffer" where 'ed' can access it. This is done with 'ed''s + command (mnemonic: "read"): + + *r !cal -m + 137 + * + + Here 'ed' is telling us that it has just read 137 characters into +the editor buffer - i.e., the output of the 'cal' command, which prints +a simple ASCII calendar. To display the buffer contents we issue the +

("print") command (not to be confused with the prompt command, +which is uppercase!). To indicate the range of lines in the buffer that +should be printed, we prefix the command with <,> (comma) which is +shorthand for "the whole buffer": + + *,p + June 2006 + Mo Tu We Th Fr Sa Su + 1 2 3 4 + 5 6 7 8 9 10 11 + 12 13 14 15 16 17 18 + 19 20 21 22 23 24 25 + 26 27 28 29 30 + + * + + Now let's write the buffer contents to a file named 'junk' with the + ("write") command: + + *w junk + 137 + * + + Need we say? It's good practice to frequently write the buffer +contents, since unwritten changes to the buffer will be lost when we +exit 'ed'. + + The sample sessions below illustrate some basic concepts of line +editing with 'ed'. We begin by creating a file, 'sonnet', with some +help from Shakespeare. As with the shell, all input to 'ed' must be +followed by a character. Commands beginning with '#' are +taken as comments and ignored. Input mode lines that begin with '#' are +just more input. + + $ ed + # The 'a' command is for appending text to the editor buffer. + a + No more be grieved at that which thou hast done. + Roses have thorns, and filvers foutians mud. + Clouds and eclipses stain both moon and sun, + And loathsome canker lives in sweetest bud. + . + # Entering a single period on a line returns 'ed' to command mode. + # Now write the buffer to the file 'sonnet' and quit: + w sonnet + 183 + # 'ed' reports the number of characters written. + q + $ ls -l + total 2 + -rw-rw-r-- 1 alm 183 Nov 10 01:16 sonnet + $ + + In the next example, some typos are corrected in the file 'sonnet'. + + $ ed sonnet + 183 + # Begin by printing the buffer to the terminal with the 'p' command. + # The ',' means "all lines". + ,p + No more be grieved at that which thou hast done. + Roses have thorns, and filvers foutians mud. + Clouds and eclipses stain both moon and sun, + And loathsome canker lives in sweetest bud. + # Select line 2 for editing. + 2 + Roses have thorns, and filvers foutians mud. + # Use the substitute command, 's', to replace 'filvers' with 'silver', + # and print the result. + s/filvers/silver/p + Roses have thorns, and silver foutians mud. + # And correct the spelling of 'fountains'. + s/utia/untai/p + Roses have thorns, and silver fountains mud. + w sonnet + 183 + q + $ + + Since 'ed' is line-oriented, we have to tell it which line, or range +of lines we want to edit. In the above example, we do this by +specifying the line's number, or sequence in the buffer. Alternatively, +we could have specified a unique string in the line, e.g., '/filvers/', +where the '/'s delimit the string in question. Subsequent commands +affect only the selected line, a.k.a. the "current" line. Portions of +that line are then replaced with the substitute command, whose syntax +is 's/OLD/NEW/'. + + Although 'ed' accepts only one command per line, the print command +'p' is an exception, and may be appended to the end of most commands. + + In the next example, a title is added to our sonnet. + + $ ed sonnet + 183 + a + Sonnet #50 + . + ,p + No more be grieved at that which thou hast done. + Roses have thorns, and silver fountains mud. + Clouds and eclipses stain both moon and sun, + And loathsome canker lives in sweetest bud. + Sonnet #50 + # The title got appended to the end; we should have used '0a' + # to append "before the first line". + # Move the title to its proper place. + 5m0p + Sonnet #50 + # The title is now the first line, and the current address has been + # set to the address of this line as well. + ,p + Sonnet #50 + No more be grieved at that which thou hast done. + Roses have thorns, and silver fountains mud. + Clouds and eclipses stain both moon and sun, + And loathsome canker lives in sweetest bud. + wq sonnet + 195 + $ + + When 'ed' opens a file, the current address is initially set to the +address of the last line of that file. Similarly, the move command 'm' +sets the current address to the address of the last line moved. + + Related programs or routines are 'vi (1)', 'sed (1)', 'regex (3)', +'sh (1)'. Relevant documents are: + + Unix User's Manual Supplementary Documents: 12 -- 13 + + B. W. Kernighan and P. J. Plauger: "Software Tools in Pascal", + Addison-Wesley, 1981. + + +File: ed.info, Node: Invoking ed, Next: Line addressing, Prev: Introduction to line editing, Up: Top + +3 Invoking ed +************* + +The format for running 'ed' is: + + ed [OPTIONS] [FILE] + red [OPTIONS] [FILE] + + FILE specifies the name of a file to read. If FILE is prefixed with +a bang (!), then it is interpreted as a shell command. In this case, +what is read is the standard output of FILE executed via 'sh (1)'. To +read a file whose name begins with a bang, prefix the name with a +backslash ('\'). The default filename is set to FILE only if it is not +prefixed with a bang. + + 'ed' supports the following options: + +'-h' +'--help' + Print an informative help message describing the options and exit. + +'-V' +'--version' + Print the version number of 'ed' on the standard output and exit. + +'-G' +'--traditional' + Forces backwards compatibility. This affects the behavior of the + 'ed' commands 'G', 'V', 'f', 'l', 'm', 't' and '!!'. If the + default behavior of these commands does not seem familiar, then + try invoking 'ed' with this switch. + +'-l' +'--loose-exit-status' + Don't exit with bad status if a command happens to "fail" (for + example if a substitution command finds nothing to replace). This + can be useful when 'ed' is invoked as the editor for crontab. + +'-p STRING' +'--prompt=STRING' + Specifies a command prompt. This may be toggled on and off with the + 'P' command. + +'-r' +'--restricted' + Run in restricted mode. This mode disables editing of files out of + the current directory and execution of shell commands. + +'-s' +'--quiet' +'--silent' + Suppresses diagnostics, the printing of byte counts by 'e', 'E', + 'r' and 'w' commands, and the '!' prompt after a '!' command. This + option may be useful if 'ed''s standard input is from a script. + +'-v' +'--verbose' + Verbose mode; prints error explanations. This may be toggled on + and off with the 'H' command. + + + Exit status: 0 if no errors occurred; otherwise >0. + + +File: ed.info, Node: Line addressing, Next: Regular expressions, Prev: Invoking ed, Up: Top + +4 Line addressing +***************** + +An address represents the number of a line in the buffer. 'ed' +maintains a "current address" which is typically supplied to commands +as the default address when none is specified. When a file is first +read, the current address is set to the address of the last line of the +file. In general, the current address is set to the address of the last +line affected by a command. + + One exception to the rule that addresses represent line numbers is +the address '0' (zero). This means "before the first line", and is +valid wherever it makes sense. + + An address range is two addresses separated either by a comma (',') +or a semicolon (';'). In a semicolon-delimited range, the current +address ('.') is set to the first address before the second address is +calculated. This feature can be used to set the starting line for +searches. The value of the first address in a range cannot exceed the +value of the second. + + Addresses can be omitted on either side of the comma or semicolon +separator. If only the first address is given in a range, then the +second address is set to the given address. If only the second address +is given, the resulting address pairs are '1,addr' and '.;addr' +respectively. If a N-tuple of addresses is given where N > 2, then the +corresponding range is determined by the last two addresses in the +N-tuple. If only one address is expected, then the last address is +used. It is an error to give any number of addresses to a command that +requires zero addresses. + + A line address is constructed as follows: + +'.' + The current line (address) in the buffer. + +'$' + The last line in the buffer. + +'N' + The Nth line in the buffer, where N is a number in the range '0,$'. + +'+N' + The Nth next line, where N is a non-negative number. + +'-N' + The Nth previous line, where N is a non-negative number. + +'+' + The next line. This is equivalent to '+1' and may be repeated with + cumulative effect. + +'-' + The previous line. This is equivalent to '-1' and may be repeated + with cumulative effect. + +',' + The first through last lines in the buffer. This is equivalent to + the address range '1,$'. + +';' + The current through last lines in the buffer. This is equivalent + to the address range '.;$'. + +'/RE/' + 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. A null RE '//' repeats the last search. + +'?RE?' + 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. A null RE '??' repeats the last search. + +''x' + The apostrophe-x character pair addresses the line previously + marked by a 'k' (mark) command, where 'x' is a lower case letter + from the portable character set. + + + Addresses can be followed by one or more address offsets, optionally +separated by whitespace. Offsets are constructed as follows: + + * '+' or '-' followed by a number adds or subtracts the indicated + number of lines to or from the address. + + * '+' or '-' not followed by a number adds or subtracts 1 to or from + the address. + + * A number adds the indicated number of lines to the address. + + + 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. + + +File: ed.info, Node: Regular expressions, Next: Commands, Prev: Line addressing, Up: Top + +5 Regular expressions +********************* + +Regular expressions are patterns used in selecting text. For example, +the 'ed' command + + g/STRING/ + +prints all lines containing STRING. Regular expressions are also used +by the 's' command for selecting old text to be replaced with new text. + + In addition to a 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 longest match is the one selected. + + The following symbols are used in constructing regular expressions: + +'C' + Any character C not listed below, including '{', '}', '(', ')', + '<' and '>', matches itself. + +'\C' + Any backslash-escaped character C, other than '{', '}', '(', ')', + '<', '>', 'b', 'B', 'w', 'W', '+' and '?', matches itself. + +'.' + Matches any single character. + +'[CHAR-CLASS]' + Matches any single character in CHAR-CLASS. To include a ']' in + CHAR-CLASS, it must be the first character. A range of characters + may be specified by separating the end characters of the range + with a '-', e.g., 'a-z' specifies the lower case characters. The + following literal expressions can also be used in CHAR-CLASS to + specify sets of characters: + + [:alnum:] [:cntrl:] [:lower:] [:space:] + [:alpha:] [:digit:] [:print:] [:upper:] + [:blank:] [:graph:] [:punct:] [:xdigit:] + + If '-' appears as the first or last character of CHAR-CLASS, then + it matches itself. All other characters in CHAR-CLASS match + themselves. + + Patterns in CHAR-CLASS of the form: + [.COL-ELM.] + [=COL-ELM=] + + where COL-ELM is a "collating element" are interpreted according + to 'locale (5)'. See 'regex (3)' for an explanation of these + constructs. + +'[^CHAR-CLASS]' + Matches any single character, other than newline, not in + CHAR-CLASS. CHAR-CLASS is defined as above. + +'^' + If '^' is the first character of a regular expression, then it + anchors the regular expression to the beginning of a line. + Otherwise, it matches itself. + +'$' + If '$' is the last character of a regular expression, it anchors + the regular expression to the end of a line. Otherwise, it matches + itself. + +'\(RE\)' + Defines a (possibly null) 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 the string 'abcabc', but not 'abcadc'. Subexpressions are + ordered relative to their left delimiter. + +'*' + Matches the single character regular expression or subexpression + immediately preceding it zero or more times. If '*' is the first + character 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 left-most match. + +'\{N,M\}' +'\{N,\}' +'\{N\}' + Matches the single character regular expression or subexpression + immediately preceding it at least N and at most M times. If M is + omitted, then it matches at least N times. If the comma is also + omitted, then it matches exactly N times. If any of these forms + occurs first in a regular expression or subexpression, then it is + interpreted literally (i.e., the regular expression '\{2\}' + matches the string '{2}', and so on). + +'\<' +'\>' + Anchors the single character regular expression or subexpression + immediately following it to the beginning (in the case of '\<') or + ending (in the case of '\>') of a "word", i.e., in ASCII, a + maximal string of alphanumeric characters, including the + underscore (_). + + + The following extended operators are preceded by a backslash '\' to +distinguish them from traditional 'ed' syntax. + +'\`' +'\'' + Unconditionally matches the beginning '\`' or ending '\'' of a + line. + +'\?' + Optionally matches the single character regular expression or + subexpression immediately preceding it. For example, the regular + expression 'a[bd]\?c' matches the strings 'abc', 'adc' and 'ac'. + If '\?' occurs at the beginning of a regular expressions or + subexpression, then it matches a literal '?'. + +'\+' + Matches the single character regular expression or subexpression + immediately preceding it one or more times. So the regular + expression 'a+' is shorthand for 'aa*'. If '\+' occurs at the + beginning of a regular expression or subexpression, then it + matches a literal '+'. + +'\b' + Matches the beginning or ending (null 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. + +'\w' + Matches any character in a word. + +'\W' + Matches any character not in a word. + + + +File: ed.info, Node: Commands, Next: Limitations, Prev: Regular expressions, Up: Top + +6 Commands +********** + +All '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 ('\'). + + In general, at most one command is allowed per line. However, most +commands accept a print suffix, which is any of 'p' (print), 'l' +(list), or 'n' (enumerate), to print the last line affected by the +command. It is not portable to give more than one print suffix, but +'ed' allows any combination of non-repeated print suffixes and combines +their effects. + + An interrupt (typically ) has the effect of aborting the +current command and returning the editor to command mode. + + 'ed' recognizes the following commands. The commands are shown +together with the default address or address range supplied if none is +specified (in parenthesis). + +'(.)a' + Appends text to the buffer after the addressed line. The address + '0' (zero) is valid for this command; it places the entered text at + the beginning of the buffer. Text is entered in input mode. The + current address is set to the address of the last line entered or, + if there were none, to the addressed line. + +'(.,.)c' + Changes lines in the buffer. The addressed lines are deleted from + the buffer, and text is inserted in their place. Text is entered + in input mode. The current address is set to the address of the + last line entered or, if there were none, to the new address of + the line after the last line deleted; if the lines deleted were + originally at the end of the buffer, the current address is set to + the address of the new last line; if no lines remain in the + buffer, the current address is set to zero. + +'(.,.)d' + Deletes the addressed lines from the buffer. The current address + is set to the new address of the line after the last line deleted; + if the lines deleted were originally at the end of the buffer, the + current address is set to the address of the new last line; if no + lines remain in the buffer, the current address is set to zero. + +'e FILE' + Edits FILE, and sets the default filename. If FILE is not + specified, then the default filename is used. Any lines in the + buffer are deleted before the new file is read. The current + address is set to the address of the last line in the buffer. + + If FILE is prefixed with a bang (!), then it is interpreted as a + shell command whose output is to be read, (*note shell escape + command:: '!' below). In this case the default filename is + unchanged. + + A warning is printed if any changes have been made in the buffer + since the last 'w' command that wrote the entire buffer to a file. + +'E FILE' + Edits FILE unconditionally. This is similar to the 'e' command, + except that unwritten changes are discarded without warning. + +'f FILE' + Sets the default filename to FILE. If FILE is not specified, then + the default unescaped filename is printed. + +'(1,$)g/RE/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 first command of COMMAND-LIST must appear on the same line as + the 'g' command. All lines of a multi-line COMMAND-LIST except the + last line must be terminated with a backslash ('\'). Any commands + are allowed, except for 'g', 'G', 'v', and 'V'. The '.' + terminating the input mode of commands 'a', 'c', and 'i' can be + omitted if it would be the last line of COMMAND-LIST. By default, + a newline alone in COMMAND-LIST is equivalent to a 'p' command. If + 'ed' is invoked with the command-line option '-G', then a newline + in COMMAND-LIST is equivalent to a '.+1p' command. + +'(1,$)G/RE/' + 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. + + 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. + +'h' + Prints an explanation of the last error. + +'H' + Toggles the printing of error explanations. By default, + explanations are not printed. It is recommended that ed scripts + begin with this command to aid in debugging. + +'(.)i' + Inserts text in the buffer before the addressed line. The address + '0' (zero) is valid for this command; it is equivalent to address + '1'. Text is entered in input mode. The current address is set to + the address of the last line entered or, if there were none, to the + addressed line. + +'(.,.+1)j' + Joins the addressed lines, replacing them by a single line + containing their joined text. If only one address is given, this + command does nothing. If lines are joined, the current address is + set to the address of the joined line. Else, the current address + is unchanged. + +'(.)kx' + Marks a line with a lower case letter 'x'. The line can then be + addressed as ''x' (i.e., a single quote followed by 'x') in + subsequent commands. The mark is not cleared until the line is + deleted or otherwise modified. The current address is unchanged. + +'(.,.)l' + List command. Prints the addressed lines unambiguously. The end of + each line is marked with a '$', and every '$' character within the + text is printed with a preceding backslash. Special characters are + printed as escape sequences. The current address is set to the + address of the last line printed. + +'(.,.)m(.)' + Moves lines in the buffer. The addressed lines are moved to after + the right-hand destination address. The destination address '0' + (zero) is valid for this command; it moves the addressed lines to + the beginning of the buffer. It is an error if the destination + address falls within the range of moved lines. The current address + is set to the new address of the last line moved. + +'(.,.)n' + Number command. Prints the addressed lines, preceding each line by + its line number and a . The current address is set to the + address of the last line printed. + +'(.,.)p' + Prints the addressed lines. The current address is set to the + address of the last line printed. + +'P' + Toggles the command prompt on and off. Unless a prompt is + specified with command-line option '-p', the command prompt is by + default turned off. + +'q' + Quits 'ed'. A warning is printed if any changes have been made in + the buffer since the last 'w' command that wrote the entire buffer + to a file. + +'Q' + Quits 'ed' unconditionally. This is similar to the 'q' command, + except that unwritten changes are discarded without warning. + +'($)r FILE' + Reads FILE and appends it after the addressed line. If FILE is not + specified, then the default filename is used. If there is no + default filename prior to the command, then the default filename + is set to FILE. Otherwise, the default filename is unchanged. The + address '0' (zero) is valid for this command; it reads the file at + the beginning of the buffer. The current address is set to the + address of the last line read or, if there were none, to the + addressed line. + + If FILE is prefixed with a bang (!), then it is interpreted as a + shell 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. + + 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 + becomes 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, except if the 's' command is part of a 'g' + or 'v' COMMAND-LIST, because in this case the meaning of the + escaped newline becomes ambiguous. 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 regular expression of the last search to be + used instead of that 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 lines are copied at the beginning of the buffer. The + current address is set to the address of the last line copied. + +'u' + Undoes the effect of the last command that modified anything in the + buffer and restores the current address to what it was before the + command. The global commands 'g', 'G', 'v', and 'V' are treated as + a single command by undo. 'u' is its own inverse. + +'(1,$)v/RE/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/' + This is similar to the 'G' command except that it interactively + edits the addressed lines not matching the regular expression RE. + +'(1,$)w FILE' + Writes the addressed lines to FILE. Any previous contents of FILE + is lost without warning. If there is no default filename, then the + default filename is set to FILE, otherwise it is unchanged. If no + filename is specified, then the default filename is used. The + current address is unchanged. + + If FILE is prefixed with a bang (!), then it is interpreted as a + shell command and the addressed lines are written to its standard + input, (*note shell escape command:: '!' below). In this case the + default filename is unchanged. Writing the buffer to a shell + command does not prevent the warning to the user if an attempt is + made to overwrite or discard the buffer via the 'e' or 'q' + commands. + +'(1,$)wq FILE' + Writes the addressed lines to FILE, and then executes a 'q' + command. + +'(1,$)W FILE' + Appends the addressed lines to the end of FILE. This is similar to + the 'w' command, except that the previous contents of file is not + clobbered. The current address is unchanged. + +'(.)x' + Copies (puts) the contents of the cut buffer to after the addressed + line. The current address is set to the address of the last line + copied. + +'(.,.)y' + Copies (yanks) the addressed lines to the cut buffer. The cut + buffer is overwritten by subsequent 'c', 'd', 'j', 's', or 'y' + commands. The current address is unchanged. + +'(.+1)zN' + Scrolls N lines at a time starting at addressed line, and sets + window size to N. If N is not specified, then the current window + size is used. Window size defaults to screen size minus two lines, + or to 22 if screen size can't be determined. The current address + is set to the address of the last line printed. + +'!COMMAND' + 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. + +'(.,.)#' + Begins a comment; the rest of the line, up to a newline, is + ignored. If a line address followed by a semicolon is given, then + the current address is set to that address. Otherwise, the current + address is unchanged. + +'($)=' + Prints the line number of the addressed line. The current address + is unchanged. + +'(.+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. + + + +File: ed.info, Node: Limitations, Next: Diagnostics, Prev: Commands, Up: Top + +7 Limitations +************* + +If the terminal hangs up, 'ed' attempts to write the buffer to the file +'ed.hup' or, if this fails, to '$HOME/ed.hup'. + + 'ed' processes FILE arguments for backslash escapes, i.e., in a +filename, any character preceded by a backslash ('\') is interpreted +literally. + + If a text (non-binary) file is not terminated by a newline character, +then 'ed' appends one on reading/writing it. In the case of a binary +file, 'ed' does not append a newline on reading/writing. + + Per line overhead: 2 'pointer's, 1 'long int', and 1 'int'. + + +File: ed.info, Node: Diagnostics, Next: Problems, Prev: Limitations, Up: Top + +8 Diagnostics +************* + +When an error occurs, if 'ed''s input is from a regular file or here +document, then it exits, otherwise it prints a '?' and returns to +command mode. An explanation of the last error can be printed with the +'h' (help) command. + + If the 'u' (undo) command occurs in a global command list, then the +command list is executed only once. + + Attempting to quit 'ed' or edit another file before writing a +modified buffer results in an error. If the command is entered a second +time, it 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 +**************** + +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 one will ever know about them and they will remain unfixed +for all eternity, if not longer. + + If you find a bug in 'ed', please send electronic mail to +. Include the version number, which you can find by +running 'ed --version'. + + +File: ed.info, Node: GNU Free Documentation License, Prev: Problems, Up: Top + +10 GNU Free Documentation License +********************************* + + Version 1.3, 3 November 2008 + + Copyright (C) 2000, 2001, 2002, 2007, 2008 Free Software Foundation, Inc. + 'http://fsf.org/' + + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + 0. PREAMBLE + + The purpose of this License is to make a manual, textbook, or other + functional and useful document "free" in the sense of freedom: to + assure everyone the effective freedom to copy and redistribute it, + with or without modifying it, either commercially or + noncommercially. Secondarily, this License preserves for the + author and publisher a way to get credit for their work, while not + being considered responsible for modifications made by others. + + This License is a kind of "copyleft", which means that derivative + works of the document must themselves be free in the same sense. + It complements the GNU General Public License, which is a copyleft + license designed for free software. + + We have designed this License in order to use it for manuals for + free software, because free software needs free documentation: a + free program should come with manuals providing the same freedoms + that the software does. But this License is not limited to + software manuals; it can be used for any textual work, regardless + of subject matter or whether it is published as a printed book. + We recommend this License principally for works whose purpose is + instruction or reference. + + 1. APPLICABILITY AND DEFINITIONS + + This License applies to any manual or other work, in any medium, + that contains a notice placed by the copyright holder saying it + can be distributed under the terms of this License. Such a notice + grants a world-wide, royalty-free license, unlimited in duration, + to use that work under the conditions stated herein. The + "Document", below, refers to any such manual or work. Any member + of the public is a licensee, and is addressed as "you". You + accept the license if you copy, modify or distribute the work in a + way requiring permission under copyright law. + + A "Modified Version" of the Document means any work containing the + Document or a portion of it, either copied verbatim, or with + modifications and/or translated into another language. + + A "Secondary Section" is a named appendix or a front-matter section + of the Document that deals exclusively with the relationship of the + publishers or authors of the Document to the Document's overall + subject (or to related matters) and contains nothing that could + fall directly within that overall subject. (Thus, if the Document + is in part a textbook of mathematics, a Secondary Section may not + explain any mathematics.) The relationship could be a matter of + historical connection with the subject or with related matters, or + of legal, commercial, philosophical, ethical or political position + regarding them. + + The "Invariant Sections" are certain Secondary Sections whose + titles are designated, as being those of Invariant Sections, in + the notice that says that the Document is released under this + License. If a section does not fit the above definition of + Secondary then it is not allowed to be designated as Invariant. + The Document may contain zero Invariant Sections. If the Document + does not identify any Invariant Sections then there are none. + + The "Cover Texts" are certain short passages of text that are + listed, as Front-Cover Texts or Back-Cover Texts, in the notice + that says that the Document is released under this License. A + Front-Cover Text may be at most 5 words, and a Back-Cover Text may + be at most 25 words. + + A "Transparent" copy of the Document means a machine-readable copy, + represented in a format whose specification is available to the + general public, that is suitable for revising the document + straightforwardly with generic text editors or (for images + composed of pixels) generic paint programs or (for drawings) some + widely available drawing editor, and that is suitable for input to + text formatters or for automatic translation to a variety of + formats suitable for input to text formatters. A copy made in an + otherwise Transparent file format whose markup, or absence of + markup, has been arranged to thwart or discourage subsequent + modification by readers is not Transparent. An image format is + not Transparent if used for any substantial amount of text. A + copy that is not "Transparent" is called "Opaque". + + Examples of suitable formats for Transparent copies include plain + ASCII without markup, Texinfo input format, LaTeX input format, + SGML or XML using a publicly available DTD, and + standard-conforming simple HTML, PostScript or PDF designed for + human modification. Examples of transparent image formats include + PNG, XCF and JPG. Opaque formats include proprietary formats that + can be read and edited only by proprietary word processors, SGML or + XML for which the DTD and/or processing tools are not generally + available, and the machine-generated HTML, PostScript or PDF + produced by some word processors for output purposes only. + + The "Title Page" means, for a printed book, the title page itself, + plus such following pages as are needed to hold, legibly, the + material this License requires to appear in the title page. For + works in formats which do not have any title page as such, "Title + Page" means the text near the most prominent appearance of the + work's title, preceding the beginning of the body of the text. + + The "publisher" means any person or entity that distributes copies + of the Document to the public. + + A section "Entitled XYZ" means a named subunit of the Document + whose title either is precisely XYZ or contains XYZ in parentheses + following text that translates XYZ in another language. (Here XYZ + stands for a specific section name mentioned below, such as + "Acknowledgements", "Dedications", "Endorsements", or "History".) + To "Preserve the Title" of such a section when you modify the + Document means that it remains a section "Entitled XYZ" according + to this definition. + + The Document may include Warranty Disclaimers next to the notice + which states that this License applies to the Document. These + Warranty Disclaimers are considered to be included by reference in + this License, but only as regards disclaiming warranties: any other + implication that these Warranty Disclaimers may have is void and + has no effect on the meaning of this License. + + 2. VERBATIM COPYING + + You may copy and distribute the Document in any medium, either + commercially or noncommercially, provided that this License, the + copyright notices, and the license notice saying this License + applies to the Document are reproduced in all copies, and that you + add no other conditions whatsoever to those of this License. You + may not use technical measures to obstruct or control the reading + or further copying of the copies you make or distribute. However, + you may accept compensation in exchange for copies. If you + distribute a large enough number of copies you must also follow + the conditions in section 3. + + You may also lend copies, under the same conditions stated above, + and you may publicly display copies. + + 3. COPYING IN QUANTITY + + If you publish printed copies (or copies in media that commonly + have printed covers) of the Document, numbering more than 100, and + the Document's license notice requires Cover Texts, you must + enclose the copies in covers that carry, clearly and legibly, all + these Cover Texts: Front-Cover Texts on the front cover, and + Back-Cover Texts on the back cover. Both covers must also clearly + and legibly identify you as the publisher of these copies. The + front cover must present the full title with all words of the + title equally prominent and visible. You may add other material + on the covers in addition. Copying with changes limited to the + covers, as long as they preserve the title of the Document and + satisfy these conditions, can be treated as verbatim copying in + other respects. + + If the required texts for either cover are too voluminous to fit + legibly, you should put the first ones listed (as many as fit + reasonably) on the actual cover, and continue the rest onto + adjacent pages. + + If you publish or distribute Opaque copies of the Document + numbering more than 100, you must either include a + machine-readable Transparent copy along with each Opaque copy, or + state in or with each Opaque copy a computer-network location from + which the general network-using public has access to download + using public-standard network protocols a complete Transparent + copy of the Document, free of added material. If you use the + latter option, you must take reasonably prudent steps, when you + begin distribution of Opaque copies in quantity, to ensure that + this Transparent copy will remain thus accessible at the stated + location until at least one year after the last time you + distribute an Opaque copy (directly or through your agents or + retailers) of that edition to the public. + + It is requested, but not required, that you contact the authors of + the Document well before redistributing any large number of + copies, to give them a chance to provide you with an updated + version of the Document. + + 4. MODIFICATIONS + + You may copy and distribute a Modified Version of the Document + under the conditions of sections 2 and 3 above, provided that you + release the Modified Version under precisely this License, with + the Modified Version filling the role of the Document, thus + licensing distribution and modification of the Modified Version to + whoever possesses a copy of it. In addition, you must do these + things in the Modified Version: + + A. Use in the Title Page (and on the covers, if any) a title + distinct from that of the Document, and from those of + previous versions (which should, if there were any, be listed + in the History section of the Document). You may use the + same title as a previous version if the original publisher of + that version gives permission. + + B. List on the Title Page, as authors, one or more persons or + entities responsible for authorship of the modifications in + the Modified Version, together with at least five of the + principal authors of the Document (all of its principal + authors, if it has fewer than five), unless they release you + from this requirement. + + C. State on the Title page the name of the publisher of the + Modified Version, as the publisher. + + D. Preserve all the copyright notices of the Document. + + E. Add an appropriate copyright notice for your modifications + adjacent to the other copyright notices. + + F. Include, immediately after the copyright notices, a license + notice giving the public permission to use the Modified + Version under the terms of this License, in the form shown in + the Addendum below. + + G. Preserve in that license notice the full lists of Invariant + Sections and required Cover Texts given in the Document's + license notice. + + H. Include an unaltered copy of this License. + + I. Preserve the section Entitled "History", Preserve its Title, + and add to it an item stating at least the title, year, new + authors, and publisher of the Modified Version as given on + the Title Page. If there is no section Entitled "History" in + the Document, create one stating the title, year, authors, + and publisher of the Document as given on its Title Page, + then add an item describing the Modified Version as stated in + the previous sentence. + + J. Preserve the network location, if any, given in the Document + for public access to a Transparent copy of the Document, and + likewise the network locations given in the Document for + previous versions it was based on. These may be placed in + the "History" section. You may omit a network location for a + work that was published at least four years before the + Document itself, or if the original publisher of the version + it refers to gives permission. + + K. For any section Entitled "Acknowledgements" or "Dedications", + Preserve the Title of the section, and preserve in the + section all the substance and tone of each of the contributor + acknowledgements and/or dedications given therein. + + L. Preserve all the Invariant Sections of the Document, + unaltered in their text and in their titles. Section numbers + or the equivalent are not considered part of the section + titles. + + M. Delete any section Entitled "Endorsements". Such a section + may not be included in the Modified Version. + + N. Do not retitle any existing section to be Entitled + "Endorsements" or to conflict in title with any Invariant + Section. + + O. Preserve any Warranty Disclaimers. + + If the Modified Version includes new front-matter sections or + appendices that qualify as Secondary Sections and contain no + material copied from the Document, you may at your option + designate some or all of these sections as invariant. To do this, + add their titles to the list of Invariant Sections in the Modified + Version's license notice. These titles must be distinct from any + other section titles. + + You may add a section Entitled "Endorsements", provided it contains + nothing but endorsements of your Modified Version by various + parties--for example, statements of peer review or that the text + has been approved by an organization as the authoritative + definition of a standard. + + You may add a passage of up to five words as a Front-Cover Text, + and a passage of up to 25 words as a Back-Cover Text, to the end + of the list of Cover Texts in the Modified Version. Only one + passage of Front-Cover Text and one of Back-Cover Text may be + added by (or through arrangements made by) any one entity. If the + Document already includes a cover text for the same cover, + previously added by you or by arrangement made by the same entity + you are acting on behalf of, you may not add another; but you may + replace the old one, on explicit permission from the previous + publisher that added the old one. + + The author(s) and publisher(s) of the Document do not by this + License give permission to use their names for publicity for or to + assert or imply endorsement of any Modified Version. + + 5. COMBINING DOCUMENTS + + You may combine the Document with other documents released under + this License, under the terms defined in section 4 above for + modified versions, provided that you include in the combination + all of the Invariant Sections of all of the original documents, + unmodified, and list them all as Invariant Sections of your + combined work in its license notice, and that you preserve all + their Warranty Disclaimers. + + The combined work need only contain one copy of this License, and + multiple identical Invariant Sections may be replaced with a single + copy. If there are multiple Invariant Sections with the same name + but different contents, make the title of each such section unique + by adding at the end of it, in parentheses, the name of the + original author or publisher of that section if known, or else a + unique number. Make the same adjustment to the section titles in + the list of Invariant Sections in the license notice of the + combined work. + + In the combination, you must combine any sections Entitled + "History" in the various original documents, forming one section + Entitled "History"; likewise combine any sections Entitled + "Acknowledgements", and any sections Entitled "Dedications". You + must delete all sections Entitled "Endorsements." + + 6. COLLECTIONS OF DOCUMENTS + + You may make a collection consisting of the Document and other + documents released under this License, and replace the individual + copies of this License in the various documents with a single copy + that is included in the collection, provided that you follow the + rules of this License for verbatim copying of each of the + documents in all other respects. + + You may extract a single document from such a collection, and + distribute it individually under this License, provided you insert + a copy of this License into the extracted document, and follow + this License in all other respects regarding verbatim copying of + that document. + + 7. AGGREGATION WITH INDEPENDENT WORKS + + A compilation of the Document or its derivatives with other + separate and independent documents or works, in or on a volume of + a storage or distribution medium, is called an "aggregate" if the + copyright resulting from the compilation is not used to limit the + legal rights of the compilation's users beyond what the individual + works permit. When the Document is included in an aggregate, this + License does not apply to the other works in the aggregate which + are not themselves derivative works of the Document. + + If the Cover Text requirement of section 3 is applicable to these + copies of the Document, then if the Document is less than one half + of the entire aggregate, the Document's Cover Texts may be placed + on covers that bracket the Document within the aggregate, or the + electronic equivalent of covers if the Document is in electronic + form. Otherwise they must appear on printed covers that bracket + the whole aggregate. + + 8. TRANSLATION + + Translation is considered a kind of modification, so you may + distribute translations of the Document under the terms of section + 4. Replacing Invariant Sections with translations requires special + permission from their copyright holders, but you may include + translations of some or all Invariant Sections in addition to the + original versions of these Invariant Sections. You may include a + translation of this License, and all the license notices in the + Document, and any Warranty Disclaimers, provided that you also + include the original English version of this License and the + original versions of those notices and disclaimers. In case of a + disagreement between the translation and the original version of + this License or a notice or disclaimer, the original version will + prevail. + + If a section in the Document is Entitled "Acknowledgements", + "Dedications", or "History", the requirement (section 4) to + Preserve its Title (section 1) will typically require changing the + actual title. + + 9. TERMINATION + + You may not copy, modify, sublicense, or distribute the Document + except as expressly provided under this License. Any attempt + otherwise to copy, modify, sublicense, or distribute it is void, + and will automatically terminate your rights under this License. + + 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, receipt of a copy of some or all of + the same material does not give you any rights to use it. + + 10. FUTURE REVISIONS OF THIS LICENSE + + The Free Software Foundation may publish new, revised versions of + the GNU Free Documentation 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. See + 'http://www.gnu.org/copyleft/'. + + Each version of the License is given a distinguishing version + number. If the Document specifies that a particular numbered + version of this License "or any later version" applies to it, you + have the option of following the terms and conditions either of + that specified version or of any later version that has been + published (not as a draft) by the Free Software Foundation. If + the Document does not specify a version number of this License, + you may choose any version ever published (not as a draft) by the + Free Software Foundation. If the Document specifies that a proxy + can decide which future versions of this License can be used, that + proxy's public statement of acceptance of a version permanently + authorizes you to choose that version for the Document. + + 11. RELICENSING + + "Massive Multiauthor Collaboration Site" (or "MMC Site") means any + World Wide Web server that publishes copyrightable works and also + provides prominent facilities for anybody to edit those works. A + public wiki that anybody can edit is an example of such a server. + A "Massive Multiauthor Collaboration" (or "MMC") contained in the + site means any set of copyrightable works thus published on the MMC + site. + + "CC-BY-SA" means the Creative Commons Attribution-Share Alike 3.0 + license published by Creative Commons Corporation, a not-for-profit + corporation with a principal place of business in San Francisco, + California, as well as future copyleft versions of that license + published by that same organization. + + "Incorporate" means to publish or republish a Document, in whole or + in part, as part of another Document. + + An MMC is "eligible for relicensing" if it is licensed under this + License, and if all works that were first published under this + License somewhere other than this MMC, and subsequently + incorporated in whole or in part into the MMC, (1) had no cover + texts or invariant sections, and (2) were thus incorporated prior + to November 1, 2008. + + The operator of an MMC Site may republish an MMC contained in the + site under CC-BY-SA on the same site at any time before August 1, + 2009, provided the MMC is eligible for relicensing. + + +ADDENDUM: How to use this License for your documents +==================================================== + +To use this License in a document you have written, include a copy of +the License in the document and put the following copyright and license +notices just after the title page: + + Copyright (C) YEAR YOUR NAME. + 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 later version published by the Free Software Foundation; + with no Invariant Sections, no Front-Cover Texts, and no Back-Cover + Texts. A copy of the license is included in the section entitled ``GNU + Free Documentation License''. + + If you have Invariant Sections, Front-Cover Texts and Back-Cover +Texts, replace the "with...Texts." line with this: + + with the Invariant Sections being LIST THEIR TITLES, with + the Front-Cover Texts being LIST, and with the Back-Cover Texts + being LIST. + + If you have Invariant Sections without Cover Texts, or some other +combination of the three, merge those two alternatives to suit the +situation. + + If your document contains nontrivial examples of program code, we +recommend releasing these examples in parallel under your choice of +free software license, such as the GNU General Public License, to +permit their use in free software. + + + +Tag Table: +Node: Top535 +Node: Overview2198 +Node: Introduction to line editing4254 +Node: Invoking ed11527 +Node: Line addressing13529 +Node: Regular expressions17242 +Node: Commands22586 +Ref: shell escape command36495 +Node: Limitations37517 +Node: Diagnostics38162 +Node: Problems38807 +Node: GNU Free Documentation License39340 + +End Tag Table + + +Local Variables: +coding: iso-8859-15 +End: diff --git a/doc/ed.texi b/doc/ed.texi new file mode 100644 index 0000000..cdf1f6c --- /dev/null +++ b/doc/ed.texi @@ -0,0 +1,1065 @@ +\input texinfo @c -*-texinfo-*- +@c %**start of header +@setfilename ed.info +@documentencoding ISO-8859-15 +@settitle GNU @command{ed} Manual +@finalout +@c %**end of header + +@set UPDATED 22 February 2017 +@set VERSION 1.14.2 + +@dircategory Basics +@direntry +* Ed: (ed). The GNU line editor +@end direntry + +@copying +Copyright @copyright{} 1993, 1994, 2006-2017 +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 later version published by the Free Software Foundation; with no +Invariant Sections, no Front-Cover Texts, and no Back-Cover Texts. +@end copying + +@ifnothtml +@titlepage +@title GNU ed +@subtitle The GNU line editor +@subtitle for GNU ed version @value{VERSION}, @value{UPDATED} +@author by Andrew L. Moore, Fran�ois Pinard, and Antonio Diaz Diaz + +@page +@vskip 0pt plus 1filll +@insertcopying +@end titlepage + +@contents +@end ifnothtml + +@ifnottex +@node Top +@top The GNU ed line editor + +This manual is for GNU ed (version @value{VERSION}, @value{UPDATED}). + +@sp 1 +GNU ed is a line-oriented text editor. It is used to create, display, +modify and otherwise manipulate text files, both interactively and via +shell scripts. A restricted version of ed, red, can only edit files in +the current directory and cannot execute shell commands. Ed is the +"standard" text editor in the sense that it is the original editor for +Unix, and thus widely available. For most purposes, however, it is +superseded by full-screen editors such as GNU Emacs or GNU Moe. +@end ifnottex + +@menu +* Overview:: Overview of the @command{ed} command +* Introduction to line editing:: Getting started with GNU @command{ed} +* Invoking ed:: Command line interface +* Line addressing:: Specifying lines/ranges in the buffer +* Regular expressions:: Patterns for selecting text +* Commands:: Commands recognized by GNU @command{ed} +* Limitations:: Intrinsic limits of GNU @command{ed} +* Diagnostics:: GNU @command{ed} error handling +* Problems:: Reporting bugs +* GNU Free Documentation License:: How you can copy and share this manual +@end menu + +@sp 1 +@insertcopying + + +@node Overview +@chapter Overview + +@command{ed} is a line-oriented text editor. It is used to create, +display, modify and otherwise manipulate text files. @command{red} is a +restricted @command{ed}: it can only edit files in the current directory +and cannot execute shell commands. + +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. + +Editing is done in two distinct modes: @dfn{command} and @dfn{input}. +When first invoked, @command{ed} is in command mode. In this mode +commands are read from the standard input and executed to manipulate the +contents of the editor buffer. A typical command might look like: + +@example +,s/@var{old}/@var{new}/g +@end example + +which replaces all occurences of the string @var{old} with @var{new}. + +When an input command, such as @samp{a} (append), @samp{i} (insert) or +@samp{c} (change), is given, @command{ed} enters input mode. This is the +primary means of adding text to a file. In this mode, no commands are +available; instead, the standard input is written directly to the editor +buffer. A @dfn{line} consists of the text up to and including a +@key{newline} character. Input mode is terminated by entering a single +period (@samp{.}) on a line. + +All @command{ed} commands operate on whole lines or ranges of lines; +e.g., the @samp{d} command deletes lines; the @samp{m} command moves +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: + +@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. + + +@node Introduction to line editing +@chapter Introduction to line editing + +@command{ed} was created, along with the Unix operating system, by Ken +Thompson and Dennis Ritchie. It is the refinement of its more complex, +programmable predecessor, @cite{QED}, to which Thompson and Ritchie had +already added pattern matching capabilities (@pxref{Regular +expressions}). + +For the purposes of this tutorial, a working knowledge of the Unix shell +@command{sh} and the Unix file system is recommended, since @command{ed} +is designed to interact closely with them. +@ifnothtml +(@xref{Top,GNU bash manual,,bash}, +@end ifnothtml +@ifhtml +(See the +@uref{http://www.gnu.org/software/bash/manual/,,bash manual} +@end ifhtml +for details about bash). + +The principal difference between line editors and display editors is +that display editors provide instant feedback to user commands, whereas +line editors require sometimes lengthy input before any effects are +seen. The advantage of instant feedback, of course, is that if a mistake +is made, it can be corrected immediately, before more damage is done. +Editing in @command{ed} requires more strategy and forethought; but if +you are up to the task, it can be quite efficient. + +Much of the @command{ed} command syntax is shared with other Unix +utilities. + +As with the shell, @key{RETURN} (the carriage-return key) enters a line +of input. So when we speak of "entering" a command or some text in +@command{ed}, @key{RETURN} is implied at the end of each line. Prior to +typing @key{RETURN}, corrections to the line may be made by typing +either @key{BACKSPACE} to erase characters backwards, or @key{CONTROL}-u +(i.e., hold the CONTROL key and type u) to erase the whole line. + +When @command{ed} first opens, it expects to be told what to do but +doesn't prompt us like the shell. So let's begin by telling @command{ed} +to do so with the @key{P} (@dfn{prompt}) command: + +@example +$ ed +P +* +@end example + +By default, @command{ed} uses asterisk (@samp{*}) as command prompt to +avoid confusion with the shell command prompt (@samp{$}). + +We can run Unix shell (@command{sh}) commands from inside @command{ed} +by prefixing them with @key{!} (exclamation mark, aka "bang"). For +example: + +@example +*!date +Mon Jun 26 10:08:41 PDT 2006 +! +*!for s in hello world; do echo $s; done +hello +world +! +* +@end example + +So far, this is no different from running commands in the Unix shell. +But let's say we want to edit the output of a command, or save it to a +file. First we must capture the command output to a temporary location +called a @dfn{buffer} where @command{ed} can access it. This is done +with @command{ed}'s @key{r} command (mnemonic: @dfn{read}): + +@example +*r !cal -m +137 +* +@end example + +Here @command{ed} is telling us that it has just read 137 characters +into the editor buffer - i.e., the output of the @command{cal} command, +which prints a simple ASCII calendar. To display the buffer contents we +issue the @key{p} (@dfn{print}) command (not to be confused with the +prompt command, which is uppercase!). To indicate the range of lines in +the buffer that should be printed, we prefix the command with @key{,} +(comma) which is shorthand for "the whole buffer": + +@example +*,p + June 2006 +Mo Tu We Th Fr Sa Su + 1 2 3 4 + 5 6 7 8 9 10 11 +12 13 14 15 16 17 18 +19 20 21 22 23 24 25 +26 27 28 29 30 + +* +@end example + +Now let's write the buffer contents to a file named @code{junk} with the +@key{w} (@dfn{write}) command: + +@example +*w junk +137 +* +@end example + +Need we say? It's good practice to frequently write the buffer contents, +since unwritten changes to the buffer will be lost when we exit +@command{ed}. + +The sample sessions below illustrate some basic concepts of line editing +with @command{ed}. We begin by creating a file, @samp{sonnet}, with some +help from Shakespeare. As with the shell, all input to @command{ed} must +be followed by a @key{newline} character. Commands beginning with +@samp{#} are taken as comments and ignored. Input mode lines that begin +with @samp{#} are just more input. + +@example +$ ed +# The 'a' command is for appending text to the editor buffer. +a +No more be grieved at that which thou hast done. +Roses have thorns, and filvers foutians mud. +Clouds and eclipses stain both moon and sun, +And loathsome canker lives in sweetest bud. +. +# Entering a single period on a line returns @command{ed} to command mode. +# Now write the buffer to the file @samp{sonnet} and quit: +w sonnet +183 +# @command{ed} reports the number of characters written. +q +$ ls -l +total 2 +-rw-rw-r-- 1 alm 183 Nov 10 01:16 sonnet +$ +@end example + +In the next example, some typos are corrected in the file @samp{sonnet}. + +@example +$ ed sonnet +183 +# Begin by printing the buffer to the terminal with the @samp{p} command. +# The ',' means "all lines". +,p +No more be grieved at that which thou hast done. +Roses have thorns, and filvers foutians mud. +Clouds and eclipses stain both moon and sun, +And loathsome canker lives in sweetest bud. +# Select line 2 for editing. +2 +Roses have thorns, and filvers foutians mud. +# Use the substitute command, @samp{s}, to replace 'filvers' with 'silver', +# and print the result. +s/filvers/silver/p +Roses have thorns, and silver foutians mud. +# And correct the spelling of 'fountains'. +s/utia/untai/p +Roses have thorns, and silver fountains mud. +w sonnet +183 +q +$ +@end example + +Since @command{ed} is line-oriented, we have to tell it which line, or +range of lines we want to edit. In the above example, we do this by +specifying the line's number, or sequence in the buffer. Alternatively, +we could have specified a unique string in the line, e.g., +@samp{/filvers/}, where the @samp{/}s delimit the string in question. +Subsequent commands affect only the selected line, a.k.a. the +@dfn{current} line. Portions of that line are then replaced with the +substitute command, whose syntax is @samp{s/@var{old}/@var{new}/}. + +Although @command{ed} accepts only one command per line, the print +command @samp{p} is an exception, and may be appended to the end of most +commands. + +In the next example, a title is added to our sonnet. + +@example +$ ed sonnet +183 +a + Sonnet #50 +. +,p +No more be grieved at that which thou hast done. +Roses have thorns, and silver fountains mud. +Clouds and eclipses stain both moon and sun, +And loathsome canker lives in sweetest bud. + Sonnet #50 +# The title got appended to the end; we should have used '0a' +# to append "before the first line". +# Move the title to its proper place. +5m0p + Sonnet #50 +# The title is now the first line, and the current address has been +# set to the address of this line as well. +,p + Sonnet #50 +No more be grieved at that which thou hast done. +Roses have thorns, and silver fountains mud. +Clouds and eclipses stain both moon and sun, +And loathsome canker lives in sweetest bud. +wq sonnet +195 +$ +@end example + +When @command{ed} opens a file, the current address is initially set to +the address of the last line of that file. Similarly, the move command +@samp{m} sets the current address to the address of the last line moved. + +Related programs or routines are @command{vi (1)}, @command{sed (1)}, +@command{regex (3)}, @command{sh (1)}. Relevant documents +are: + +@quotation +Unix User's Manual Supplementary Documents: 12 --- 13 +@end quotation + +@quotation +B. W. Kernighan and P. J. Plauger: "Software Tools in Pascal", +Addison-Wesley, 1981. +@end quotation + + +@node Invoking ed +@chapter Invoking ed + +The format for running @command{ed} is: + +@example +ed [@var{options}] [@var{file}] +red [@var{options}] [@var{file}] +@end example + +@var{file} specifies the name of a file to read. If @var{file} is +prefixed with a bang (!), then it is interpreted as a shell command. In +this case, what is read is the standard output of @var{file} executed +via @command{sh (1)}. To read a file whose name begins with a bang, +prefix the name with a backslash (@kbd{\}). The default filename is set +to @var{file} only if it is not prefixed with a bang. + +@command{ed} supports the following options: + +@table @code +@item -h +@itemx --help +Print an informative help message describing the options and exit. + +@item -V +@itemx --version +Print the version number of @command{ed} on the standard output and exit. + +@item -G +@itemx --traditional +Forces backwards compatibility. This affects the behavior of the +@command{ed} commands @samp{G}, @samp{V}, @samp{f}, @samp{l}, @samp{m}, +@samp{t} and @samp{!!}. If the default behavior of these commands does +not seem familiar, then try invoking @command{ed} with this switch. + +@item -l +@itemx --loose-exit-status +Don't exit with bad status if a command happens to "fail" (for example +if a substitution command finds nothing to replace). This can be useful +when @command{ed} is invoked as the editor for crontab. + +@item -p @var{string} +@itemx --prompt=@var{string} +Specifies a command prompt. This may be toggled on and off with the +@samp{P} command. + +@item -r +@itemx --restricted +Run in restricted mode. This mode disables editing of files out of the +current directory and execution of shell commands. + +@item -s +@itemx --quiet +@itemx --silent +Suppresses diagnostics, the printing of byte counts by @samp{e}, +@samp{E}, @samp{r} and @samp{w} commands, and the @samp{!} prompt after +a @samp{!} command. This option may be useful if @command{ed}'s standard +input is from a script. + +@item -v +@itemx --verbose +Verbose mode; prints error explanations. This may be toggled on and off +with the @samp{H} command. + +@end table + +Exit status: 0 if no errors occurred; otherwise >0. + + +@node Line addressing +@chapter Line addressing + +An address represents the number of a line in the buffer. @command{ed} +maintains a @dfn{current address} which is typically supplied to +commands as the default address when none is specified. When a file is +first read, the current address is set to the address of the last line +of the file. In general, the current address is set to the address of +the last line affected by a command. + +One exception to the rule that addresses represent line numbers is the +address @samp{0} (zero). This means "before the first line", and is +valid wherever it makes sense. + +An address range is two addresses separated either by a comma (@samp{,}) +or a semicolon (@samp{;}). In a semicolon-delimited range, the current +address (@samp{.}) is set to the first address before the second address +is calculated. This feature can be used to set the starting line for +searches. The value of the first address in a range cannot exceed the +value of the second. + +Addresses can be omitted on either side of the comma or semicolon +separator. If only the first address is given in a range, then the +second address is set to the given address. If only the second address +is given, the resulting address pairs are @samp{1,addr} and +@samp{.;addr} respectively. If a @var{n}-tuple of addresses is given +where @var{n} > 2, then the corresponding range is determined by the +last two addresses in the @var{n}-tuple. If only one address is +expected, then the last address is used. It is an error to give any +number of addresses to a command that requires zero addresses. + +A line address is constructed as follows: + +@table @code +@item . +The current line (address) in the buffer. + +@item $ +The last line in the buffer. + +@item @var{n} +The @var{n}th line in the buffer, where @var{n} is a number in the range +@samp{0,$}. + +@item +@var{n} +The @var{n}th next line, where @var{n} is a non-negative number. + +@item -@var{n} +The @var{n}th previous line, where @var{n} is a non-negative number. + +@item + +The next line. This is equivalent to @samp{+1} and may be repeated with +cumulative effect. + +@item - +The previous line. This is equivalent to @samp{-1} and may be repeated +with cumulative effect. + +@item , +The first through last lines in the buffer. This is equivalent to the +address range @samp{1,$}. + +@item ; +The current through last lines in the buffer. This is equivalent to the +address range @samp{.;$}. + +@item /@var{re}/ +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. A null @var{re} @samp{//} repeats the last search. + +@item ?@var{re}? +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. A null @var{re} @samp{??} repeats the last search. + +@item 'x +The apostrophe-x character pair addresses the line previously marked by +a @samp{k} (mark) command, where @samp{x} is a lower case letter from +the portable character set. + +@end table + +Addresses can be followed by one or more address offsets, optionally +separated by whitespace. Offsets are constructed as follows: + +@itemize @bullet +@item +@samp{+} or @samp{-} followed by a number adds or subtracts the +indicated number of lines to or from the address. + +@item +@samp{+} or @samp{-} not followed by a number adds or subtracts 1 to or +from the address. + +@item +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. + + +@node Regular expressions +@chapter Regular expressions + +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. + +In addition to a 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 longest match is the one selected. + +The following symbols are used in constructing regular expressions: + +@table @code + +@item @var{c} +Any character @var{c} not listed below, including @samp{@{}, @samp{@}}, +@samp{(}, @samp{)}, @samp{<} and @samp{>}, matches itself. + +@item \@var{c} +Any backslash-escaped character @var{c}, other than @samp{@{}, +@samp{@}}, @samp{(}, @samp{)}, @samp{<}, @samp{>}, @samp{b}, @samp{B}, +@samp{w}, @samp{W}, @samp{+} and @samp{?}, matches itself. + +@item . +Matches any single character. + +@item [@var{char-class}] +Matches any single character in @var{char-class}. To include a @samp{]} +in @var{char-class}, it must be the first character. A range of +characters may be specified by separating the end characters of the +range with a @samp{-}, e.g., @samp{a-z} specifies the lower case +characters. The following literal expressions can also be used in +@var{char-class} to specify sets of characters: + +@example +[:alnum:] [:cntrl:] [:lower:] [:space:] +[:alpha:] [:digit:] [:print:] [:upper:] +[:blank:] [:graph:] [:punct:] [:xdigit:] +@end example + +If @samp{-} appears as the first or last character of @var{char-class}, +then it matches itself. All other characters in @var{char-class} match +themselves. + +Patterns in +@var{char-class} +of the form: +@example +[.@var{col-elm}.] +[=@var{col-elm}=] +@end example + +@noindent +where @var{col-elm} is a @dfn{collating element} are interpreted +according to @code{locale (5)}. See +@code{regex (3)} for an explanation of these constructs. + +@item [^@var{char-class}] +Matches any single character, other than newline, not in +@var{char-class}. @var{char-class} is defined as above. + +@item ^ +If @samp{^} is the first character of a regular expression, then it +anchors the regular expression to the beginning of a line. Otherwise, +it matches itself. + +@item $ +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 +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 +@samp{\(a.c\)\1} matches the string @samp{abcabc}, but not +@samp{abcadc}. Subexpressions are ordered relative to their left +delimiter. + +@item * +Matches the single character regular expression or subexpression +immediately preceding it zero or more times. 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. + +@item \@{@var{n},@var{m}\@} +@itemx \@{@var{n},\@} +@itemx \@{@var{n}\@} +Matches the single character regular expression or subexpression +immediately preceding it at least @var{n} and at most @var{m} times. If +@var{m} is omitted, then it matches at least @var{n} times. If the comma +is also omitted, then it matches exactly @var{n} times. If any of these +forms occurs first in a regular expression or subexpression, then it is +interpreted literally (i.e., the regular expression @samp{\@{2\@}} +matches the string @samp{@{2@}}, and so on). + +@item \< +@itemx \> +Anchors the single character regular expression or subexpression +immediately following it to the beginning (in the case of @samp{\<}) or +ending (in the case of @samp{\>}) of a @dfn{word}, i.e., in ASCII, a +maximal string of alphanumeric characters, including the underscore (_). + +@end table + +The following extended operators are preceded by a backslash @samp{\} to +distinguish them from traditional @command{ed} syntax. + +@table @code + +@item \` +@itemx \' +Unconditionally matches the beginning @samp{\`} or ending @samp{\'} of a line. + +@item \? +Optionally matches the single character regular expression or +subexpression immediately preceding it. For example, the regular +expression @samp{a[bd]\?c} matches the strings @samp{abc}, @samp{adc} +and @samp{ac}. If @samp{\?} occurs at the beginning of a regular +expressions or subexpression, then it matches a literal @samp{?}. + +@item \+ +Matches the single character regular expression or subexpression +immediately preceding it one or more times. So the regular expression +@samp{a+} is shorthand for @samp{aa*}. If @samp{\+} occurs at the +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. + +@item \B +Matches (a null string) inside a word. + +@item \w +Matches any character in a word. + +@item \W +Matches any character not in a word. + +@end table + + +@node Commands +@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{\}). + +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 +affected by the command. It is not portable to give more than one print +suffix, but @command{ed} allows any combination of non-repeated print +suffixes and combines their effects. + +An interrupt (typically @key{Control-C}) has the effect of aborting the +current command and returning the editor to command mode. + +@command{ed} recognizes the following commands. The commands are shown +together with the default address or address range supplied if none is +specified (in parenthesis). + +@table @code + +@item (.)a +Appends text to the buffer after the addressed line. The address +@samp{0} (zero) is valid for this command; it places the entered text at +the beginning of the buffer. Text is entered in input mode. The current +address is set to the address of the last line entered or, if there were +none, to the addressed line. + +@item (.,.)c +Changes lines in the buffer. The addressed lines are deleted from the +buffer, and text is inserted in their place. Text is entered in input +mode. The current address is set to the address of the last line entered +or, if there were none, to the new address of the line after the last +line deleted; if the lines deleted were originally at the end of the +buffer, the current address is set to the address of the new last line; +if no lines remain in the buffer, the current address is set to zero. + +@item (.,.)d +Deletes the addressed lines from the buffer. The current address is set +to the new address of the line after the last line deleted; if the lines +deleted were originally at the end of the buffer, the current address is +set to the address of the new last line; if no lines remain in the +buffer, the current address is set to zero. + +@item e @var{file} +Edits @var{file}, and sets the default filename. If @var{file} is not +specified, then the default filename is used. Any lines in the buffer +are deleted before the new file is read. The current address is set to +the address of the last line in the buffer. + +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. + +A warning is printed if any changes have been made in the buffer since +the last @samp{w} command that wrote the entire buffer to a file. + +@item E @var{file} +Edits @var{file} unconditionally. This is similar to the @samp{e} +command, except that unwritten changes are discarded without warning. + +@item f @var{file} +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} +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 first command of @var{command-list} must appear on the same line as +the @samp{g} command. All lines of a multi-line @var{command-list} +except the last line must be terminated with a backslash (@samp{\}). Any +commands are allowed, except for @samp{g}, @samp{G}, @samp{v}, and +@samp{V}. The @samp{.} terminating the input mode of commands @samp{a}, +@samp{c}, and @samp{i} can be omitted if it would be the last line of +@var{command-list}. By default, a 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}/ +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. + +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. + +@item h +Prints an explanation of the last error. + +@item H +Toggles the printing of error explanations. By default, explanations are +not printed. It is recommended that ed scripts begin with this command +to aid in debugging. + +@item (.)i +Inserts text in the buffer before the addressed line. The address +@samp{0} (zero) is valid for this command; it is equivalent to address +@samp{1}. Text is entered in input mode. The current address is set to +the address of the last line entered or, if there were none, to the +addressed line. + +@item (.,.+1)j +Joins the addressed lines, replacing them by a single line containing +their joined text. If only one address is given, this command does +nothing. If lines are joined, the current address is set to the address +of the joined line. Else, the current address is unchanged. + +@item (.)kx +Marks a line with a lower case letter @samp{x}. The line can then be +addressed as @samp{'x} (i.e., a single quote followed by @samp{x}) in +subsequent commands. The mark is not cleared until the line is deleted +or otherwise modified. The current address is unchanged. + +@item (.,.)l +List command. Prints the addressed lines unambiguously. The end of each +line is marked with a @samp{$}, and every @samp{$} character within the +text is printed with a preceding backslash. Special characters are +printed as escape sequences. The current address is set to the address +of the last line printed. + +@item (.,.)m(.) +Moves lines in the buffer. The addressed lines are moved to after the +right-hand destination address. The destination address @samp{0} (zero) +is valid for this command; it moves the addressed lines to the beginning +of the buffer. It is an error if the destination address falls within +the range of moved lines. The current address is set to the new address +of the last line moved. + +@item (.,.)n +Number command. Prints the addressed lines, preceding each line by its +line number and a @key{tab}. The current address is set to the address +of the last line printed. + +@item (.,.)p +Prints the addressed lines. The current address is set to the address of +the last line printed. + +@item P +Toggles the command prompt on and off. Unless a prompt is specified with +command-line option @samp{-p}, the command prompt is by default turned +off. + +@item q +Quits @command{ed}. A warning is printed if any changes have been made +in the buffer since the last @samp{w} command that wrote the entire +buffer to a file. + +@item Q +Quits @command{ed} unconditionally. This is similar to the @code{q} +command, except that unwritten changes are discarded without warning. + +@item ($)r @var{file} +Reads @var{file} and appends it after the addressed line. If @var{file} +is not specified, then the default filename is used. If there is no +default filename prior to the command, then the default filename is set +to @var{file}. Otherwise, the default filename is unchanged. The address +@samp{0} (zero) is valid for this command; it reads the file at the +beginning of the buffer. The current address is set to the address of +the last line read or, if there were none, to the addressed line. + +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. + +@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 becomes 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}, except if the @samp{s} command is part +of a @samp{g} or @samp{v} @var{command-list}, because in this case the +meaning of the escaped newline becomes ambiguous. 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 regular expression of +the last search to be used instead of that 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 +lines are copied at the beginning of the buffer. The current address is +set to the address of the last line copied. + +@item u +Undoes the effect of the last command that modified anything in the +buffer and restores the current address to what it was before the +command. The 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. + +@item (1,$)v/@var{re}/@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}/ +This is similar to the @samp{G} command except that it interactively +edits the addressed lines not matching the regular expression @var{re}. + +@item (1,$)w @var{file} +Writes the addressed lines to @var{file}. Any previous contents of +@var{file} is lost without warning. If there is no default filename, +then the default filename is set to @var{file}, otherwise it is +unchanged. If no filename is specified, then the default filename is +used. The current address is unchanged. + +If @var{file} is prefixed with a bang (!), then it is interpreted as a +shell command and the addressed lines are written to its standard input, +(@pxref{shell escape command} @samp{!} below). In this case the default +filename is unchanged. Writing the buffer to a shell command does not +prevent the warning to the user if an attempt is made to overwrite or +discard the buffer via the @samp{e} or @samp{q} commands. + +@item (1,$)wq @var{file} +Writes the addressed lines to @var{file}, and then executes a @samp{q} +command. + +@item (1,$)W @var{file} +Appends the addressed lines to the end of @var{file}. This is similar to +the @samp{w} command, except that the previous contents of file is not +clobbered. The current address is unchanged. + +@item (.)x +Copies (puts) the contents of the cut buffer to after the addressed +line. The current address is set to the address of the last line copied. + +@item (.,.)y +Copies (yanks) the addressed lines to the cut buffer. The cut buffer is +overwritten by subsequent @samp{c}, @samp{d}, @samp{j}, @samp{s}, or +@samp{y} commands. The current address is unchanged. + +@item (.+1)z@var{n} +Scrolls @var{n} lines at a time starting at addressed line, and sets +window size to @var{n}. If @var{n} is not specified, then the current +window size is used. Window size defaults to screen size minus two +lines, or to 22 if screen size can't be determined. The current address +is set to the 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. + +@item (.,.)# +Begins a comment; the rest of the line, up to a newline, is ignored. If +a line address followed by a semicolon is given, then the current +address is set to that address. Otherwise, the current address is +unchanged. + +@item ($)= +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. + +@end table + + +@node Limitations +@chapter Limitations + +If the terminal hangs up, @command{ed} attempts to write the buffer to +the file @file{ed.hup} or, if this fails, to @file{$HOME/ed.hup}. + +@command{ed} processes @var{file} arguments for backslash escapes, i.e., +in a filename, any character preceded by a backslash (@samp{\}) is +interpreted literally. + +If a text (non-binary) file is not terminated by a newline character, +then @command{ed} appends one on reading/writing it. In the case of a +binary file, @command{ed} does not append a newline on reading/writing. + +Per line overhead: 2 @code{pointer}s, 1 @code{long int}, and 1 @code{int}. + + +@node Diagnostics +@chapter Diagnostics + +When an error occurs, if @command{ed}'s input is from a regular file or +here document, then it exits, otherwise it prints a @samp{?} and returns +to command mode. An explanation of the last error can be printed with +the @samp{h} (help) command. + +If the @samp{u} (undo) command occurs in a global command list, then the +command list is executed only once. + +Attempting to quit @command{ed} or edit another file before writing a +modified buffer results in an error. If the command is entered a second +time, it succeeds, but any changes to the buffer are lost. + + +@node Problems +@chapter Reporting bugs + +There are probably bugs in @command{ed}. There are certainly errors and +omissions in this manual. If you report them, they will get fixed. If +you don't, no one will ever know about them and they will remain unfixed +for all eternity, if not longer. + +If you find a bug in @command{ed}, please send electronic mail to +@email{bug-ed@@gnu.org}. Include the version number, which you can +find by running @w{@code{ed --version}}. + + +@node GNU Free Documentation License +@chapter GNU Free Documentation License +@include fdl.texi + +@bye diff --git a/doc/fdl.texi b/doc/fdl.texi new file mode 100644 index 0000000..8805f1a --- /dev/null +++ b/doc/fdl.texi @@ -0,0 +1,506 @@ +@c The GNU Free Documentation License. +@center Version 1.3, 3 November 2008 + +@c This file is intended to be included within another document, +@c hence no sectioning command or @node. + +@display +Copyright @copyright{} 2000, 2001, 2002, 2007, 2008 Free Software Foundation, Inc. +@uref{http://fsf.org/} + +Everyone is permitted to copy and distribute verbatim copies +of this license document, but changing it is not allowed. +@end display + +@enumerate 0 +@item +PREAMBLE + +The purpose of this License is to make a manual, textbook, or other +functional and useful document @dfn{free} in the sense of freedom: to +assure everyone the effective freedom to copy and redistribute it, +with or without modifying it, either commercially or noncommercially. +Secondarily, this License preserves for the author and publisher a way +to get credit for their work, while not being considered responsible +for modifications made by others. + +This License is a kind of ``copyleft'', which means that derivative +works of the document must themselves be free in the same sense. It +complements the GNU General Public License, which is a copyleft +license designed for free software. + +We have designed this License in order to use it for manuals for free +software, because free software needs free documentation: a free +program should come with manuals providing the same freedoms that the +software does. But this License is not limited to software manuals; +it can be used for any textual work, regardless of subject matter or +whether it is published as a printed book. We recommend this License +principally for works whose purpose is instruction or reference. + +@item +APPLICABILITY AND DEFINITIONS + +This License applies to any manual or other work, in any medium, that +contains a notice placed by the copyright holder saying it can be +distributed under the terms of this License. Such a notice grants a +world-wide, royalty-free license, unlimited in duration, to use that +work under the conditions stated herein. The ``Document'', below, +refers to any such manual or work. Any member of the public is a +licensee, and is addressed as ``you''. You accept the license if you +copy, modify or distribute the work in a way requiring permission +under copyright law. + +A ``Modified Version'' of the Document means any work containing the +Document or a portion of it, either copied verbatim, or with +modifications and/or translated into another language. + +A ``Secondary Section'' is a named appendix or a front-matter section +of the Document that deals exclusively with the relationship of the +publishers or authors of the Document to the Document's overall +subject (or to related matters) and contains nothing that could fall +directly within that overall subject. (Thus, if the Document is in +part a textbook of mathematics, a Secondary Section may not explain +any mathematics.) The relationship could be a matter of historical +connection with the subject or with related matters, or of legal, +commercial, philosophical, ethical or political position regarding +them. + +The ``Invariant Sections'' are certain Secondary Sections whose titles +are designated, as being those of Invariant Sections, in the notice +that says that the Document is released under this License. If a +section does not fit the above definition of Secondary then it is not +allowed to be designated as Invariant. The Document may contain zero +Invariant Sections. If the Document does not identify any Invariant +Sections then there are none. + +The ``Cover Texts'' are certain short passages of text that are listed, +as Front-Cover Texts or Back-Cover Texts, in the notice that says that +the Document is released under this License. A Front-Cover Text may +be at most 5 words, and a Back-Cover Text may be at most 25 words. + +A ``Transparent'' copy of the Document means a machine-readable copy, +represented in a format whose specification is available to the +general public, that is suitable for revising the document +straightforwardly with generic text editors or (for images composed of +pixels) generic paint programs or (for drawings) some widely available +drawing editor, and that is suitable for input to text formatters or +for automatic translation to a variety of formats suitable for input +to text formatters. A copy made in an otherwise Transparent file +format whose markup, or absence of markup, has been arranged to thwart +or discourage subsequent modification by readers is not Transparent. +An image format is not Transparent if used for any substantial amount +of text. A copy that is not ``Transparent'' is called ``Opaque''. + +Examples of suitable formats for Transparent copies include plain +@sc{ascii} without markup, Texinfo input format, La@TeX{} input +format, @acronym{SGML} or @acronym{XML} using a publicly available +@acronym{DTD}, and standard-conforming simple @acronym{HTML}, +PostScript or @acronym{PDF} designed for human modification. Examples +of transparent image formats include @acronym{PNG}, @acronym{XCF} and +@acronym{JPG}. Opaque formats include proprietary formats that can be +read and edited only by proprietary word processors, @acronym{SGML} or +@acronym{XML} for which the @acronym{DTD} and/or processing tools are +not generally available, and the machine-generated @acronym{HTML}, +PostScript or @acronym{PDF} produced by some word processors for +output purposes only. + +The ``Title Page'' means, for a printed book, the title page itself, +plus such following pages as are needed to hold, legibly, the material +this License requires to appear in the title page. For works in +formats which do not have any title page as such, ``Title Page'' means +the text near the most prominent appearance of the work's title, +preceding the beginning of the body of the text. + +The ``publisher'' means any person or entity that distributes copies +of the Document to the public. + +A section ``Entitled XYZ'' means a named subunit of the Document whose +title either is precisely XYZ or contains XYZ in parentheses following +text that translates XYZ in another language. (Here XYZ stands for a +specific section name mentioned below, such as ``Acknowledgements'', +``Dedications'', ``Endorsements'', or ``History''.) To ``Preserve the Title'' +of such a section when you modify the Document means that it remains a +section ``Entitled XYZ'' according to this definition. + +The Document may include Warranty Disclaimers next to the notice which +states that this License applies to the Document. These Warranty +Disclaimers are considered to be included by reference in this +License, but only as regards disclaiming warranties: any other +implication that these Warranty Disclaimers may have is void and has +no effect on the meaning of this License. + +@item +VERBATIM COPYING + +You may copy and distribute the Document in any medium, either +commercially or noncommercially, provided that this License, the +copyright notices, and the license notice saying this License applies +to the Document are reproduced in all copies, and that you add no other +conditions whatsoever to those of this License. You may not use +technical measures to obstruct or control the reading or further +copying of the copies you make or distribute. However, you may accept +compensation in exchange for copies. If you distribute a large enough +number of copies you must also follow the conditions in section 3. + +You may also lend copies, under the same conditions stated above, and +you may publicly display copies. + +@item +COPYING IN QUANTITY + +If you publish printed copies (or copies in media that commonly have +printed covers) of the Document, numbering more than 100, and the +Document's license notice requires Cover Texts, you must enclose the +copies in covers that carry, clearly and legibly, all these Cover +Texts: Front-Cover Texts on the front cover, and Back-Cover Texts on +the back cover. Both covers must also clearly and legibly identify +you as the publisher of these copies. The front cover must present +the full title with all words of the title equally prominent and +visible. You may add other material on the covers in addition. +Copying with changes limited to the covers, as long as they preserve +the title of the Document and satisfy these conditions, can be treated +as verbatim copying in other respects. + +If the required texts for either cover are too voluminous to fit +legibly, you should put the first ones listed (as many as fit +reasonably) on the actual cover, and continue the rest onto adjacent +pages. + +If you publish or distribute Opaque copies of the Document numbering +more than 100, you must either include a machine-readable Transparent +copy along with each Opaque copy, or state in or with each Opaque copy +a computer-network location from which the general network-using +public has access to download using public-standard network protocols +a complete Transparent copy of the Document, free of added material. +If you use the latter option, you must take reasonably prudent steps, +when you begin distribution of Opaque copies in quantity, to ensure +that this Transparent copy will remain thus accessible at the stated +location until at least one year after the last time you distribute an +Opaque copy (directly or through your agents or retailers) of that +edition to the public. + +It is requested, but not required, that you contact the authors of the +Document well before redistributing any large number of copies, to give +them a chance to provide you with an updated version of the Document. + +@item +MODIFICATIONS + +You may copy and distribute a Modified Version of the Document under +the conditions of sections 2 and 3 above, provided that you release +the Modified Version under precisely this License, with the Modified +Version filling the role of the Document, thus licensing distribution +and modification of the Modified Version to whoever possesses a copy +of it. In addition, you must do these things in the Modified Version: + +@enumerate A +@item +Use in the Title Page (and on the covers, if any) a title distinct +from that of the Document, and from those of previous versions +(which should, if there were any, be listed in the History section +of the Document). You may use the same title as a previous version +if the original publisher of that version gives permission. + +@item +List on the Title Page, as authors, one or more persons or entities +responsible for authorship of the modifications in the Modified +Version, together with at least five of the principal authors of the +Document (all of its principal authors, if it has fewer than five), +unless they release you from this requirement. + +@item +State on the Title page the name of the publisher of the +Modified Version, as the publisher. + +@item +Preserve all the copyright notices of the Document. + +@item +Add an appropriate copyright notice for your modifications +adjacent to the other copyright notices. + +@item +Include, immediately after the copyright notices, a license notice +giving the public permission to use the Modified Version under the +terms of this License, in the form shown in the Addendum below. + +@item +Preserve in that license notice the full lists of Invariant Sections +and required Cover Texts given in the Document's license notice. + +@item +Include an unaltered copy of this License. + +@item +Preserve the section Entitled ``History'', Preserve its Title, and add +to it an item stating at least the title, year, new authors, and +publisher of the Modified Version as given on the Title Page. If +there is no section Entitled ``History'' in the Document, create one +stating the title, year, authors, and publisher of the Document as +given on its Title Page, then add an item describing the Modified +Version as stated in the previous sentence. + +@item +Preserve the network location, if any, given in the Document for +public access to a Transparent copy of the Document, and likewise +the network locations given in the Document for previous versions +it was based on. These may be placed in the ``History'' section. +You may omit a network location for a work that was published at +least four years before the Document itself, or if the original +publisher of the version it refers to gives permission. + +@item +For any section Entitled ``Acknowledgements'' or ``Dedications'', Preserve +the Title of the section, and preserve in the section all the +substance and tone of each of the contributor acknowledgements and/or +dedications given therein. + +@item +Preserve all the Invariant Sections of the Document, +unaltered in their text and in their titles. Section numbers +or the equivalent are not considered part of the section titles. + +@item +Delete any section Entitled ``Endorsements''. Such a section +may not be included in the Modified Version. + +@item +Do not retitle any existing section to be Entitled ``Endorsements'' or +to conflict in title with any Invariant Section. + +@item +Preserve any Warranty Disclaimers. +@end enumerate + +If the Modified Version includes new front-matter sections or +appendices that qualify as Secondary Sections and contain no material +copied from the Document, you may at your option designate some or all +of these sections as invariant. To do this, add their titles to the +list of Invariant Sections in the Modified Version's license notice. +These titles must be distinct from any other section titles. + +You may add a section Entitled ``Endorsements'', provided it contains +nothing but endorsements of your Modified Version by various +parties---for example, statements of peer review or that the text has +been approved by an organization as the authoritative definition of a +standard. + +You may add a passage of up to five words as a Front-Cover Text, and a +passage of up to 25 words as a Back-Cover Text, to the end of the list +of Cover Texts in the Modified Version. Only one passage of +Front-Cover Text and one of Back-Cover Text may be added by (or +through arrangements made by) any one entity. If the Document already +includes a cover text for the same cover, previously added by you or +by arrangement made by the same entity you are acting on behalf of, +you may not add another; but you may replace the old one, on explicit +permission from the previous publisher that added the old one. + +The author(s) and publisher(s) of the Document do not by this License +give permission to use their names for publicity for or to assert or +imply endorsement of any Modified Version. + +@item +COMBINING DOCUMENTS + +You may combine the Document with other documents released under this +License, under the terms defined in section 4 above for modified +versions, provided that you include in the combination all of the +Invariant Sections of all of the original documents, unmodified, and +list them all as Invariant Sections of your combined work in its +license notice, and that you preserve all their Warranty Disclaimers. + +The combined work need only contain one copy of this License, and +multiple identical Invariant Sections may be replaced with a single +copy. If there are multiple Invariant Sections with the same name but +different contents, make the title of each such section unique by +adding at the end of it, in parentheses, the name of the original +author or publisher of that section if known, or else a unique number. +Make the same adjustment to the section titles in the list of +Invariant Sections in the license notice of the combined work. + +In the combination, you must combine any sections Entitled ``History'' +in the various original documents, forming one section Entitled +``History''; likewise combine any sections Entitled ``Acknowledgements'', +and any sections Entitled ``Dedications''. You must delete all +sections Entitled ``Endorsements.'' + +@item +COLLECTIONS OF DOCUMENTS + +You may make a collection consisting of the Document and other documents +released under this License, and replace the individual copies of this +License in the various documents with a single copy that is included in +the collection, provided that you follow the rules of this License for +verbatim copying of each of the documents in all other respects. + +You may extract a single document from such a collection, and distribute +it individually under this License, provided you insert a copy of this +License into the extracted document, and follow this License in all +other respects regarding verbatim copying of that document. + +@item +AGGREGATION WITH INDEPENDENT WORKS + +A compilation of the Document or its derivatives with other separate +and independent documents or works, in or on a volume of a storage or +distribution medium, is called an ``aggregate'' if the copyright +resulting from the compilation is not used to limit the legal rights +of the compilation's users beyond what the individual works permit. +When the Document is included in an aggregate, this License does not +apply to the other works in the aggregate which are not themselves +derivative works of the Document. + +If the Cover Text requirement of section 3 is applicable to these +copies of the Document, then if the Document is less than one half of +the entire aggregate, the Document's Cover Texts may be placed on +covers that bracket the Document within the aggregate, or the +electronic equivalent of covers if the Document is in electronic form. +Otherwise they must appear on printed covers that bracket the whole +aggregate. + +@item +TRANSLATION + +Translation is considered a kind of modification, so you may +distribute translations of the Document under the terms of section 4. +Replacing Invariant Sections with translations requires special +permission from their copyright holders, but you may include +translations of some or all Invariant Sections in addition to the +original versions of these Invariant Sections. You may include a +translation of this License, and all the license notices in the +Document, and any Warranty Disclaimers, provided that you also include +the original English version of this License and the original versions +of those notices and disclaimers. In case of a disagreement between +the translation and the original version of this License or a notice +or disclaimer, the original version will prevail. + +If a section in the Document is Entitled ``Acknowledgements'', +``Dedications'', or ``History'', the requirement (section 4) to Preserve +its Title (section 1) will typically require changing the actual +title. + +@item +TERMINATION + +You may not copy, modify, sublicense, or distribute the Document +except as expressly provided under this License. Any attempt +otherwise to copy, modify, sublicense, or distribute it is void, and +will automatically terminate your rights under this License. + +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, receipt of a copy of some or all of the same material does +not give you any rights to use it. + +@item +FUTURE REVISIONS OF THIS LICENSE + +The Free Software Foundation may publish new, revised versions +of the GNU Free Documentation 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. See +@uref{http://www.gnu.org/copyleft/}. + +Each version of the License is given a distinguishing version number. +If the Document specifies that a particular numbered version of this +License ``or any later version'' applies to it, you have the option of +following the terms and conditions either of that specified version or +of any later version that has been published (not as a draft) by the +Free Software Foundation. If the Document does not specify a version +number of this License, you may choose any version ever published (not +as a draft) by the Free Software Foundation. If the Document +specifies that a proxy can decide which future versions of this +License can be used, that proxy's public statement of acceptance of a +version permanently authorizes you to choose that version for the +Document. + +@item +RELICENSING + +``Massive Multiauthor Collaboration Site'' (or ``MMC Site'') means any +World Wide Web server that publishes copyrightable works and also +provides prominent facilities for anybody to edit those works. A +public wiki that anybody can edit is an example of such a server. A +``Massive Multiauthor Collaboration'' (or ``MMC'') contained in the +site means any set of copyrightable works thus published on the MMC +site. + +``CC-BY-SA'' means the Creative Commons Attribution-Share Alike 3.0 +license published by Creative Commons Corporation, a not-for-profit +corporation with a principal place of business in San Francisco, +California, as well as future copyleft versions of that license +published by that same organization. + +``Incorporate'' means to publish or republish a Document, in whole or +in part, as part of another Document. + +An MMC is ``eligible for relicensing'' if it is licensed under this +License, and if all works that were first published under this License +somewhere other than this MMC, and subsequently incorporated in whole +or in part into the MMC, (1) had no cover texts or invariant sections, +and (2) were thus incorporated prior to November 1, 2008. + +The operator of an MMC Site may republish an MMC contained in the site +under CC-BY-SA on the same site at any time before August 1, 2009, +provided the MMC is eligible for relicensing. + +@end enumerate + +@page +@heading ADDENDUM: How to use this License for your documents + +To use this License in a document you have written, include a copy of +the License in the document and put the following copyright and +license notices just after the title page: + +@smallexample +@group + Copyright (C) @var{year} @var{your name}. + 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 later version published by the Free Software Foundation; + with no Invariant Sections, no Front-Cover Texts, and no Back-Cover + Texts. A copy of the license is included in the section entitled ``GNU + Free Documentation License''. +@end group +@end smallexample + +If you have Invariant Sections, Front-Cover Texts and Back-Cover Texts, +replace the ``with@dots{}Texts.'' line with this: + +@smallexample +@group + with the Invariant Sections being @var{list their titles}, with + the Front-Cover Texts being @var{list}, and with the Back-Cover Texts + being @var{list}. +@end group +@end smallexample + +If you have Invariant Sections without Cover Texts, or some other +combination of the three, merge those two alternatives to suit the +situation. + +If your document contains nontrivial examples of program code, we +recommend releasing these examples in parallel under your choice of +free software license, such as the GNU General Public License, +to permit their use in free software. + +@c Local Variables: +@c ispell-local-pdict: "ispell-dict" +@c End: + diff --git a/ed.h b/ed.h new file mode 100644 index 0000000..2b4e3fa --- /dev/null +++ b/ed.h @@ -0,0 +1,149 @@ +/* Global declarations for the ed editor. */ +/* GNU ed - The GNU line editor. + Copyright (C) 1993, 1994 Andrew Moore, Talke Studio + Copyright (C) 2006-2017 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 + 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, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . +*/ + +#ifndef __cplusplus +enum Bool { false = 0, true = 1 }; +typedef enum Bool bool; +#endif + +enum Pflags /* print suffixes */ + { + GLS = 0x01, /* list after command */ + GNP = 0x02, /* enumerate after command */ + GPR = 0x04 /* print after command */ + }; + + +typedef struct line /* Line node */ + { + struct line * q_forw; + struct line * q_back; + long pos; /* position of text in scratch buffer */ + int len; /* length of line ('\n' is not stored) */ + } +line_t; + + +typedef struct + { + enum { UADD = 0, UDEL = 1, UMOV = 2, VMOV = 3 } type; + line_t * head; /* head of list */ + line_t * tail; /* tail of list */ + } +undo_t; + +#ifndef max +#define max( a,b ) ( (( a ) > ( b )) ? ( a ) : ( b ) ) +#endif +#ifndef min +#define min( a,b ) ( (( a ) < ( b )) ? ( a ) : ( b ) ) +#endif + + +/* defined in buffer.c */ +bool append_lines( const char ** const ibufpp, const int addr, + bool insert, const bool isglobal ); +bool close_sbuf( void ); +bool copy_lines( const int first_addr, const int second_addr, const int addr ); +int current_addr( void ); +int dec_addr( int addr ); +bool delete_lines( const int from, const int to, const bool isglobal ); +int get_line_node_addr( const line_t * const lp ); +char * get_sbuf_line( const line_t * const lp ); +int inc_addr( int addr ); +int inc_current_addr( void ); +bool init_buffers( void ); +bool isbinary( void ); +bool join_lines( const int from, const int to, const bool isglobal ); +int last_addr( void ); +bool modified( void ); +bool move_lines( const int first_addr, const int second_addr, const int addr, + const bool isglobal ); +bool open_sbuf( void ); +int path_max( const char * filename ); +bool put_lines( const int addr ); +const char * put_sbuf_line( const char * const buf, const int size ); +line_t * search_line_node( const int addr ); +void set_binary( void ); +void set_current_addr( const int addr ); +void set_modified( const bool m ); +bool yank_lines( const int from, const int to ); +void clear_undo_stack( void ); +undo_t * push_undo_atom( const int type, const int from, const int to ); +void reset_undo_state( void ); +bool undo( const bool isglobal ); + +/* defined in global.c */ +void clear_active_list( void ); +const line_t * next_active_node( void ); +bool set_active_node( const line_t * const lp ); +void unset_active_nodes( const line_t * bp, const line_t * const ep ); + +/* defined in io.c */ +bool get_extended_line( const char ** const ibufpp, int * const lenp, + const bool strip_escaped_newlines ); +const char * get_stdin_line( int * const sizep ); +int linenum( void ); +bool print_lines( int from, const int to, const int pflags ); +int read_file( const char * const filename, const int addr ); +int write_file( const char * const filename, const char * const mode, + const int from, const int to ); +void reset_unterminated_line( void ); +void unmark_unterminated_line( const line_t * const lp ); + +/* defined in main.c */ +bool is_regular_file( const int fd ); +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 traditional( void ); + +/* defined in main_loop.c */ +int main_loop( const bool loose ); +void set_def_filename( const char * const s ); +void set_error_msg( const char * msg ); +void set_prompt( const char * const s ); +void set_verbose( void ); +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 ); +bool extract_replacement( const char ** const ibufpp, const bool isglobal ); +int next_matching_node_addr( const char ** const ibufpp, const bool forward ); +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 subst_regex( void ); + +/* defined in signal.c */ +void disable_interrupts( void ); +void enable_interrupts( void ); +bool parse_int( int * const i, const char * const str, const char ** const tail ); +bool resize_buffer( char ** const buf, int * const size, const int min_size ); +bool resize_line_buffer( const line_t *** const buf, int * const size, + const int min_size ); +bool resize_undo_buffer( undo_t ** const buf, int * const size, + const int min_size ); +void set_signals( void ); +void set_window_lines( const int lines ); +const char * strip_escapes( const char * p ); +int window_columns( void ); +int window_lines( void ); diff --git a/global.c b/global.c new file mode 100644 index 0000000..d6242dc --- /dev/null +++ b/global.c @@ -0,0 +1,87 @@ +/* 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-2017 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 + 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, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . +*/ + +#include +#include +#include +#include + +#include "ed.h" + + +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 ) */ + + +/* clear the global-active list */ +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; + enable_interrupts(); + } + + +/* 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; + } + + +/* add a line node to the global-active list */ +bool set_active_node( const line_t * const lp ) + { + disable_interrupts(); + if( !resize_line_buffer( &active_list, &active_size, + ( active_len + 1 ) * sizeof (line_t **) ) ) + { + show_strerror( 0, errno ); + set_error_msg( "Memory exhausted" ); + enable_interrupts(); + return false; + } + enable_interrupts(); + active_list[active_len++] = lp; + return true; + } + + +/* remove a range of lines from the global-active list */ +void unset_active_nodes( const line_t * bp, const line_t * const ep ) + { + while( bp != 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; } + } + bp = bp->q_forw; + } + } diff --git a/io.c b/io.c new file mode 100644 index 0000000..d4d2a63 --- /dev/null +++ b/io.c @@ -0,0 +1,350 @@ +/* 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-2017 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 + 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, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . +*/ + +#include +#include +#include + +#include "ed.h" + + +static const line_t * unterminated_line = 0; /* last line has no '\n' */ +int linenum_ = 0; /* script line number */ + +void reset_unterminated_line( void ) { unterminated_line = 0; } + +void unmark_unterminated_line( const line_t * const lp ) + { if( unterminated_line == lp ) unterminated_line = 0; } + +static bool unterminated_last_line( void ) + { return ( unterminated_line != 0 && + unterminated_line == search_line_node( last_addr() ) ); } + +int linenum( void ) { return linenum_; } + + +/* print text to stdout */ +static void print_line( const char * p, int len, const int pflags ) + { + const char escapes[] = "\a\b\f\n\r\t\v\\"; + const char escchars[] = "abfnrtv\\"; + int col = 0; + + if( pflags & GNP ) { printf( "%d\t", current_addr() ); col = 8; } + while( --len >= 0 ) + { + const unsigned char ch = *p++; + if( !( pflags & GLS ) ) putchar( ch ); + else + { + if( ++col > window_columns() ) { col = 1; fputs( "\\\n", stdout ); } + if( ch >= 32 && ch <= 126 && ch != '\\' ) putchar( ch ); + else + { + char * const p = strchr( escapes, ch ); + ++col; putchar('\\'); + if( ch && p ) putchar( escchars[p-escapes] ); + else + { + col += 2; + putchar( ( ( ch >> 6 ) & 7 ) + '0' ); + putchar( ( ( ch >> 3 ) & 7 ) + '0' ); + putchar( ( ch & 7 ) + '0' ); + } + } + } + } + if( !traditional() && ( pflags & GLS ) ) putchar('$'); + putchar('\n'); + } + + +/* print a range of lines to stdout */ +bool print_lines( int from, const int to, const int pflags ) + { + line_t * const ep = search_line_node( inc_addr( to ) ); + line_t * bp = search_line_node( from ); + + if( !from ) { set_error_msg( "Invalid address" ); return false; } + while( bp != ep ) + { + const char * const s = get_sbuf_line( bp ); + if( !s ) return false; + set_current_addr( from++ ); + print_line( s, bp->len, pflags ); + bp = bp->q_forw; + } + return true; + } + + +/* return the parity of escapes at the end of a string */ +static bool trailing_escape( const char * const s, int len ) + { + bool odd_escape = false; + while( --len >= 0 && s[len] == '\\' ) odd_escape = !odd_escape; + return odd_escape; + } + + +/* If *ibufpp contains an escaped newline, get an extended line (one + with escaped newlines) from stdin. + Return line length in *lenp, including the trailing newline. */ +bool get_extended_line( const char ** const ibufpp, int * const lenp, + const bool strip_escaped_newlines ) + { + static char * buf = 0; + static int bufsz = 0; + int len; + + for( len = 0; (*ibufpp)[len++] != '\n'; ) ; + if( len < 2 || !trailing_escape( *ibufpp, len - 1 ) ) + { if( lenp ) *lenp = len; return true; } + if( !resize_buffer( &buf, &bufsz, len ) ) return false; + memcpy( buf, *ibufpp, len ); + --len; buf[len-1] = '\n'; /* strip trailing esc */ + if( strip_escaped_newlines ) --len; /* strip newline */ + while( true ) + { + int len2; + const char * const s = get_stdin_line( &len2 ); + if( !s ) return false; /* error */ + if( len2 <= 0 ) return false; /* EOF */ + if( !resize_buffer( &buf, &bufsz, len + len2 ) ) return false; + memcpy( buf + len, s, len2 ); + len += len2; + if( len2 < 2 || !trailing_escape( buf, len - 1 ) ) break; + --len; buf[len-1] = '\n'; /* strip trailing esc */ + if( strip_escaped_newlines ) --len; /* strip newline */ + } + if( !resize_buffer( &buf, &bufsz, len + 1 ) ) return false; + buf[len] = 0; + *ibufpp = buf; + if( lenp ) *lenp = len; + return true; + } + + +/* 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 */ +const char * get_stdin_line( int * const sizep ) + { + static char * buf = 0; + static int bufsz = 0; + int i = 0; + + while( true ) + { + const int c = getchar(); + if( !resize_buffer( &buf, &bufsz, i + 2 ) ) { *sizep = 0; return 0; } + if( c == EOF ) + { + if( ferror( stdin ) ) + { + show_strerror( "stdin", errno ); + set_error_msg( "Cannot read stdin" ); + clearerr( stdin ); + *sizep = 0; return 0; + } + if( feof( stdin ) ) + { + set_error_msg( "Unexpected end-of-file" ); + clearerr( stdin ); + buf[0] = 0; *sizep = 0; if( i > 0 ) ++linenum_; /* discard line */ + return buf; + } + } + else + { + buf[i++] = c; if( !c ) set_binary(); if( c != '\n' ) continue; + ++linenum_; buf[i] = 0; *sizep = i; + return buf; + } + } + } + + +/* 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) */ +static const char * read_stream_line( FILE * const fp, int * const sizep, + bool * const newline_addedp ) + { + static char * buf = 0; + static int bufsz = 0; + int c, i = 0; + + while( true ) + { + 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; + } + buf[i] = 0; + if( c == EOF ) + { + if( ferror( fp ) ) + { + show_strerror( 0, errno ); + set_error_msg( "Cannot read input file" ); + return 0; + } + else if( i ) + { + buf[i] = '\n'; buf[i+1] = 0; *newline_addedp = true; + if( !isbinary() ) ++i; + } + } + *sizep = i; + return buf; + } + + +/* read a stream into the editor buffer; + return total size of data read, or -1 if error */ +static long read_stream( FILE * const fp, const int addr ) + { + line_t * lp = search_line_node( addr ); + undo_t * up = 0; + long total_size = 0; + const bool o_isbinary = isbinary(); + const bool appended = ( addr == last_addr() ); + const bool o_unterminated_last_line = unterminated_last_line(); + bool newline_added = false; + + set_current_addr( addr ); + while( true ) + { + int size = 0; + const char * const s = read_stream_line( fp, &size, &newline_added ); + if( !s ) return -1; + if( size <= 0 ) break; + total_size += size; + disable_interrupts(); + if( !put_sbuf_line( s, size + newline_added ) ) + { enable_interrupts(); return -1; } + lp = lp->q_forw; + if( up ) up->tail = lp; + else + { + up = push_undo_atom( UADD, current_addr(), current_addr() ); + if( !up ) { enable_interrupts(); return -1; } + } + enable_interrupts(); + } + if( addr && appended && total_size && o_unterminated_last_line ) + fputs( "Newline inserted\n", stdout ); /* before stream */ + else if( newline_added && ( !appended || !isbinary() ) ) + fputs( "Newline appended\n", stdout ); /* after stream */ + if( !appended && isbinary() && !o_isbinary && newline_added ) + ++total_size; + if( appended && isbinary() && ( newline_added || total_size == 0 ) ) + unterminated_line = search_line_node( last_addr() ); + return total_size; + } + + +/* read a named file/pipe into the buffer; return line count, or -1 if error */ +int read_file( const char * const filename, const int addr ) + { + FILE * fp; + long size; + int ret; + + if( *filename == '!' ) fp = popen( filename + 1, "r" ); + else fp = fopen( strip_escapes( filename ), "r" ); + if( !fp ) + { + show_strerror( filename, errno ); + set_error_msg( "Cannot open input file" ); + return -1; + } + size = read_stream( fp, addr ); + if( *filename == '!' ) ret = pclose( fp ); else ret = fclose( fp ); + if( size < 0 ) return -1; + if( ret != 0 ) + { + show_strerror( filename, errno ); + set_error_msg( "Cannot close input file" ); + return -1; + } + if( !scripted() ) printf( "%lu\n", size ); + return current_addr() - addr; + } + + +/* write a range of lines to a stream */ +static long write_stream( FILE * const fp, int from, const int to ) + { + line_t * lp = search_line_node( from ); + long size = 0; + + while( from && from <= to ) + { + int len; + char * p = get_sbuf_line( lp ); + if( !p ) return -1; + len = lp->len; + if( from != last_addr() || !isbinary() || !unterminated_last_line() ) + p[len++] = '\n'; + size += len; + while( --len >= 0 ) + if( fputc( *p++, fp ) == EOF ) + { + show_strerror( 0, errno ); + set_error_msg( "Cannot write file" ); + return -1; + } + ++from; lp = lp->q_forw; + } + return size; + } + + +/* write a range of lines to a named file/pipe; return line count */ +int write_file( const char * const filename, const char * const mode, + const int from, const int to ) + { + FILE * fp; + long size; + int ret; + + if( *filename == '!' ) fp = popen( filename + 1, "w" ); + else fp = fopen( strip_escapes( filename ), mode ); + if( !fp ) + { + show_strerror( filename, errno ); + set_error_msg( "Cannot open output file" ); + return -1; + } + size = write_stream( fp, from, to ); + if( *filename == '!' ) ret = pclose( fp ); else ret = fclose( fp ); + if( size < 0 ) return -1; + if( ret != 0 ) + { + show_strerror( filename, errno ); + set_error_msg( "Cannot close output file" ); + return -1; + } + if( !scripted() ) printf( "%lu\n", size ); + return ( from && from <= to ) ? to - from + 1 : 0; + } diff --git a/main.c b/main.c new file mode 100644 index 0000000..a0dfc2e --- /dev/null +++ b/main.c @@ -0,0 +1,210 @@ +/* GNU ed - The GNU line editor. + Copyright (C) 2006-2017 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 + 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, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . +*/ +/* + 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. +*/ +/* + * CREDITS + * + * This program is based on the editor algorithm described in + * Brian W. Kernighan and P. J. Plauger's book "Software Tools + * in Pascal", Addison-Wesley, 1981. + * + * The buffering algorithm is attributed to Rodney Ruddock of + * the University of Guelph, Guelph, Ontario. + * + */ + +#include +#include +#include +#include +#include + +#include "carg_parser.h" +#include "ed.h" + + +static const char * const Program_name = "GNU Ed"; +static const char * const program_name = "ed"; +static const char * const program_year = "2017"; +static const char * invocation_name = 0; + +static bool restricted_ = false; /* if set, run in restricted mode */ +static bool scripted_ = false; /* if set, suppress diagnostics, + byte counts and '!' prompt */ +static bool traditional_ = false; /* if set, be backwards compatible */ + + +bool restricted( void ) { return restricted_; } +bool scripted( void ) { return scripted_; } +bool traditional( void ) { return traditional_; } + + +static void show_help( void ) + { + printf( "%s - The GNU line editor.\n", Program_name ); + printf( "\nUsage: %s [options] [file]\n", invocation_name ); + printf( "\nOptions:\n" + " -h, --help display this help and exit\n" + " -V, --version output version information and exit\n" + " -G, --traditional run in compatibility mode\n" + " -l, --loose-exit-status exit with 0 status even if a command fails\n" + " -p, --prompt=STRING use STRING as an interactive prompt\n" + " -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" + "Start 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" + "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" + "General help using GNU software: http://www.gnu.org/gethelp\n" ); + } + + +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" + "This is free software: you are free to change and redistribute it.\n" + "There is NO WARRANTY, to the extent permitted by law.\n" ); + } + + +void show_strerror( const char * const filename, const int errcode ) + { + if( !scripted_ ) + { + if( filename && filename[0] ) fprintf( stderr, "%s: ", filename ); + fprintf( stderr, "%s\n", strerror( errcode ) ); + } + } + + +static void show_error( const char * const msg, const int errcode, const bool help ) + { + if( msg && msg[0] ) + { + fprintf( stderr, "%s: %s", program_name, msg ); + if( errcode > 0 ) fprintf( stderr, ": %s", strerror( errcode ) ); + fputc( '\n', stderr ); + } + if( help ) + fprintf( stderr, "Try '%s --help' for more information.\n", + invocation_name ); + } + + +/* return true if file descriptor is a regular file */ +bool is_regular_file( const int fd ) + { + struct stat st; + return ( fstat( fd, &st ) != 0 || S_ISREG( st.st_mode ) ); + } + + +bool may_access_filename( const char * const name ) + { + if( restricted_ && + ( *name == '!' || strcmp( name, ".." ) == 0 || strchr( name, '/' ) ) ) + { + set_error_msg( "Shell access restricted" ); + return false; + } + return true; + } + + +int main( const int argc, const char * const argv[] ) + { + int argind; + bool loose = false; + const struct ap_Option options[] = + { + { '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 } }; + + struct Arg_parser parser; + invocation_name = argv[0]; + + if( !ap_init( &parser, argc, argv, options, 0 ) ) + { show_error( "Memory exhausted.", 0, false ); return 1; } + if( ap_error( &parser ) ) /* bad option */ + { show_error( ap_error( &parser ), 0, true ); return 1; } + + for( argind = 0; argind < ap_arguments( &parser ); ++argind ) + { + const int code = ap_code( &parser, argind ); + const char * const arg = ap_argument( &parser, argind ); + if( !code ) break; /* no more options */ + switch( code ) + { + case 'G': traditional_ = true; break; /* backward compatibility */ + case 'h': show_help(); return 0; + case 'l': loose = true; break; + case 'p': set_prompt( arg ); break; + case 'r': restricted_ = true; break; + case 's': scripted_ = true; break; + case 'v': set_verbose(); break; + case 'V': show_version(); return 0; + default : show_error( "internal error: uncaught option.", 0, false ); + return 3; + } + } /* end process options */ + + setlocale( LC_ALL, "" ); + if( !init_buffers() ) return 1; + + while( argind < ap_arguments( &parser ) ) + { + const char * const arg = ap_argument( &parser, argind ); + 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 ); + } + else + { + fputs( "?\n", stdout ); + if( arg[0] ) set_error_msg( "Invalid filename" ); + if( is_regular_file( 0 ) ) return 2; + } + break; + } + ap_free( &parser ); + + return main_loop( loose ); + } diff --git a/main_loop.c b/main_loop.c new file mode 100644 index 0000000..bcf31a8 --- /dev/null +++ b/main_loop.c @@ -0,0 +1,722 @@ +/* GNU ed - The GNU line editor. + Copyright (C) 1993, 1994 Andrew Moore, Talke Studio + Copyright (C) 2006-2017 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 + 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, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . +*/ + +#include +#include +#include +#include +#include + +#include "ed.h" + + +enum Status { QUIT = -1, ERR = -2, EMOD = -3, FATAL = -4 }; + +static char def_filename[1024] = ""; /* default filename */ +static char errmsg[80] = ""; /* error message buffer */ +static char prompt_str[80] = "*"; /* command prompt */ +static int first_addr = 0, second_addr = 0; +static bool prompt_on = false; /* if set, show command prompt */ +static bool verbose = false; /* if set, print all error messages */ + + +void set_def_filename( const char * const s ) + { + strncpy( def_filename, s, sizeof def_filename ); + def_filename[sizeof(def_filename)-1] = 0; + } + +void set_error_msg( const char * msg ) + { + if( !msg ) msg = ""; + strncpy( errmsg, msg, sizeof errmsg ); + errmsg[sizeof(errmsg)-1] = 0; + } + +void set_prompt( const char * const s ) + { + prompt_on = true; + strncpy( prompt_str, s, sizeof prompt_str ); + prompt_str[sizeof(prompt_str)-1] = 0; + } + +void set_verbose( void ) { verbose = true; } + + +static const line_t * mark[26]; /* line markers */ +static int markno; /* line marker count */ + +static bool mark_line_node( const line_t * const lp, int c ) + { + c -= 'a'; + if( c < 0 || c >= 26 ) + { set_error_msg( "Invalid mark character" ); return false; } + if( !mark[c] ) ++markno; + mark[c] = lp; + return true; + } + + +void unmark_line_node( const line_t * const lp ) + { + int i; + for( i = 0; markno && i < 26; ++i ) + if( mark[i] == lp ) + { mark[i] = 0; --markno; } + } + + +/* return address of a marked line */ +static int get_marked_node_addr( int c ) + { + c -= 'a'; + if( c < 0 || c >= 26 ) + { set_error_msg( "Invalid mark character" ); return -1; } + return get_line_node_addr( mark[c] ); + } + + +/* Returns 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 */ + static int bufsz = 0; + static char * shcmd = 0; /* shell command buffer */ + static int shcmdsz = 0; /* shell command buffer size */ + static int shcmdlen = 0; /* shell command length */ + int i = 0, len = 0; + bool replacement = false; + + 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 + { + if( shcmdlen <= 0 || ( traditional() && !shcmd[1] ) ) + { set_error_msg( "No previous command" ); return 0; } + memcpy( buf, shcmd, shcmdlen ); /* bufsz >= shcmdlen */ + i += shcmdlen; ++*ibufpp; replacement = true; + } + while( **ibufpp != '\n' ) + { + if( **ibufpp == '%' ) + { + const char * p; + if( !def_filename[0] ) + { set_error_msg( "No current filename" ); return 0; } + p = strip_escapes( def_filename ); + len = strlen( p ); + if( !resize_buffer( &buf, &bufsz, i + len ) ) return 0; + memcpy( buf + i, p, len ); + i += len; ++*ibufpp; replacement = true; + } + else + { + if( !resize_buffer( &buf, &bufsz, i + 2 ) ) return 0; + if( ( buf[i++] = *(*ibufpp)++ ) == '\\' ) buf[i++] = *(*ibufpp)++; + } + } + 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 ); + return shcmd; + } + + +static const char * skip_blanks( const char * p ) + { + while( isspace( (unsigned char)*p ) && *p != '\n' ) ++p; + return p; + } + + +/* Returns pointer to copy of filename in the command buffer */ +static const char * get_filename( const char ** const ibufpp, + const bool traditional_f_command ) + { + static char * buf = 0; + static int bufsz = 0; + const int pmax = path_max( 0 ); + int n; + + *ibufpp = skip_blanks( *ibufpp ); + if( **ibufpp != '\n' ) + { + int size = 0; + if( !get_extended_line( ibufpp, &size, true ) ) return 0; + if( **ibufpp == '!' ) + { ++*ibufpp; return get_shell_command( ibufpp ); } + else if( size > pmax ) + { set_error_msg( "Filename too long" ); return 0; } + } + else if( !traditional_f_command && !def_filename[0] ) + { set_error_msg( "No current filename" ); return 0; } + if( !resize_buffer( &buf, &bufsz, pmax + 1 ) ) return 0; + for( n = 0; **ibufpp != '\n'; ++n, ++*ibufpp ) buf[n] = **ibufpp; + buf[n] = 0; + while( **ibufpp == '\n' ) ++*ibufpp; /* skip newline */ + return ( may_access_filename( buf ) ? buf : 0 ); + } + + +static void invalid_address( void ) { set_error_msg( "Invalid address" ); } + + +/* Get line addresses from the command buffer until an invalid address + is seen. Returns 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. */ +static int extract_addresses( const char ** const ibufpp ) + { + bool first = true; /* true == addr, false == offset */ + + first_addr = second_addr = -1; /* set to undefined */ + *ibufpp = skip_blanks( *ibufpp ); + + while( true ) + { + int n; + const unsigned char ch = **ibufpp; + if( isdigit( ch ) ) + { + if( !parse_int( &n, *ibufpp, ibufpp ) ) return -1; + if( first ) { first = false; second_addr = n; } else second_addr += n; + } + else switch( ch ) + { + case '\t': + case ' ': *ibufpp = skip_blanks( ++*ibufpp ); break; + case '+': + case '-': if( first ) { first = false; second_addr = current_addr(); } + if( isdigit( (unsigned char)(*ibufpp)[1] ) ) + { + if( !parse_int( &n, *ibufpp, ibufpp ) ) return -1; + second_addr += n; + } + else { ++*ibufpp; + if( ch == '+' ) ++second_addr; else --second_addr; } + break; + case '.': + case '$': if( !first ) { invalid_address(); return -1; }; + first = false; ++*ibufpp; + second_addr = ( ( ch == '.' ) ? current_addr() : last_addr() ); + break; + case '/': + case '?': if( !first ) { invalid_address(); return -1; }; + second_addr = next_matching_node_addr( ibufpp, ch == '/' ); + 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; + second_addr = get_marked_node_addr( *(*ibufpp)++ ); + if( second_addr < 0 ) return -1; + break; + case '%': + case ',': + case ';': if( first ) + { + if( first_addr < 0 ) + { first_addr = ( ( ch == ';' ) ? current_addr() : 1 ); + second_addr = last_addr(); } + } + else + { + if( second_addr < 0 || second_addr > last_addr() ) + { invalid_address(); return -1; } + if( ch == ';' ) set_current_addr( second_addr ); + first_addr = second_addr; first = true; + } + ++*ibufpp; + break; + default : + if( !first && ( second_addr < 0 || second_addr > last_addr() ) ) + { invalid_address(); return -1; } + { + int addr_cnt = 0; /* limited to 2 */ + if( second_addr >= 0 ) addr_cnt = ( first_addr >= 0 ) ? 2 : 1; + if( addr_cnt <= 0 ) second_addr = current_addr(); + if( addr_cnt <= 1 ) first_addr = second_addr; + return addr_cnt; + } + } + } + } + + +/* get a valid address from the command buffer */ +static bool get_third_addr( const char ** const ibufpp, int * const addr ) + { + const int old1 = first_addr; + const int old2 = second_addr; + int addr_cnt = extract_addresses( ibufpp ); + + if( addr_cnt < 0 ) return false; + if( traditional() && addr_cnt == 0 ) + { set_error_msg( "Destination expected" ); return false; } + if( second_addr < 0 || second_addr > last_addr() ) + { invalid_address(); return false; } + *addr = second_addr; + first_addr = old1; second_addr = old2; + return true; + } + + +/* set default range and return true if address range is valid */ +static bool check_addr_range( const int n, const int m, const int addr_cnt ) + { + if( addr_cnt == 0 ) { first_addr = n; second_addr = m; } + if( first_addr < 1 || first_addr > second_addr || second_addr > last_addr() ) + { invalid_address(); return false; } + return true; + } + +/* set defaults to current_addr and return true if address range is valid */ +static bool check_addr_range2( const int addr_cnt ) + { + return check_addr_range( current_addr(), current_addr(), addr_cnt ); + } + +/* set default second_addr and return true if second_addr is valid */ +static bool check_second_addr( const int addr, const int addr_cnt ) + { + if( addr_cnt == 0 ) second_addr = addr; + if( second_addr < 1 || second_addr > last_addr() ) + { invalid_address(); return false; } + return true; + } + + +/* verify the command suffixes in the command buffer */ +static bool get_command_suffix( const char ** const ibufpp, + int * const pflagsp, int * const snump ) + { + bool nos_or_rep = !snump; /* not s command or repeated g/count */ + bool error = false; + while( true ) + { + const unsigned char ch = **ibufpp; + if( ch >= '1' && ch <= '9' ) + { + int n = 0; + if( nos_or_rep || !parse_int( &n, *ibufpp, ibufpp ) || n <= 0 ) + { error = true; break; } + nos_or_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; } + else break; + ++*ibufpp; + } + if( error || *(*ibufpp)++ != '\n' ) + { set_error_msg( "Invalid command suffix" ); return false; } + return true; + } + + +static bool unexpected_address( const int addr_cnt ) + { + if( addr_cnt > 0 ) { set_error_msg( "Unexpected address" ); return true; } + return false; + } + +static bool unexpected_command_suffix( const unsigned char ch ) + { + if( !isspace( ch ) ) + { set_error_msg( "Unexpected command suffix" ); return true; } + return false; + } + + +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 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 + } sflags = 0; /* if sflags != 0, repeat last substitution */ + + if( !check_addr_range2( addr_cnt ) ) return false; + do { + bool error = false; + if( **ibufpp >= '1' && **ibufpp <= '9' ) + { + int n = 0; + if( ( sflags & SGG ) || !parse_int( &n, *ibufpp, ibufpp ) || n <= 0 ) + error = true; + else + { sflags |= SGG; snum = n; } + } + else switch( **ibufpp ) + { + case '\n':sflags |= SGF; break; + case 'g': if( sflags & SGG ) error = true; + else { sflags |= SGG; 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; + default : if( sflags ) error = true; + } + if( error ) { set_error_msg( "Invalid command suffix" ); 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 ) + { + 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; + } + else if( sflags & SGP ) pflags ^= gmask; + *pflagsp = pflags; + if( !isglobal ) clear_undo_stack(); + if( !search_and_replace( first_addr, second_addr, snum, isglobal ) ) + return false; + return true; + } + + +static bool exec_global( const char ** const ibufpp, const int pflags, + const bool interactive ); + +/* execute the next command in command buffer; return error status */ +static int exec_command( const char ** const ibufpp, const int prev_status, + const bool isglobal ) + { + const char * fnp; /* filename */ + int pflags = 0; /* print suffixes */ + int addr, c, n; + const int addr_cnt = extract_addresses( ibufpp ); + + if( addr_cnt < 0 ) return ERR; + *ibufpp = skip_blanks( *ibufpp ); + c = *(*ibufpp)++; + switch( c ) + { + case 'a': if( !get_command_suffix( ibufpp, &pflags, 0 ) ) return ERR; + if( !isglobal ) clear_undo_stack(); + if( !append_lines( ibufpp, second_addr, false, isglobal ) ) + return ERR; + break; + case 'c': if( first_addr == 0 ) first_addr = 1; + if( second_addr == 0 ) second_addr = 1; + if( !check_addr_range2( addr_cnt ) || + !get_command_suffix( ibufpp, &pflags, 0 ) ) return ERR; + if( !isglobal ) clear_undo_stack(); + if( !delete_lines( first_addr, second_addr, isglobal ) || + !append_lines( ibufpp, current_addr(), + current_addr() >= first_addr, isglobal ) ) + return ERR; + break; + case 'd': if( !check_addr_range2( addr_cnt ) || + !get_command_suffix( ibufpp, &pflags, 0 ) ) return ERR; + if( !isglobal ) clear_undo_stack(); + if( !delete_lines( first_addr, second_addr, isglobal ) ) return ERR; + break; + case 'e': if( modified() && prev_status != EMOD ) return EMOD; + /* fall through */ + case 'E': if( unexpected_address( addr_cnt ) || + unexpected_command_suffix( **ibufpp ) ) return ERR; + fnp = get_filename( ibufpp, false ); + if( !fnp || !delete_lines( 1, last_addr(), isglobal ) || + !close_sbuf() ) return ERR; + if( !open_sbuf() ) return FATAL; + if( fnp[0] && fnp[0] != '!' ) set_def_filename( fnp ); + if( read_file( fnp[0] ? fnp : def_filename, 0 ) < 0 ) + return ERR; + reset_undo_state(); set_modified( false ); + break; + case 'f': if( unexpected_address( addr_cnt ) || + unexpected_command_suffix( **ibufpp ) ) return ERR; + fnp = get_filename( ibufpp, traditional() ); + if( !fnp ) return ERR; + if( fnp[0] == '!' ) + { set_error_msg( "Invalid redirection" ); return ERR; } + if( fnp[0] ) set_def_filename( fnp ); + printf( "%s\n", strip_escapes( def_filename ) ); + break; + case 'g': + case 'v': + case 'G': + case 'V': if( isglobal ) + { set_error_msg( "Cannot nest global commands" ); return ERR; } + n = ( c == 'g' || c == 'G' ); /* mark matching lines */ + if( !check_addr_range( 1, last_addr(), addr_cnt ) || + !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 ) ) || + !exec_global( ibufpp, pflags, n ) ) + return ERR; + break; + case 'h': + case 'H': if( unexpected_address( addr_cnt ) || + !get_command_suffix( ibufpp, &pflags, 0 ) ) 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; + 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; + 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 ) || + !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 ) || + !print_lines( first_addr, second_addr, pflags | n ) ) + return ERR; + pflags = 0; + break; + case 'm': if( !check_addr_range2( addr_cnt ) || + !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( !isglobal ) clear_undo_stack(); + if( !move_lines( first_addr, second_addr, addr, isglobal ) ) + return ERR; + break; + case 'P': + case 'q': + case 'Q': if( unexpected_address( addr_cnt ) || + !get_command_suffix( ibufpp, &pflags, 0 ) ) return ERR; + if( c == 'P' ) prompt_on = !prompt_on; + else if( c == 'q' && modified() && prev_status != EMOD ) + return EMOD; + else return QUIT; + break; + case 'r': if( unexpected_command_suffix( **ibufpp ) ) return ERR; + if( addr_cnt == 0 ) second_addr = last_addr(); + fnp = get_filename( ibufpp, false ); + if( !fnp ) return ERR; + if( !def_filename[0] && fnp[0] != '!' ) set_def_filename( fnp ); + if( !isglobal ) clear_undo_stack(); + addr = read_file( fnp[0] ? fnp : def_filename, second_addr ); + if( addr < 0 ) return ERR; + if( addr ) set_modified( true ); + break; + case 's': if( !command_s( ibufpp, &pflags, addr_cnt, isglobal ) ) + return ERR; + break; + case 't': if( !check_addr_range2( addr_cnt ) || + !get_third_addr( ibufpp, &addr ) || + !get_command_suffix( ibufpp, &pflags, 0 ) ) 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 ) || + !undo( isglobal ) ) return ERR; + break; + case 'w': + case 'W': n = **ibufpp; + if( n == 'q' || n == 'Q' ) ++*ibufpp; + if( unexpected_command_suffix( **ibufpp ) ) return ERR; + fnp = get_filename( ibufpp, false ); + if( !fnp ) return ERR; + if( addr_cnt == 0 && last_addr() == 0 ) + first_addr = second_addr = 0; + else if( !check_addr_range( 1, last_addr(), addr_cnt ) ) + return ERR; + if( !def_filename[0] && fnp[0] != '!' ) set_def_filename( fnp ); + addr = write_file( fnp[0] ? fnp : def_filename, + ( c == 'W' ) ? "a" : "w", first_addr, second_addr ); + if( addr < 0 ) return ERR; + if( addr == last_addr() && fnp[0] != '!' ) set_modified( false ); + else if( n == 'q' && modified() && prev_status != EMOD ) + return EMOD; + if( n == 'q' || n == 'Q' ) return QUIT; + 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( !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 ) || + !yank_lines( first_addr, second_addr ) ) return ERR; + break; + case 'z': if( !check_second_addr( current_addr() + !isglobal, addr_cnt ) ) + return ERR; + 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 ) || + !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; + printf( "%d\n", addr_cnt ? second_addr : last_addr() ); + break; + case '!': if( unexpected_address( addr_cnt ) ) return ERR; + fnp = get_shell_command( ibufpp ); + if( !fnp ) return ERR; + if( system( fnp + 1 ) < 0 ) + { set_error_msg( "Can't create shell process" ); return ERR; } + if( !scripted() ) fputs( "!\n", stdout ); + break; + case '\n': if( !check_second_addr( current_addr() + + ( traditional() || !isglobal ), addr_cnt ) || + !print_lines( second_addr, second_addr, 0 ) ) + return ERR; + break; + case '#': while( *(*ibufpp)++ != '\n' ) ; + break; + default : set_error_msg( "Unknown command" ); return ERR; + } + if( pflags && !print_lines( current_addr(), current_addr(), pflags ) ) + return ERR; + return 0; + } + + +/* apply command list in the command buffer to the active lines in a + range; return false if error */ +static bool exec_global( const char ** const ibufpp, const int pflags, + const bool interactive ) + { + static char * buf = 0; + static int bufsz = 0; + const char * cmd = 0; + + if( !interactive ) + { + if( traditional() && strcmp( *ibufpp, "\n" ) == 0 ) + cmd = "p\n"; /* null cmd_list == 'p' */ + else + { + if( !get_extended_line( ibufpp, 0, false ) ) return false; + cmd = *ibufpp; + } + } + clear_undo_stack(); + while( true ) + { + const line_t * const lp = next_active_node(); + if( !lp ) break; + set_current_addr( get_line_node_addr( lp ) ); + if( current_addr() < 0 ) return false; + if( interactive ) + { + /* print current_addr; get a command in global syntax */ + int len = 0; + if( !print_lines( current_addr(), current_addr(), pflags ) ) + return false; + *ibufpp = get_stdin_line( &len ); + if( !*ibufpp ) return false; /* error */ + if( len <= 0 ) return false; /* 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 false; } } + else + { + if( !get_extended_line( ibufpp, &len, false ) || + !resize_buffer( &buf, &bufsz, len + 1 ) ) return false; + memcpy( buf, *ibufpp, len + 1 ); + cmd = buf; + } + } + *ibufpp = cmd; + while( **ibufpp ) if( exec_command( ibufpp, 0, true ) < 0 ) return false; + } + return true; + } + + +static void script_error( void ) + { + if( verbose ) fprintf( stderr, "script, line %d: %s\n", linenum(), errmsg ); + } + + +int main_loop( const bool loose ) + { + extern jmp_buf jmp_state; + const char * ibufp; /* pointer to command buffer */ + volatile int err_status = 0; /* program exit status */ + int len = 0, status; + + disable_interrupts(); + set_signals(); + status = setjmp( jmp_state ); + if( !status ) enable_interrupts(); + else { status = -1; fputs( "\n?\n", stdout ); set_error_msg( "Interrupt" ); } + + while( true ) + { + fflush( stdout ); fflush( stderr ); + if( status < 0 && verbose ) { printf( "%s\n", errmsg ); fflush( stdout ); } + if( prompt_on ) { fputs( prompt_str, stdout ); fflush( stdout ); } + ibufp = get_stdin_line( &len ); + if( !ibufp ) return 2; /* an error happened */ + if( len <= 0 ) /* EOF on stdin ('q') */ + { + if( !modified() || status == EMOD ) status = QUIT; + else { status = EMOD; if( !loose ) err_status = 2; } + } + else status = exec_command( &ibufp, status, false ); + if( status == 0 ) continue; + if( status == QUIT ) return err_status; + fputs( "?\n", stdout ); /* give warning */ + if( !loose && err_status == 0 ) err_status = 1; + if( status == EMOD ) set_error_msg( "Warning: buffer modified" ); + if( is_regular_file( 0 ) ) + { script_error(); return ( ( status == FATAL ) ? 1 : err_status ); } + if( status == FATAL ) + { if( verbose ) { printf( "%s\n", errmsg ); } return 1; } + } + } diff --git a/red.in b/red.in new file mode 100644 index 0000000..5e147db --- /dev/null +++ b/red.in @@ -0,0 +1,3 @@ +#! /bin/sh +bindir=`echo "$0" | sed -e 's,[^/]*$,,'` +exec "${bindir}"ed --restricted "$@" diff --git a/regex.c b/regex.c new file mode 100644 index 0000000..15e3323 --- /dev/null +++ b/regex.c @@ -0,0 +1,394 @@ +/* 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-2017 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 + 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, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . +*/ + +#include +#include +#include +#include +#include +#include +#include + +#include "ed.h" + + +static regex_t * subst_regex_ = 0; /* regex of previous substitution */ + +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; } + + +/* translate characters in a string */ +static void translit_text( char * p, int len, const char from, const char to ) + { + while( --len >= 0 ) + { + if( *p == from ) *p = to; + ++p; + } + } + + +/* overwrite newlines with ASCII NULs */ +static void newline_to_nul( char * const s, const int len ) + { translit_text( s, len, '\n', '\0' ); } + +/* overwrite ASCII NULs with newlines */ +static void nul_to_newline( char * const s, const int len ) + { translit_text( s, len, '\0', '\n' ); } + + +/* expand a POSIX character class */ +static const char * parse_char_class( const char * p ) + { + char c, d; + + if( *p == '^' ) ++p; + if( *p == ']' ) ++p; + for( ; *p != ']' && *p != '\n'; ++p ) + if( *p == '[' && ( ( d = p[1] ) == '.' || d == ':' || d == '=' ) ) + for( ++p, c = *++p; *p != ']' || c != d; ++p ) + if( ( c = *p ) == '\n' ) + return 0; + return ( ( *p == ']' ) ? p : 0 ); + } + + +/* copy a pattern string from the command buffer; return pointer to the copy */ +static char * extract_pattern( const char ** const ibufpp, const char delimiter ) + { + static char * buf = 0; + static int bufsz = 0; + const char * nd = *ibufpp; + int len; + + while( *nd != delimiter && *nd != '\n' ) + { + if( *nd == '[' ) + { + nd = parse_char_class( ++nd ); + if( !nd ) { set_error_msg( "Unbalanced brackets ([])" ); return 0; } + } + else if( *nd == '\\' && *++nd == '\n' ) + { set_error_msg( "Trailing backslash (\\)" ); return 0; } + ++nd; + } + len = nd - *ibufpp; + if( !resize_buffer( &buf, &bufsz, len + 1 ) ) return 0; + memcpy( buf, *ibufpp, len ); + buf[len] = 0; + *ibufpp = nd; + if( isbinary() ) nul_to_newline( buf, len ); + return buf; + } + + +/* 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 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( "Invalid pattern delimiter" ); return 0; } + if( delimiter == '\n' || *++*ibufpp == delimiter || + ( **ibufpp == '\n' && !test_delimiter ) ) + { + if( !exp ) set_error_msg( "No previous pattern" ); + return exp; + } + 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, 0 ); + if( n ) + { + char buf[80]; + regerror( n, exp, buf, sizeof buf ); + set_error_msg( buf ); + exp = 0; + } + return exp; + } + + +bool set_subst_regex( const char ** const ibufpp ) + { + regex_t * exp; + + disable_interrupts(); + exp = get_compiled_regex( ibufpp, true ); + if( exp && exp != subst_regex_ ) + { + if( subst_regex_ ) regfree( subst_regex_ ); + subst_regex_ = exp; + } + enable_interrupts(); + return ( exp ? true : false ); + } + + +/* add line 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( "Invalid pattern delimiter" ); return false; } + exp = get_compiled_regex( ibufpp, false ); + if( !exp ) return false; + if( **ibufpp == delimiter ) ++*ibufpp; + clear_active_list(); + 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 ); + if( !s ) return false; + if( isbinary() ) nul_to_newline( s, lp->len ); + if( match == !regexec( exp, s, 0, 0, 0 ) && !set_active_node( lp ) ) + return false; + } + return true; + } + + +/* 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 ) + { + const regex_t * const exp = get_compiled_regex( ibufpp, false ); + int addr = current_addr(); + + if( !exp ) return -1; + do { + addr = ( forward ? inc_addr( addr ) : dec_addr( addr ) ); + if( addr ) + { + const line_t * const lp = search_line_node( addr ); + char * const s = get_sbuf_line( lp ); + if( !s ) return -1; + if( isbinary() ) nul_to_newline( s, lp->len ); + if( !regexec( exp, s, 0, 0, 0 ) ) return addr; + } + } + while( addr != current_addr() ); + set_error_msg( "No match" ); + return -1; + } + + +/* extract substitution replacement from the command buffer */ +bool extract_replacement( const char ** const ibufpp, const bool isglobal ) + { + static char * buf = 0; /* temporary buffer */ + static int bufsz = 0; + int i = 0; + const char delimiter = **ibufpp; + + if( delimiter == '\n' ) + { set_error_msg( "Missing pattern delimiter" ); return false; } + ++*ibufpp; + if( **ibufpp == '%' && ( (*ibufpp)[1] == delimiter || (*ibufpp)[1] == '\n' ) ) + { + ++*ibufpp; + if( !rbuf ) { set_error_msg( "No previous substitution" ); return false; } + return true; + } + while( **ibufpp != delimiter ) + { + if( **ibufpp == '\n' ) + { + if( isglobal && (*ibufpp)[1] != 0 ) + { set_error_msg( "Invalid newline substitution" ); return false; } + break; + } + if( !resize_buffer( &buf, &bufsz, i + 2 ) ) return false; + if( ( buf[i++] = *(*ibufpp)++ ) == '\\' && + ( buf[i++] = *(*ibufpp)++ ) == '\n' && !isglobal ) + { + /* not reached if isglobal; in command-list, newlines are unescaped */ + int size = 0; + *ibufpp = get_stdin_line( &size ); + if( !*ibufpp ) return false; /* error */ + if( size <= 0 ) return false; /* EOF */ + } + } + /* make sure that buf gets allocated if empty replacement */ + if( !resize_buffer( &buf, &bufsz, i + 1 ) ) return false; + buf[i] = 0; + disable_interrupts(); + { char * p = buf; buf = rbuf; rbuf = p; /* swap buffers */ + rlen = i; i = bufsz; bufsz = rbufsz; rbufsz = i; } + enable_interrupts(); + return true; + } + + +/* Produce replacement text from matched text and replacement template. + Return new offset to end of replacement text, or -1 if error. */ +static int replace_matched_text( char ** txtbufp, int * const txtbufszp, + const char * const txt, + const regmatch_t * const rm, int offset, + const int re_nsub ) + { + const char * sub = rbuf; + + for( ; sub - rbuf < rlen; ++sub ) + { + int n; + if( *sub == '&' ) + { + int j = rm[0].rm_so; int k = rm[0].rm_eo; + if( !resize_buffer( txtbufp, txtbufszp, offset + k - j ) ) return -1; + while( j < k ) (*txtbufp)[offset++] = txt[j++]; + } + else if( *sub == '\\' && *++sub >= '1' && *sub <= '9' && + ( n = *sub - '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; + while( j < k ) (*txtbufp)[offset++] = txt[j++]; + } + else + { + if( !resize_buffer( txtbufp, txtbufszp, offset + 1 ) ) return -1; + (*txtbufp)[offset++] = *sub; + } + } + if( !resize_buffer( txtbufp, txtbufszp, offset + 1 ) ) return -1; + (*txtbufp)[offset] = 0; + return offset; + } + + +/* Produce new text with one or all matches replaced in a line. + Return size of the new line text, 0 if no change, -1 if error */ +static int line_replace( char ** txtbufp, int * const txtbufszp, + const line_t * const lp, const int snum ) + { + enum { se_max = 30 }; /* max subexpressions in a regular expression */ + regmatch_t rm[se_max]; + char * txt = get_sbuf_line( lp ); + const char * eot; + int i = 0, offset = 0; + const bool global = ( snum <= 0 ); + bool changed = false; + + 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 ) ) + { + int matchno = 0; + do { + if( global || snum == ++matchno ) + { + changed = true; i = rm[0].rm_so; + if( !resize_buffer( txtbufp, txtbufszp, offset + i ) ) return -1; + 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 ); + if( offset < 0 ) return -1; + } + else + { + i = rm[0].rm_eo; + if( !resize_buffer( txtbufp, txtbufszp, offset + i ) ) return -1; + if( isbinary() ) newline_to_nul( txt, i ); + memcpy( *txtbufp + offset, txt, i ); offset += i; + } + txt += rm[0].rm_eo; + } + while( *txt && ( !changed || ( global && rm[0].rm_eo ) ) && + !regexec( subst_regex_, txt, se_max, rm, REG_NOTBOL ) ); + i = eot - txt; + if( !resize_buffer( txtbufp, txtbufszp, offset + i + 2 ) ) return -1; + if( global && i > 0 && !rm[0].rm_eo ) + { set_error_msg( "Infinite substitution loop" ); return -1; } + if( isbinary() ) newline_to_nul( txt, i ); + memcpy( *txtbufp + offset, txt, i ); /* tail copy */ + memcpy( *txtbufp + offset + i, "\n", 2 ); + } + return ( changed ? offset + i + 1 : 0 ); + } + + +/* for each line in a range, change text matching a regular expression + according to a substitution template (replacement); return false if error */ +bool search_and_replace( const int first_addr, const int second_addr, + const int snum, const bool isglobal ) + { + static char * txtbuf = 0; /* new text of line buffer */ + static int txtbufsz = 0; /* new text of line buffer size */ + int addr = first_addr; + int lc; + bool match_found = false; + + for( lc = 0; lc <= second_addr - first_addr; ++lc, ++addr ) + { + const line_t * const lp = search_line_node( addr ); + const int size = line_replace( &txtbuf, &txtbufsz, lp, snum ); + if( size < 0 ) return false; + if( size ) + { + const char * txt = txtbuf; + const char * const eot = txtbuf + size; + undo_t * up = 0; + disable_interrupts(); + if( !delete_lines( addr, addr, isglobal ) ) + { enable_interrupts(); return false; } + set_current_addr( addr - 1 ); + do { + txt = put_sbuf_line( txt, eot - txt ); + if( !txt ) { enable_interrupts(); return false; } + if( up ) up->tail = search_line_node( current_addr() ); + else + { + up = push_undo_atom( UADD, current_addr(), current_addr() ); + if( !up ) { enable_interrupts(); return false; } + } + } + while( txt != eot ); + enable_interrupts(); + addr = current_addr(); + match_found = true; + } + } + if( !match_found && !isglobal ) + { set_error_msg( "No match" ); return false; } + return true; + } diff --git a/signal.c b/signal.c new file mode 100644 index 0000000..6d7fcdb --- /dev/null +++ b/signal.c @@ -0,0 +1,264 @@ +/* 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-2017 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 + 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, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . +*/ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "ed.h" + + +jmp_buf jmp_state; +static int mutex = 0; /* If > 0, signals stay pending */ +static int window_lines_ = 22; /* scroll lines set by sigwinch_handler */ +static int window_columns_ = 72; +static bool sighup_pending = false; +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 ); + } + } + + +static void sigint_handler( int signum ) + { + if( mutex ) sigint_pending = true; + else + { + sigset_t set; + sigint_pending = false; + sigemptyset( &set ); + sigaddset( &set, signum ); + sigprocmask( SIG_UNBLOCK, &set, 0 ); + longjmp( jmp_state, -1 ); + } + } + + +static void sigwinch_handler( int signum ) + { +#ifdef TIOCGWINSZ + struct winsize ws; /* window size structure */ + + if( ioctl( 0, TIOCGWINSZ, (char *) &ws ) >= 0 ) + { + /* Sanity check values of environment vars */ + if( ws.ws_row > 2 && ws.ws_row < 600 ) window_lines_ = ws.ws_row - 2; + if( ws.ws_col > 8 && ws.ws_col < 1800 ) window_columns_ = ws.ws_col - 8; + } +#endif + if( signum ) {} /* keep compiler happy */ + } + + +static int set_signal( const int signum, void (*handler)( int ) ) + { + struct sigaction new_action; + + new_action.sa_handler = handler; + sigemptyset( &new_action.sa_mask ); +#ifdef SA_RESTART + new_action.sa_flags = SA_RESTART; +#else + new_action.sa_flags = 0; +#endif + return sigaction( signum, &new_action, 0 ); + } + + +void enable_interrupts( void ) + { + if( --mutex <= 0 ) + { + mutex = 0; + if( sighup_pending ) sighup_handler( SIGHUP ); + if( sigint_pending ) sigint_handler( SIGINT ); + } + } + + +void disable_interrupts( void ) { ++mutex; } + + +void set_signals( void ) + { +#ifdef SIGWINCH + sigwinch_handler( SIGWINCH ); + if( isatty( 0 ) ) set_signal( SIGWINCH, sigwinch_handler ); +#endif + set_signal( SIGHUP, sighup_handler ); + set_signal( SIGQUIT, SIG_IGN ); + set_signal( SIGINT, sigint_handler ); + } + + +void set_window_lines( const int lines ) { window_lines_ = lines; } +int window_columns( void ) { return window_columns_; } +int window_lines( void ) { return window_lines_; } + + +/* convert a string to int with out_of_range detection */ +bool parse_int( int * const i, const char * const str, const char ** const tail ) + { + char * tmp; + long li; + + errno = 0; + *i = li = strtol( str, &tmp, 10 ); + if( tail ) *tail = tmp; + if( tmp == str ) + { + set_error_msg( "Bad numerical result" ); + *i = 0; + return false; + } + if( errno == ERANGE || li > INT_MAX || li < -INT_MAX ) + { + set_error_msg( "Numerical result out of range" ); + *i = 0; + return false; + } + return true; + } + + +/* assure at least a minimum size for buffer 'buf' */ +bool resize_buffer( char ** const buf, int * const size, const int min_size ) + { + if( *size < min_size ) + { + const int new_size = ( min_size < 512 ? 512 : ( 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( "Memory exhausted" ); + enable_interrupts(); + return false; + } + *size = new_size; + *buf = (char *)new_buf; + enable_interrupts(); + } + return true; + } + + +/* assure at least a minimum size for buffer 'buf' */ +bool resize_line_buffer( const line_t *** const buf, int * const size, + const int min_size ) + { + if( *size < min_size ) + { + const int new_size = ( min_size < 512 ? 512 : ( 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( "Memory exhausted" ); + enable_interrupts(); + return false; + } + *size = new_size; + *buf = (const line_t **)new_buf; + enable_interrupts(); + } + return true; + } + + +/* assure at least a minimum size for buffer 'buf' */ +bool resize_undo_buffer( undo_t ** const buf, int * const size, + const int min_size ) + { + if( *size < min_size ) + { + const int new_size = ( min_size < 512 ? 512 : ( 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( "Memory exhausted" ); + enable_interrupts(); + return false; + } + *size = new_size; + *buf = (undo_t *)new_buf; + enable_interrupts(); + } + return true; + } + + +/* return unescaped copy of escaped string */ +const char * strip_escapes( const char * p ) + { + static char * buf = 0; + static int bufsz = 0; + const int len = strlen( p ); + int i = 0; + + if( !resize_buffer( &buf, &bufsz, len + 1 ) ) return 0; + /* assert: no trailing escape */ + while( ( buf[i++] = ( (*p == '\\' ) ? *++p : *p ) ) ) + ++p; + return buf; + } diff --git a/testsuite/a.ed b/testsuite/a.ed new file mode 100644 index 0000000..314edc3 --- /dev/null +++ b/testsuite/a.ed @@ -0,0 +1,37 @@ +H +# empty append at address 0 should set the current address to 0 +0a +. ++4a +# this is not a comment +. +# empty append at current address should not modify the current address +a +. +a +hello world! +. +a +hello world!! +. +0a +hello world!!! +. +!read one # shell escape should not modify the current address +text for the read shell command above +a +shell escape marker +. +$a +hello world!!!! +. +u +u +a +hello world!!!!! +. +a +to be undone +. +u +w out.o diff --git a/testsuite/a.err b/testsuite/a.err new file mode 100644 index 0000000..7d6029a --- /dev/null +++ b/testsuite/a.err @@ -0,0 +1,5 @@ +H +ag +hello world +. +w out.ro diff --git a/testsuite/a.r b/testsuite/a.r new file mode 100644 index 0000000..9434d34 --- /dev/null +++ b/testsuite/a.r @@ -0,0 +1,20 @@ +hello world!!! +shell escape marker +This natural inequality of the two powers of population and of +production in the earth, and that great law of our nature which must +constantly keep their effects equal, form the great difficulty that to +me appears insurmountable in the way to the perfectibility of society. +# this is not a comment +hello world! +hello world!! +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 +of this law which pervades all animated nature. No fancied equality, no +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 +which should live in ease, happiness, and comparative leisure; and feel +no anxiety about providing the means of subsistence for themselves and +their families. +hello world!!!! +hello world!!!!! diff --git a/testsuite/addr1.err b/testsuite/addr1.err new file mode 100644 index 0000000..7b40b33 --- /dev/null +++ b/testsuite/addr1.err @@ -0,0 +1,3 @@ +H +100 +w out.ro diff --git a/testsuite/addr2.err b/testsuite/addr2.err new file mode 100644 index 0000000..da4ffa9 --- /dev/null +++ b/testsuite/addr2.err @@ -0,0 +1,3 @@ +H +-100 +w out.ro diff --git a/testsuite/addr3.err b/testsuite/addr3.err new file mode 100644 index 0000000..e5a7fb7 --- /dev/null +++ b/testsuite/addr3.err @@ -0,0 +1,3 @@ +H +0p +w out.ro diff --git a/testsuite/addr4.err b/testsuite/addr4.err new file mode 100644 index 0000000..7f4f4ac --- /dev/null +++ b/testsuite/addr4.err @@ -0,0 +1,3 @@ +H +2,1p +w out.ro diff --git a/testsuite/bang1.err b/testsuite/bang1.err new file mode 100644 index 0000000..afce43f --- /dev/null +++ b/testsuite/bang1.err @@ -0,0 +1,3 @@ +H +.!date +w out.ro diff --git a/testsuite/bang2.err b/testsuite/bang2.err new file mode 100644 index 0000000..3493119 --- /dev/null +++ b/testsuite/bang2.err @@ -0,0 +1,3 @@ +H +!! +w out.ro diff --git a/testsuite/c.ed b/testsuite/c.ed new file mode 100644 index 0000000..98b8a3b --- /dev/null +++ b/testsuite/c.ed @@ -0,0 +1,25 @@ +H +0c +at the top +. +4c +in the middle +. +5c +. +c +after the middle +. +$c +at the bottom +. +u +u +-5,10c +between middle/bottom +. +c +to be undone +. +u +w out.o diff --git a/testsuite/c.err b/testsuite/c.err new file mode 100644 index 0000000..2775d49 --- /dev/null +++ b/testsuite/c.err @@ -0,0 +1,5 @@ +H +c0 +hello world +. +w out.ro diff --git a/testsuite/c.r b/testsuite/c.r new file mode 100644 index 0000000..4fc5e90 --- /dev/null +++ b/testsuite/c.r @@ -0,0 +1,9 @@ +at the top +production in the earth, and that great law of our nature which must +constantly keep their effects equal, form the great difficulty that to +in the middle +after the middle +of this law which pervades all animated nature. No fancied equality, no +between middle/bottom +no anxiety about providing the means of subsistence for themselves and +at the bottom diff --git a/testsuite/check.sh b/testsuite/check.sh new file mode 100755 index 0000000..1be15e1 --- /dev/null +++ b/testsuite/check.sh @@ -0,0 +1,102 @@ +#! /bin/sh +# check script for GNU ed - The GNU line editor +# Copyright (C) 2006-2017 Antonio Diaz Diaz. +# +# This script is free software; you have unlimited permission +# to copy, distribute and modify it. + +LC_ALL=C +export LC_ALL +objdir=`pwd` +testdir=`cd "$1" ; pwd` +ED="${objdir}"/ed +framework_failure() { echo "failure in testing framework" ; exit 1 ; } + +if [ ! -f "${ED}" ] || [ ! -x "${ED}" ] ; then + echo "${ED}: cannot execute" + exit 1 +fi + +if [ -d tmp ] ; then rm -rf tmp ; fi +mkdir tmp +cd "${objdir}"/tmp || framework_failure + +cat "${testdir}"/test.txt > test.txt || framework_failure +cat "${testdir}"/test.bin > test.bin || framework_failure +touch zero || framework_failure +fail=0 + +printf "testing ed-%s...\n" "$2" + +# Run the .err scripts first with a regular file connected to standard +# input, since these don't generate output; they exit with non-zero status. +for i in "${testdir}"/*.err ; do + if "${ED}" -s test.txt < "$i" > /dev/null 2>&1 ; then + echo "*** The script $i exited abnormally ***" + fail=127 + fi +done + +# Run the .err scripts again with a regular file connected to standard +# input, but with '--loose-exit-status'; they should exit with zero status. +for i in "${testdir}"/*.err ; do + if "${ED}" -sl test.txt < "$i" > /dev/null 2>&1 ; then + true + else + echo "*** The script $i failed '--loose-exit-status' ***" + fail=127 + fi +done + +# Run the .err scripts again as pipes - these should exit with non-zero +# status without altering the contents of the buffer; the produced +# 'out.ro' must be identical to 'test.txt'. +for i in "${testdir}"/*.err ; do + base=`echo "$i" | sed 's,^.*/,,;s,\.err$,,'` # remove dir and ext + if cat "$i" | "${ED}" -s test.txt > /dev/null 2>&1 ; then + echo "*** The piped script $i exited abnormally ***" + fail=127 + else + if cmp -s out.ro test.txt ; then + true + else + mv -f out.ro ${base}.ro + echo "*** Output ${base}.ro of piped script $i is incorrect ***" + fail=127 + fi + fi + rm -f out.ro +done + +# Run the .ed scripts and compare their output against the .r files, +# which contain the correct output. +# The .ed scripts should exit with zero status. +for i in "${testdir}"/*.ed ; do + base=`echo "$i" | sed 's,^.*/,,;s,\.ed$,,'` # remove dir and ext + if "${ED}" -s test.txt < "$i" > /dev/null 2> out.log ; then + if cmp -s out.o "${testdir}"/${base}.r ; then + true + else + mv -f out.o ${base}.o + echo "*** Output ${base}.o of script $i is incorrect ***" + fail=127 + fi + else + mv -f out.log ${base}.log + echo "*** The script $i exited abnormally ***" + fail=127 + fi + rm -f out.o out.log +done + +rm -f test.txt test.bin zero + +if [ ${fail} = 0 ] ; then + echo "tests completed successfully." + cd "${objdir}" && rm -r tmp +else + echo "tests failed." + echo "Please, send a bug report to bug-ed@gnu.org." + echo "Include the (compressed) contents of '${objdir}/tmp' in the report." +fi +exit ${fail} diff --git a/testsuite/d.ed b/testsuite/d.ed new file mode 100644 index 0000000..0312989 --- /dev/null +++ b/testsuite/d.ed @@ -0,0 +1,12 @@ +H +2 d +. d +$ d +-5 d +u +u ++3,+4d +# to be undone +1,$d +u +w out.o diff --git a/testsuite/d.err b/testsuite/d.err new file mode 100644 index 0000000..16cbbba --- /dev/null +++ b/testsuite/d.err @@ -0,0 +1,3 @@ +H +d1 +w out.ro diff --git a/testsuite/d.r b/testsuite/d.r new file mode 100644 index 0000000..59e352f --- /dev/null +++ b/testsuite/d.r @@ -0,0 +1,7 @@ +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/e1.ed b/testsuite/e1.ed new file mode 100644 index 0000000..61d8f52 --- /dev/null +++ b/testsuite/e1.ed @@ -0,0 +1,3 @@ +H +e test.bin +w out.o diff --git a/testsuite/e1.err b/testsuite/e1.err new file mode 100644 index 0000000..2b7728c --- /dev/null +++ b/testsuite/e1.err @@ -0,0 +1,3 @@ +H +ee test.bin +w out.ro diff --git a/testsuite/e1.r b/testsuite/e1.r new file mode 100644 index 0000000..c866266 Binary files /dev/null and b/testsuite/e1.r differ diff --git a/testsuite/e2.ed b/testsuite/e2.ed new file mode 100644 index 0000000..73b8253 --- /dev/null +++ b/testsuite/e2.ed @@ -0,0 +1,4 @@ +H +f test.bin +e +w out.o diff --git a/testsuite/e2.err b/testsuite/e2.err new file mode 100644 index 0000000..06e88ec --- /dev/null +++ b/testsuite/e2.err @@ -0,0 +1,3 @@ +H +.e test.bin +w out.ro diff --git a/testsuite/e2.r b/testsuite/e2.r new file mode 100644 index 0000000..c866266 Binary files /dev/null and b/testsuite/e2.r differ diff --git a/testsuite/e3.ed b/testsuite/e3.ed new file mode 100644 index 0000000..36ca4ac --- /dev/null +++ b/testsuite/e3.ed @@ -0,0 +1,5 @@ +H +e test.bin +1d +E !cat test.bin +w out.o diff --git a/testsuite/e3.err b/testsuite/e3.err new file mode 100644 index 0000000..6d36baa --- /dev/null +++ b/testsuite/e3.err @@ -0,0 +1,3 @@ +H +etest.bin +w out.ro diff --git a/testsuite/e3.r b/testsuite/e3.r new file mode 100644 index 0000000..c866266 Binary files /dev/null and b/testsuite/e3.r differ diff --git a/testsuite/e4.ed b/testsuite/e4.ed new file mode 100644 index 0000000..5ce96b7 --- /dev/null +++ b/testsuite/e4.ed @@ -0,0 +1,5 @@ +H +e test.bin +# modifying the last line of a binary file adds a newline +$s/x/x/ +w out.o diff --git a/testsuite/e4.r b/testsuite/e4.r new file mode 100644 index 0000000..fb695e1 Binary files /dev/null and b/testsuite/e4.r differ diff --git a/testsuite/e5.ed b/testsuite/e5.ed new file mode 100644 index 0000000..5c548be --- /dev/null +++ b/testsuite/e5.ed @@ -0,0 +1,7 @@ +H +e test.bin +# modifying the last line of a binary file adds a newline +$s/x/x/ +# but undo restores the line to its previous state +u +w out.o diff --git a/testsuite/e5.r b/testsuite/e5.r new file mode 100644 index 0000000..c866266 Binary files /dev/null and b/testsuite/e5.r differ diff --git a/testsuite/f1.err b/testsuite/f1.err new file mode 100644 index 0000000..00c37e2 --- /dev/null +++ b/testsuite/f1.err @@ -0,0 +1,3 @@ +H +.f test.bin +w out.ro diff --git a/testsuite/f2.err b/testsuite/f2.err new file mode 100644 index 0000000..b35cc86 --- /dev/null +++ b/testsuite/f2.err @@ -0,0 +1,3 @@ +H +ftest.bin +w out.ro diff --git a/testsuite/g.ed b/testsuite/g.ed new file mode 100644 index 0000000..eefe72f --- /dev/null +++ b/testsuite/g.ed @@ -0,0 +1,32 @@ +H +g/./m0 +g//a\ +hello world +# lines beginning with a `#' should be ignored +g/hello /# including in global commands \ +s/lo/p!/\ +a\ +order\ +.\ +# and in the command list \ +i\ +caos\ +.\ +-1s/l/L +u +u +17,33g/[A-I]/-1d\ ++1c\ +hello world\ +.\ +47 +;d +# don't change current address if no match +g/xxx/1d +;j +g/heLp! world//caos/d\ +-;/order/;d +# to be undone +g/./s//x/g +u +w out.o diff --git a/testsuite/g.r b/testsuite/g.r new file mode 100644 index 0000000..a50255d --- /dev/null +++ b/testsuite/g.r @@ -0,0 +1,28 @@ +their families. +heLp! world +no anxiety about providing the means of subsistence for themselves and +heLp! world +which should live in ease, happiness, and comparative leisure; and feel +heLp! world +decisive against the possible existence of a society, all the members of +heLp! world +of it even for a single century. And it appears, therefore, to be +hello world +caos +agrarian regulations in their utmost extent, could remove the pressure +heLp! world +of this law which pervades all animated nature. No fancied equality, no +heLp! world +comparison of this. I see no way by which man can escape from the weight +hello world +caos +All other arguments are of slight and subordinate consideration in +hello world +caos +me appears insurmountable in the way to the perfectibility of society. +heLp! world +constantly keep their effects equal, form the great difficulty that to +heLp! world +production in the earth, and that great law of our nature which must +heLp! world +This natural inequality of the two powers of population and of diff --git a/testsuite/g1.err b/testsuite/g1.err new file mode 100644 index 0000000..70da494 --- /dev/null +++ b/testsuite/g1.err @@ -0,0 +1,3 @@ +H +g +w out.ro diff --git a/testsuite/g2.err b/testsuite/g2.err new file mode 100644 index 0000000..698103d --- /dev/null +++ b/testsuite/g2.err @@ -0,0 +1,3 @@ +H +g//d +w out.ro diff --git a/testsuite/g3.err b/testsuite/g3.err new file mode 100644 index 0000000..2f5ca12 --- /dev/null +++ b/testsuite/g3.err @@ -0,0 +1,3 @@ +H +g/./s //x/ +w out.ro diff --git a/testsuite/g4.err b/testsuite/g4.err new file mode 100644 index 0000000..8797183 --- /dev/null +++ b/testsuite/g4.err @@ -0,0 +1,7 @@ +H +# newlines in replacement are ambiguous; last delimiter can't be omitted +g/./s/y/y\ +f text.bin +# the previous s command should not set replacement +s/./%/ +w out.ro diff --git a/testsuite/h.err b/testsuite/h.err new file mode 100644 index 0000000..02c6d23 --- /dev/null +++ b/testsuite/h.err @@ -0,0 +1,3 @@ +H +.h +w out.ro diff --git a/testsuite/i.ed b/testsuite/i.ed new file mode 100644 index 0000000..579c0ff --- /dev/null +++ b/testsuite/i.ed @@ -0,0 +1,37 @@ +H +# empty insert at address 0 should set the current address to 0 +0i +. ++4i +# this is not a comment +. +# empty insert at current address should not modify the current address +i +. +i +hello world! +. +i +hello world!! +. +0i +hello world!!! +. +i + +second line + +. +$i +hello world!!!! +. +u +u +i +hello world!!!!! +. +i +to be undone +. +u +w out.o diff --git a/testsuite/i.err b/testsuite/i.err new file mode 100644 index 0000000..47073f6 --- /dev/null +++ b/testsuite/i.err @@ -0,0 +1,5 @@ +H +ii +hello world +. +w out.ro diff --git a/testsuite/i.r b/testsuite/i.r new file mode 100644 index 0000000..e1a20ba --- /dev/null +++ b/testsuite/i.r @@ -0,0 +1,22 @@ + +second line + +hello world!!! +This natural inequality of the two powers of population and of +production in the earth, and that great law of our nature which must +constantly keep their effects equal, form the great difficulty that to +hello world!! +hello world! +# this is not a comment +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 +of this law which pervades all animated nature. No fancied equality, no +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 +which should live in ease, happiness, and comparative leisure; and feel +no anxiety about providing the means of subsistence for themselves and +hello world!!!!! +hello world!!!! +their families. diff --git a/testsuite/j.ed b/testsuite/j.ed new file mode 100644 index 0000000..4827cb5 --- /dev/null +++ b/testsuite/j.ed @@ -0,0 +1,14 @@ +H +2,3j +j +7 +u +u +3j +j +3,3j +j +# to be undone +1,$j +u +w out.o diff --git a/testsuite/j.r b/testsuite/j.r new file mode 100644 index 0000000..5eef11c --- /dev/null +++ b/testsuite/j.r @@ -0,0 +1,9 @@ +This natural inequality of the two powers of population and of +production in the earth, and that great law of our nature which mustconstantly keep their effects equal, form the great difficulty that tome 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 +of this law which pervades all animated nature. No fancied equality, no +agrarian regulations in their utmost extent, could remove the pressure +of it even for a single century. And it appears, therefore, to bedecisive against the possible existence of a society, all the members ofwhich should live in ease, happiness, and comparative leisure; and feel +no anxiety about providing the means of subsistence for themselves and +their families. diff --git a/testsuite/k.ed b/testsuite/k.ed new file mode 100644 index 0000000..493759e --- /dev/null +++ b/testsuite/k.ed @@ -0,0 +1,12 @@ +H +7l +2ka +4kb +9kc +13kd +i +hello world +. +'a,'bd +'c,'dd +w out.o diff --git a/testsuite/k.r b/testsuite/k.r new file mode 100644 index 0000000..ab1a79e --- /dev/null +++ b/testsuite/k.r @@ -0,0 +1,6 @@ +This natural inequality of the two powers of population and of +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 +hello world +of this law which pervades all animated nature. No fancied equality, no +agrarian regulations in their utmost extent, could remove the pressure diff --git a/testsuite/k1.err b/testsuite/k1.err new file mode 100644 index 0000000..bde56ce --- /dev/null +++ b/testsuite/k1.err @@ -0,0 +1,8 @@ +H +a +hello +. +.ka +'ad +'ap +w out.ro diff --git a/testsuite/k2.err b/testsuite/k2.err new file mode 100644 index 0000000..dfca298 --- /dev/null +++ b/testsuite/k2.err @@ -0,0 +1,3 @@ +H +kA +w out.ro diff --git a/testsuite/k3.err b/testsuite/k3.err new file mode 100644 index 0000000..f59619f --- /dev/null +++ b/testsuite/k3.err @@ -0,0 +1,3 @@ +H +0ka +w out.ro diff --git a/testsuite/m.err b/testsuite/m.err new file mode 100644 index 0000000..a5260ec --- /dev/null +++ b/testsuite/m.err @@ -0,0 +1,3 @@ +H +1,$m5 +w out.ro diff --git a/testsuite/m_addr.ed b/testsuite/m_addr.ed new file mode 100644 index 0000000..28c77e5 --- /dev/null +++ b/testsuite/m_addr.ed @@ -0,0 +1,20 @@ +H +3 ---- 2,1 2 3m;,,;; +-2,.m7 +. ++,+++m. +-1,m. +.-4m-2 +-2m-1 +1,2;3,4,$;5,6,7 +;.m0 +u +u ++;m7 +-m-6 ++1m+4 +-3m?all? +/their/-m-2 +# to be undone +,1m$ +u +,w out.o diff --git a/testsuite/m_addr.r b/testsuite/m_addr.r new file mode 100644 index 0000000..5051d68 --- /dev/null +++ b/testsuite/m_addr.r @@ -0,0 +1,13 @@ +their families. +no anxiety about providing the means of subsistence for themselves and +which should live in ease, happiness, and comparative leisure; and feel +decisive against the possible existence of a society, all the members of +of it even for a single century. And it appears, therefore, to be +agrarian regulations in their utmost extent, could remove the pressure +of this law which pervades all animated nature. No fancied equality, no +comparison of this. I see no way by which man can escape from the weight +All other arguments are of slight and subordinate consideration in +me appears insurmountable in the way to the perfectibility of society. +constantly keep their effects equal, form the great difficulty that to +production in the earth, and that great law of our nature which must +This natural inequality of the two powers of population and of diff --git a/testsuite/p1.err b/testsuite/p1.err new file mode 100644 index 0000000..9791c80 --- /dev/null +++ b/testsuite/p1.err @@ -0,0 +1,3 @@ +H +ppp +w out.ro diff --git a/testsuite/p2.err b/testsuite/p2.err new file mode 100644 index 0000000..056c914 --- /dev/null +++ b/testsuite/p2.err @@ -0,0 +1,3 @@ +H +.P +w out.ro diff --git a/testsuite/q.ed b/testsuite/q.ed new file mode 100644 index 0000000..eb98c7d --- /dev/null +++ b/testsuite/q.ed @@ -0,0 +1,7 @@ +H +w out.o +a +hello +. +Q +w out.o diff --git a/testsuite/q.r b/testsuite/q.r new file mode 100644 index 0000000..f707ae0 --- /dev/null +++ b/testsuite/q.r @@ -0,0 +1,13 @@ +This natural inequality of the two powers of population and of +production in the earth, and that great law of our nature which must +constantly keep their effects equal, form the great difficulty that to +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 +of this law which pervades all animated nature. No fancied equality, no +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 +which should live in ease, happiness, and comparative leisure; and feel +no anxiety about providing the means of subsistence for themselves and +their families. diff --git a/testsuite/q1.err b/testsuite/q1.err new file mode 100644 index 0000000..dd1066f --- /dev/null +++ b/testsuite/q1.err @@ -0,0 +1,3 @@ +H +.q +w out.ro diff --git a/testsuite/q2.err b/testsuite/q2.err new file mode 100644 index 0000000..ca2939e --- /dev/null +++ b/testsuite/q2.err @@ -0,0 +1,3 @@ +H +.Q +w out.ro diff --git a/testsuite/q3.err b/testsuite/q3.err new file mode 100644 index 0000000..fbe1aa8 --- /dev/null +++ b/testsuite/q3.err @@ -0,0 +1,6 @@ +H +w out.ro +a +hello +. +q diff --git a/testsuite/q4.err b/testsuite/q4.err new file mode 100644 index 0000000..2510100 --- /dev/null +++ b/testsuite/q4.err @@ -0,0 +1,6 @@ +H +w out.ro +a +hello +. +# EOF should behave as a 'q' command diff --git a/testsuite/q5.err b/testsuite/q5.err new file mode 100644 index 0000000..14d7aaa --- /dev/null +++ b/testsuite/q5.err @@ -0,0 +1,7 @@ +H +w out.ro +a +hello +. +# EOF in the middle of a command should behave as a 'q' command +w out.ro \ No newline at end of file diff --git a/testsuite/q6.err b/testsuite/q6.err new file mode 100644 index 0000000..b99a455 --- /dev/null +++ b/testsuite/q6.err @@ -0,0 +1,4 @@ +H +w out.ro +a +# EOF in input mode should behave as a 'q' command diff --git a/testsuite/q7.err b/testsuite/q7.err new file mode 100644 index 0000000..ca8da06 --- /dev/null +++ b/testsuite/q7.err @@ -0,0 +1,5 @@ +H +w out.ro +a +hello +# EOF in the middle of a line in input mode should behave as a 'q' command \ No newline at end of file diff --git a/testsuite/q8.err b/testsuite/q8.err new file mode 100644 index 0000000..8450355 --- /dev/null +++ b/testsuite/q8.err @@ -0,0 +1,7 @@ +H +w out.ro +a +hello +. +w !wc +q diff --git a/testsuite/r.err b/testsuite/r.err new file mode 100644 index 0000000..b41bbd5 --- /dev/null +++ b/testsuite/r.err @@ -0,0 +1,3 @@ +H +r a-good-book +w out.ro diff --git a/testsuite/r1.ed b/testsuite/r1.ed new file mode 100644 index 0000000..e63660d --- /dev/null +++ b/testsuite/r1.ed @@ -0,0 +1,16 @@ +H +7r test.bin +u +u +.r +# empty read at current address should not modify the current address +.r zero +f test.bin +-7r +0r !echo hello world +1 +r !! % +# to be undone +r test.txt +u +w out.o diff --git a/testsuite/r1.r b/testsuite/r1.r new file mode 100644 index 0000000..15718c6 Binary files /dev/null and b/testsuite/r1.r differ diff --git a/testsuite/r2.ed b/testsuite/r2.ed new file mode 100644 index 0000000..0b7d20e --- /dev/null +++ b/testsuite/r2.ed @@ -0,0 +1,4 @@ +H +# appending a binary file does not add a newline +r test.bin +w out.o diff --git a/testsuite/r2.r b/testsuite/r2.r new file mode 100644 index 0000000..7f3bdea Binary files /dev/null and b/testsuite/r2.r differ diff --git a/testsuite/r3.ed b/testsuite/r3.ed new file mode 100644 index 0000000..2e67568 --- /dev/null +++ b/testsuite/r3.ed @@ -0,0 +1,6 @@ +H +# appending a binary file does not add a newline +r test.bin +# but undo does not remove any newline already present +u +w out.o diff --git a/testsuite/r3.r b/testsuite/r3.r new file mode 100644 index 0000000..f707ae0 --- /dev/null +++ b/testsuite/r3.r @@ -0,0 +1,13 @@ +This natural inequality of the two powers of population and of +production in the earth, and that great law of our nature which must +constantly keep their effects equal, form the great difficulty that to +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 +of this law which pervades all animated nature. No fancied equality, no +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 +which should live in ease, happiness, and comparative leisure; and feel +no anxiety about providing the means of subsistence for themselves and +their families. diff --git a/testsuite/s.ed b/testsuite/s.ed new file mode 100644 index 0000000..a643f1e --- /dev/null +++ b/testsuite/s.ed @@ -0,0 +1,58 @@ +H +s/fam// +s/il/%/ +s/ies/off\&%1spr\ing/ +1s/of/01/2 ++10s/and/02/g +# set current address to last modified line (6) +,s/way/03 +u +u +s,man,04,1p +10szallzf&z1 +-3s!no!%&%! +9s'it'&05&'gp +12s|of|%|p1 +s/\([^ ][^ ]*\)/(\1)/pg +2s +/4/sp +/\(No\)/sr +/\(.\)/sgpr +,s&$&$& +5s//%/lg +,s%^%^% +5i +hello/[]world +. +s/[/]/ / +s/[[:digit:][]/ / +s/[]]/ / +7s=\((03)\) =\1\ += +-1s($($( +2s/a/1/l +s/a/2/n +s/a/3/p +s/a/4/ln +s/e/5/lp +s/e/6/np +s/e/7/lnp +s/i/8 +s/u/%/ +s/u/% +3s/ /_/lnp3 +s0e0103 +4sg +6s5 +9sp +10s +11sg +12sg +,s/ (nature)/$\ +(nature)/ ++12s/ (for)/$\ +(for)/ +# to be undone +,s/./x/g +u +w out.o diff --git a/testsuite/s.r b/testsuite/s.r new file mode 100644 index 0000000..c2b20b9 --- /dev/null +++ b/testsuite/s.r @@ -0,0 +1,17 @@ +^This natural inequality of the two powers 01 population and of$ +^(prod8ct8on) (in) (th5) (61rth,) (2nd) (th3t) (gr74t) (law) (of) (o8r)$ +(nature) (which) (must)$ +^constantly keep th1ir_effects equal, form the great difficulty that to$ +^m1 app1ars insurmountabl1 in th1 03 to th1 p1rf1ctibility of soci1ty.$ +hello world +^All other arguments are of slight and subordinate consid1ration in$$ +^(comparison) (of) (this.) (I) (see) (no) (03)$ +(by) (which) (04) (can) (escape) (from) (the) (weight)$ +^of this law which pervades all animated nature. (No) fanci1d equality, %no%$ +^(a)grarian regulations in their utmost extent, could r1move the pressure$ +^of it05it 1v1n for a singl1 c1ntury. And it05it app1ars, th1r1for1, to b1$ +^d1cisive against the possible existence of a society, fall the members of$ +^which should live in ease, happiness, 02 comparative leisure; 02 feel$ +^(no) (anxiety) (about) (providing) (the) (means) (of05of) (subsistence)$ +(for) (themselves) (and)$ +^their off&%1spring.$ diff --git a/testsuite/s01.err b/testsuite/s01.err new file mode 100644 index 0000000..c0fc270 --- /dev/null +++ b/testsuite/s01.err @@ -0,0 +1,3 @@ +H +s . x +w out.ro diff --git a/testsuite/s02.err b/testsuite/s02.err new file mode 100644 index 0000000..7cb57da --- /dev/null +++ b/testsuite/s02.err @@ -0,0 +1,3 @@ +H +s/x*/a/g +w out.ro diff --git a/testsuite/s03.err b/testsuite/s03.err new file mode 100644 index 0000000..9fee8b1 --- /dev/null +++ b/testsuite/s03.err @@ -0,0 +1,3 @@ +H +s/[xyx/a/ +w out.ro diff --git a/testsuite/s04.err b/testsuite/s04.err new file mode 100644 index 0000000..b920b16 --- /dev/null +++ b/testsuite/s04.err @@ -0,0 +1,3 @@ +H +s/\a\b\c/xyz/ +w out.ro diff --git a/testsuite/s05.err b/testsuite/s05.err new file mode 100644 index 0000000..6eed8ca --- /dev/null +++ b/testsuite/s05.err @@ -0,0 +1,3 @@ +H +s//xyz/ +w out.ro diff --git a/testsuite/s06.err b/testsuite/s06.err new file mode 100644 index 0000000..45b338a --- /dev/null +++ b/testsuite/s06.err @@ -0,0 +1,3 @@ +H +s +w out.ro diff --git a/testsuite/s07.err b/testsuite/s07.err new file mode 100644 index 0000000..fd86a9c --- /dev/null +++ b/testsuite/s07.err @@ -0,0 +1,4 @@ +H +/./ +sr +w out.ro diff --git a/testsuite/s08.err b/testsuite/s08.err new file mode 100644 index 0000000..9b1e2f4 --- /dev/null +++ b/testsuite/s08.err @@ -0,0 +1,3 @@ +H +s/[h[=]/x/ +w out.ro diff --git a/testsuite/s09.err b/testsuite/s09.err new file mode 100644 index 0000000..a75b2c1 --- /dev/null +++ b/testsuite/s09.err @@ -0,0 +1,3 @@ +H +s/[h[:]/x/ +w out.ro diff --git a/testsuite/s10.err b/testsuite/s10.err new file mode 100644 index 0000000..8069299 --- /dev/null +++ b/testsuite/s10.err @@ -0,0 +1,3 @@ +H +s/[h[.]/x/ +w out.ro diff --git a/testsuite/s11.err b/testsuite/s11.err new file mode 100644 index 0000000..3a3d913 --- /dev/null +++ b/testsuite/s11.err @@ -0,0 +1,8 @@ +H +# Missing pattern delimiter must not alter RE nor REPLACEMENT +s/i/1/g +s/1/i/ +s/ +s/1 +s//%/g +w out.ro diff --git a/testsuite/s12.err b/testsuite/s12.err new file mode 100644 index 0000000..90dee78 --- /dev/null +++ b/testsuite/s12.err @@ -0,0 +1,3 @@ +H +s/./&/g3 +w out.ro diff --git a/testsuite/s13.err b/testsuite/s13.err new file mode 100644 index 0000000..82e3194 --- /dev/null +++ b/testsuite/s13.err @@ -0,0 +1,3 @@ +H +s/./&/3g +w out.ro diff --git a/testsuite/s14.err b/testsuite/s14.err new file mode 100644 index 0000000..18555c5 --- /dev/null +++ b/testsuite/s14.err @@ -0,0 +1,4 @@ +H +s/./&/ +sg3 +w out.ro diff --git a/testsuite/s15.err b/testsuite/s15.err new file mode 100644 index 0000000..f4341a9 --- /dev/null +++ b/testsuite/s15.err @@ -0,0 +1,4 @@ +H +s/./&/ +s3g +w out.ro diff --git a/testsuite/s16.err b/testsuite/s16.err new file mode 100644 index 0000000..4f6fba7 --- /dev/null +++ b/testsuite/s16.err @@ -0,0 +1,3 @@ +H +s3.3&3p +w out.ro diff --git a/testsuite/s17.err b/testsuite/s17.err new file mode 100644 index 0000000..225e2a3 --- /dev/null +++ b/testsuite/s17.err @@ -0,0 +1,3 @@ +H +sg.g&gp +w out.ro diff --git a/testsuite/s18.err b/testsuite/s18.err new file mode 100644 index 0000000..5cb703d --- /dev/null +++ b/testsuite/s18.err @@ -0,0 +1,3 @@ +H +sr.r&rp +w out.ro diff --git a/testsuite/s19.err b/testsuite/s19.err new file mode 100644 index 0000000..0dda461 --- /dev/null +++ b/testsuite/s19.err @@ -0,0 +1,3 @@ +H +sp.p&p +w out.ro diff --git a/testsuite/s20.err b/testsuite/s20.err new file mode 100644 index 0000000..f48b2ff --- /dev/null +++ b/testsuite/s20.err @@ -0,0 +1,5 @@ +H +$m7 +,s/xxx/yyy/ +.m$ +w out.ro diff --git a/testsuite/s21.err b/testsuite/s21.err new file mode 100644 index 0000000..c76c519 --- /dev/null +++ b/testsuite/s21.err @@ -0,0 +1,4 @@ +H +w out.ro +s/a/EOF in the middle of a replacement with newlines \ +should behave as a 'q' command \ No newline at end of file diff --git a/testsuite/t.ed b/testsuite/t.ed new file mode 100644 index 0000000..3399b45 --- /dev/null +++ b/testsuite/t.ed @@ -0,0 +1,11 @@ +H +1t0 +2,3t2 +,t$ +u +u +t0;/./ +# to be undone +,t0 +u +w out.o diff --git a/testsuite/t.r b/testsuite/t.r new file mode 100644 index 0000000..b90a437 --- /dev/null +++ b/testsuite/t.r @@ -0,0 +1,33 @@ +This natural inequality of the two powers of population and of +their families. +This natural inequality of the two powers of population and of +This natural inequality of the two powers of population and of +production in the earth, and that great law of our nature which must +production in the earth, and that great law of our nature which must +constantly keep their effects equal, form the great difficulty that to +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 +of this law which pervades all animated nature. No fancied equality, no +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 +which should live in ease, happiness, and comparative leisure; and feel +no anxiety about providing the means of subsistence for themselves and +their families. +This natural inequality of the two powers of population and of +This natural inequality of the two powers of population and of +This natural inequality of the two powers of population and of +production in the earth, and that great law of our nature which must +production in the earth, and that great law of our nature which must +constantly keep their effects equal, form the great difficulty that to +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 +of this law which pervades all animated nature. No fancied equality, no +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 +which should live in ease, happiness, and comparative leisure; and feel +no anxiety about providing the means of subsistence for themselves and +their families. diff --git a/testsuite/t1.err b/testsuite/t1.err new file mode 100644 index 0000000..02a9033 --- /dev/null +++ b/testsuite/t1.err @@ -0,0 +1,3 @@ +H +tt +w out.ro diff --git a/testsuite/t2.err b/testsuite/t2.err new file mode 100644 index 0000000..fdd99ba --- /dev/null +++ b/testsuite/t2.err @@ -0,0 +1,3 @@ +H +t0;-1 +w out.ro diff --git a/testsuite/test.bin b/testsuite/test.bin new file mode 100644 index 0000000..c866266 Binary files /dev/null and b/testsuite/test.bin differ diff --git a/testsuite/test.txt b/testsuite/test.txt new file mode 100644 index 0000000..f707ae0 --- /dev/null +++ b/testsuite/test.txt @@ -0,0 +1,13 @@ +This natural inequality of the two powers of population and of +production in the earth, and that great law of our nature which must +constantly keep their effects equal, form the great difficulty that to +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 +of this law which pervades all animated nature. No fancied equality, no +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 +which should live in ease, happiness, and comparative leisure; and feel +no anxiety about providing the means of subsistence for themselves and +their families. diff --git a/testsuite/u.err b/testsuite/u.err new file mode 100644 index 0000000..205f56c --- /dev/null +++ b/testsuite/u.err @@ -0,0 +1,3 @@ +H +.u +w out.ro diff --git a/testsuite/v.ed b/testsuite/v.ed new file mode 100644 index 0000000..023b7eb --- /dev/null +++ b/testsuite/v.ed @@ -0,0 +1,13 @@ +H +v/[w]/m0 +u +u +v/o/a\ +hello world +v/hello /s/lo/p!/\ +a\ +order +# to be undone +v/z/s/./x/g +u +w out.o diff --git a/testsuite/v.r b/testsuite/v.r new file mode 100644 index 0000000..840aa7c --- /dev/null +++ b/testsuite/v.r @@ -0,0 +1,27 @@ +their families. +order +hello world +no anxiety about providing the means of subsistence for themselves and +order +decisive against the possible existence of a society, all the members of +order +of it even for a single century. And it appears, therefore, to be +order +agrarian regulations in their utmost extent, could remove the pressure +order +All other arguments are of slight and subordinate consideration in +order +constantly keep their effects equal, form the great difficulty that to +order +This natural inequality of the two powers of population and of +order +production in the earth, and that great law of our nature which must +order +me appears insurmountable in the way to the perfectibility of society. +order +comparison of this. I see no way by which man can escape from the weight +order +of this law which pervades all animated nature. No fancied equality, no +order +which should live in ease, happiness, and comparative leisure; and feel +order diff --git a/testsuite/w.ed b/testsuite/w.ed new file mode 100644 index 0000000..ce32199 --- /dev/null +++ b/testsuite/w.ed @@ -0,0 +1,7 @@ +H +5w \!.z +6W ./!.z +0r !cat < ./!.z +r \!.z +!rm -f ./!.z +wq out.o diff --git a/testsuite/w.r b/testsuite/w.r new file mode 100644 index 0000000..9157ecb --- /dev/null +++ b/testsuite/w.r @@ -0,0 +1,17 @@ +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 +This natural inequality of the two powers of population and of +production in the earth, and that great law of our nature which must +constantly keep their effects equal, form the great difficulty that to +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 +of this law which pervades all animated nature. No fancied equality, no +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 +which should live in ease, happiness, and comparative leisure; and feel +no anxiety about providing the means of subsistence for themselves and +their families. +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 diff --git a/testsuite/w1.err b/testsuite/w1.err new file mode 100644 index 0000000..5185887 --- /dev/null +++ b/testsuite/w1.err @@ -0,0 +1,3 @@ +H +w to/some/far-away/place +w out.ro diff --git a/testsuite/w2.err b/testsuite/w2.err new file mode 100644 index 0000000..a55f36c --- /dev/null +++ b/testsuite/w2.err @@ -0,0 +1,3 @@ +H +wbad_write +w out.ro diff --git a/testsuite/w3.err b/testsuite/w3.err new file mode 100644 index 0000000..bd42097 --- /dev/null +++ b/testsuite/w3.err @@ -0,0 +1,3 @@ +H +wqp bad_write +w out.ro diff --git a/testsuite/x.ed b/testsuite/x.ed new file mode 100644 index 0000000..8c1349c --- /dev/null +++ b/testsuite/x.ed @@ -0,0 +1,17 @@ +H +2,4y +$x +3x +u +u +,y +8y +$x +16 +y +x +# to be undone +,y +x +u +w out.o diff --git a/testsuite/x.err b/testsuite/x.err new file mode 100644 index 0000000..c75f849 --- /dev/null +++ b/testsuite/x.err @@ -0,0 +1,3 @@ +H +x +w out.ro diff --git a/testsuite/x.r b/testsuite/x.r new file mode 100644 index 0000000..89cbcb0 --- /dev/null +++ b/testsuite/x.r @@ -0,0 +1,21 @@ +This natural inequality of the two powers of population and of +production in the earth, and that great law of our nature which must +constantly keep their effects equal, form the great difficulty that to +production in the earth, and that great law of our nature which must +constantly keep their effects equal, form the great difficulty that to +me appears insurmountable in the way to the perfectibility of society. +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 +of this law which pervades all animated nature. No fancied equality, no +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 +which should live in ease, happiness, and comparative leisure; and feel +no anxiety about providing the means of subsistence for themselves and +their families. +their families. +production in the earth, and that great law of our nature which must +constantly keep their effects equal, form the great difficulty that to +me appears insurmountable in the way to the perfectibility of society. +All other arguments are of slight and subordinate consideration in diff --git a/testsuite/z.err b/testsuite/z.err new file mode 100644 index 0000000..fe297c0 --- /dev/null +++ b/testsuite/z.err @@ -0,0 +1,4 @@ +H +$z +z +w out.ro