pax_global_header00006660000000000000000000000064136424123440014515gustar00rootroot0000000000000052 comment=98813a10212335b997db4b90f812965e55829e2f memo-1.7.1/000077500000000000000000000000001364241234400124605ustar00rootroot00000000000000memo-1.7.1/.gitignore000066400000000000000000000000571364241234400144520ustar00rootroot00000000000000memo *.o *.out memo.1.gz memo-cron-reminder.sh memo-1.7.1/COPYING000066400000000000000000001045141364241234400135200ustar00rootroot00000000000000 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 . memo-1.7.1/INSTALL000066400000000000000000000022531364241234400135130ustar00rootroot00000000000000How to install Memo from source code To compile and install Memo, you will need fairly modern C compiler which supports C99 standard. You will also need GNU Make program. Make is not mandatory, but makes compiling and installing Memo easier. 1) Extract the source code archive e.g memo-1.0.tar.gz 2) Move to the Memo source code directory 3) Type make. This will compile Memo. 4) Type make install as root. This will install Memo to /usr/local/bin and memo.1 manpage to /usr/local/share/man/man1/memo.1.gz 5) Run Memo. For example: memo -a "My first note" Compile Memo without GNU Make. While it's possible to compile Memo without GNU Make program, you will have to manually install the memo binary and the manpage. Compile command (assuming GCC is the C compiler in use): gcc -o memo memo.c If compiled natively on Windows MinGW is needed as well as Pcre library for POSIX regular expression support. To install memo binary: cp memo /usr/local/bin/ To install memo.1 manpage: cp memo.1 /usr/local/share/man/man1/ gzip /usr/local/share/man/man1/memo.1 Any errors or improvements, please contact niko@byteptr.com memo-1.7.1/Makefile000066400000000000000000000007351364241234400141250ustar00rootroot00000000000000DESTDIR ?= PREFIX ?= /usr/local MANPREFIX ?= $(PREFIX)/man CFLAGS += -std=c99 -Wall ifeq ($(OS),Windows_NT) LDFLAGS += -lpcre endif all: memo clean: rm -f memo *.o install: all install -d $(DESTDIR)$(PREFIX)/bin $(DESTDIR)$(MANPREFIX)/man1 install -m755 memo $(DESTDIR)$(PREFIX)/bin/ install -m644 memo.1 $(DESTDIR)$(MANPREFIX)/man1/ uninstall: rm -f $(DESTDIR)$(PREFIX)/bin/memo rm -f $(DESTDIR)$(MANPREFIX)/man1/memo.1 .PHONY: all clean install uninstall memo-1.7.1/NEWS000066400000000000000000000123761364241234400131700ustar00rootroot000000000000001.7.1: 2020-04-05 Version 1.7.1 released 1.7: 2019-06-12 Version 1.7 released. Add supports for long options for easier beginner usage. 1.6: 2015-03-20 Version 1.6 released. Memo now has support for colors. Colors are disabled by default, but can be easily enabled via .memorc property USE_COLORS=yes. See man page for more detailed information about how to customize default colors. Colors are not supported on Windows. Malloc return values are no longer casted. Casting malloc is unnecessary in C. Memo now supports $XDG_CONFIG_HOME environment variable when looking for .memorc file. See the man page for more information. 1.5: 2015-01-01 Version 1.5 released. Memo can now export notes to a CSV file. In ~/.memorc a property MARK_AS_DONE can be set. The property takes a valid date(yyyy-MM-dd) as a value. When set Memo will automatically mark notes older than the date as done. New command line flag -O added. With -O Memo reorders note id codes. For example if there's notes with id codes 1,4 and 5 they will become 1,2 and 3. Search is no longer case sensitive. On Windows Memo now uses _ as a file prefix instead of dot. So On Windows .memorc is _memorc and .memo is _memo. However, Windows is not officially supported. Use Cygwin instead if on Windows. This release includes multiple bug fixes and to avoid code duplication several helper functions where added. As this version had increasing number of contributors I'm not going to list all the people here. Thanks for all the contributors for bug fixes and feature suggestions. 1.4: 2014-11-21 Version 1.4 released. Version 1.4 implements new features as well as portability fixes. Memo can now replace existing note without touching the id of the note. Note replace functionality is behind -r flag. It's now possible to add multiple notes at once using -i flag. When flag -i is used Memo reads notes from stdin until the end of transmission (^D). Memo can now show only undone notes with flag -u. Flag -s is now depracated. Same functionality is available by simply typing "memo". Adding a note from stdin is now behind flag - instead of just command "memo". This change was made since it's more logical to show the notes when user types "memo" than assume input from stdin. Besides flag - is pretty standard for reading from stdin. This version also includes various portability fixes for Windows and Mac OS X operating systems. Thanks for Mikael Berthe for new ideas, Aaron Massey for Mac OS X related fixes and Mattn for Windows related changes. Thanks also for other contributors I possibly forgot to mention. 1.3: 2014-11-06 Version 1.3 released. This release brings new features as well as bugfixes. -D option now asks for confirmation. It's possible to disable it via ~/.memorc property. See manpage for more. Added -o option to display all notes organized by date. Help (-h) is now shorter and all the examples are available in the man page. BUGFIX: Memo no longer makes unnecessary file accessing. BUGFIX: Improve error reporting in various ways. BUGFIX: Better way to check if a file exists. This should add reliability and probably fixes problems what Memo had when running on Jolla mobile phone. Thanks for Mikael Berthe for noticing small bugs. 1.2: 2014-10-30 Bugfix version 1.2 released. This is an important fix and everyone must upgrade. Memo assumed that the is is always one char long. This caused a problem where note status could not be changed if the id was > 9. Thanks for Mikael Berthe for noticing this bug. 1.1: 2014-10-29 Stable version 1.1 released. Notes can be now marked as postponed. See man page for more information. Memo path can be now set using MEMO_PATH environment variable. See man page for more information. BUGFIX: Prevent Memo from adding empty notes. 1.0: 2014-10-24 First official release of Memo. File format is now stable and documented. Different note statuses are now supported. Notes can be "undone" or "done". BUGFIX: Fixed a minor memory leak in main(). 0.9: 2014-10-20 It's now possible to change the path where Memo stores notes. See manpage for more information. Some refactoring of the codebase was also made. Couple of minor bugfixes were made, Memo should be now even more stable. 0.8: 2014-10-19 Notes can be now searched with regular expressions. POSIX.2 basic regular expressions are supported. This was chosen to achieve compatibility with tools such as grep and sed. Added manual page memo(1) 0.7: 2014-10-15 It's now possible to add a note with custom date. For example one could do memo -a "Text for the short note" 2014-24-12. If date is omitted, current date will be used. 0.6: 2014-10-11 Initial release. Memo was originally implemented in Java, but that was an ugly hack. Version 0.6 is now rewritten in C99 and has proper support for reading from stdin among other things. 2014-10-12 Added "delete all" option. Also fixed unnecessary errors when ~/.memo does not exist. Applied patches from Jari Aalto. Includes code readability fixes as well as improves help. memo-1.7.1/README.md000066400000000000000000000006011364241234400137340ustar00rootroot00000000000000# Memo - Unix-style note-taking software Memo is a Unix-style note-taking software for POSIX compatible systems. At the moment it's tested on GNU/Linux and on FreeBSD, but it should be very portable for other platforms. Memo also works under Cygwin, but it's not actively tested under it. Memo is licenced under the GPL. For more, see [homepage](https://www.nrosvall.name/memo/). memo-1.7.1/memo.1000066400000000000000000000104201364241234400134740ustar00rootroot00000000000000.\" Manpage for memo. .\" Any errors or typos, contact niko@byteptr.com. .TH man 1 "5 Apr 2020" "1.7.1" "memo man page" .SH NAME memo \- unix-style note-taking software .SH SYNOPSIS memo [OPTIONS] .SH DESCRIPTION Memo is a note-taking software for POSIX compatible operating systems. The short notes are saved to user's home directory in ~/.memo file by default. .SH OPTIONS .IP "-a, --add [yyyy-MM-dd]" Add a new note .IP "-d, --delete " Delete note by id .IP "-D, --delete-all" Delete all notes .IP "-e, --export " Export notes to a file. must be either csv or html .IP "-f, --search " Find notes by text search .IP "-F --regex " Find notes by regular expression .IP "-i, --stdin" Add multiple notes from stdin .IP "-l, --latest " Show latest n notes .IP "-m, --set-done " Mark note status as done .IP "-M, --set-undone " Mark note status as undone .IP "-o, --list-date" Show all notes organized by date .IP "-O, --organize" Reorder and organize note id codes .IP "-p, --path" Show current memo file path .IP "-P, --postpone [id]" Show postponed or mark note as postponed .IP "-R, --delete-done" Delete all notes marked as done .IP "-r, --replace [content]/[yyyy-MM-dd]" Replace note content or date .IP "-s, --list" Show all notes except postponed. Same as typing command memo .IP "-T, --set-done-all" Mark all notes as done .IP "-u, --list-undone" Show only undone notes .IP - Read from stdin .IP "-h, --help" Show short help and exit. This page .IP "-V, --version" Show version number of program .SH EXAMPLES Add a new note: memo -a "Remember to buy milk!" .PP Add a new note with custom date: memo -a "File taxes" 2014-10-14 .PP Search memos by string: memo -f buy .PP Output: 4 2014-10-10 Remember to buy milk .PP Replace record 4 with new text: memo -r 4 "Remember to buy cheese" .PP Add note from stdin: echo "My new note" | memo - .PP Mark note as postponed: memo -P 4 .PP Show postponed notes: memo -P .PP Postponed notes are not shown by default. Postponed note can be marked as undone or done normally using -m or -M flag. Only undone notes can be postponed. .PP It's possible to change the location (and name) of the .memo file. Create $HOME/.memorc (or $XDG_CONFIG_HOME/.memorc) with a line MEMO_PATH=/path/you/would/like , Memo will use that path instead of the default $HOME/.memo path. .PP It's also possible to set memo path using an environment variable. For example: export MEMO_PATH=/path/to/some/file. If MEMO_PATH environment variable is set that will be used. If it's not set, Memo will try to read .memorc for MEMO_PATH. If the file does not exist or has errors, Memo will use $HOME/.memo file to store the notes. .PP Since version 1.3 -D option asks for confirmation before deleting all notes. It's possible to disable this confirmation via .memorc property. To disable the confirmation add MEMO_CONFIRM_DELETE=no to .memorc file. .PP Since version 1.5 it's possible to set a property MARK_AS_DONE in .memorc. The property takes a valid date as a value. For example: MARK_AS_DONE=2014-12-23. If the property is set Memo will mark all notes older than the property value as done automatically. .SH NOTES On some terminal emulators with Bash you can't use exclamation mark if Bash history expand feature is enabled. For example: memo -a "This is a test note!" 2014-12-20 would fail. Some terminal emulators workaround this (Gnome Terminal for example). You might want to disable Bash history expand if you don't use it by putting set +H to your ~/.bashrc. Please note, that this is not a bug in Memo, or in Bash. It's a feature of Bash. .SH FILES .I $HOME/.memo .I $HOME/.memorc, $XDG_CONFIG_HOME/.memorc .SH COLORS .PP Since version 1.6 Memo has support for colors. Color support can be enabled in .memorc by setting USE_COLORS=yes. By default Memo uses blue for odd lines and magenta for even lines. These can be modified via .memorc properties LINE_COLOR and ODD_LINE_COLOR. Supported colors are: .IP red .IP cyan .IP green .IP blue .IP black .IP brown .IP magenta .IP gray .IP none .SH AUTHORS Written by Niko Rosvall and contributors. .SH COPYRIGHT Copyright (C) 2014-2020 Niko Rosvall .PP Released under license GPL-3+. For more information, see http://www.gnu.org/licenses memo-1.7.1/memo.c000066400000000000000000001565171364241234400136000ustar00rootroot00000000000000/* Memo is a Unix-style note-taking software. * * Copyright (C) 2014-2020 Niko Rosvall * * 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 . * * * memo.c implements a flexible, Unix-style note-taking software. * * If you're interested hacking Memo, please remember: * coding style is pretty much the same as for Linux kernel. * see https://www.kernel.org/doc/Documentation/CodingStyle * * When adding features, please consider if they can be * accomplished in a sane way with standard unix tools instead. * * If you port Memo for another platform, please let me know, * no reason for that other than it's nice to know where Memo runs. * Memo should be fairly portable for POSIX systems. */ /* To enable _POSIX_C_SOURCE feature test macro */ #define _XOPEN_SOURCE 600 /* Make only POSIX.2 regexp functions available */ #define _POSIX_C_SOURCE 200112L #ifdef _WIN32 # undef __STRICT_ANSI__ # define S_IRGRP 0 # define S_IROTH 0 #endif #include #include #include #include #include #include #include #include #include #include #include #ifdef _WIN32 # include #else # include #endif #include typedef enum { DONE = 1, UNDONE = 2, DELETE = 3, DELETE_DONE = 4, STATUS_ERROR = 5, ALL_DONE = 6, POSTPONED = 7 } NoteStatus_t; /* NOTE_STATUS part is handled by NoteStatus_t * in function mark_note_status. */ typedef enum { NOTE_DATE = 1, NOTE_CONTENT = 2, NOTE_ID = 3 } NotePart_t; /* Function declarations */ static char *read_file_line(FILE *fp); static int add_notes_from_stdin(); static char *get_memo_file_path(); static char *get_memo_default_path(); static char *get_memo_conf_path(); static char *get_temp_memo_path(); static char *get_memo_conf_value(const char *prop); static int is_valid_date_format(const char *date, int silent_errors); static int file_exists(const char *path); static void remove_content_newlines(char *content); static int add_note(char *content, const char *date); static int replace_note(int id, const char *data); static int get_next_id(); static char *get_note_date(char *line); static int get_note_id_from_line(const char *line); static char *integer_to_string(int id); static int delete_note(int id); static int show_notes(NoteStatus_t status); static int show_notes_tree(); static int count_file_lines(FILE *fp); static char *note_part_replace(NotePart_t part, char *note_line, const char *data); static char *case_strstr(const char *str1, const char *str2); static int search_notes(char *search); static int search_regexp(const char *regexp); static const char *export_html(const char *path); static const char *export_csv(const char *path); static void output(char *line, int is_odd_line); static void output_default(char *line, int is_odd_line); static void output_undone(char *line, int is_odd_line); static void output_postponed(char *line, int is_odd_line); static void output_without_date(char *line, int is_odd_line); static void show_latest(int count); static FILE *get_memo_file_ptr(char *mode); static FILE *get_memo_tmpfile_ptr(); static void usage(); static void fail(FILE *out, const char *fmt, ...); static int delete_all(); static void show_memo_file_path(); static NoteStatus_t get_note_status(const char *line); static int mark_note_status(NoteStatus_t status, int id); static void note_status_replace(char *line, char new, char old); static void mark_as_done(FILE *fp, char *line); static void mark_as_undone(FILE *fp, char *line); static void mark_as_postponed(FILE *fp, char *line); static int mark_old_as_done(); static int organize_note_identifiers(); static char *get_line_color(int is_odd_line); static char *color_to_escape_seq(char *color); static int is_odd(int n); static void sort_dates_ascend(char *dates[], int date_index); static int int_sort(const void *a , const void *b); #define VERSION "1.7.1" /* Check if given date is in valid date format. * Memo assumes the date format to be yyyy-MM-dd. * * If silent_errors is 1, no error information will be outputted. * When silent_errors != 1, error information is outputted to stderr. * * Functions returns 0 on success and -1 on failure. */ static int is_valid_date_format(const char *date, int silent_errors) { int d; int m; int y; int ret; /* contains number of days in each month from jan to dec */ int day_count[12] = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 }; ret = sscanf(date, "%04d-%02d-%02d", &y, &m, &d); if (ret != 3) { if ( !silent_errors) fail(stderr,"%s: invalid date format\n", __func__); return -1; } /* Leap year check */ if (y % 400 == 0 || y % 100 != 0 || y % 4 == 0) day_count[1] = 29; if (m < 13 && m > 0) { if (d <= day_count[m - 1]) { return 0; } else { if (!silent_errors) fail(stderr, "%s: invalid day\n", __func__); } } else { if (!silent_errors) fail(stderr, "%s: invalid month\n", __func__); } if (!silent_errors) fail(stderr, "%s: parsing date failed\n", __func__); return -1; } /* Functions checks if file exists. * This should be more reliable than using access(). * * Returns 1 when the file is found and 0 * when it's not found. * * Please note that 0 could be returned even if * the file exists but there are other problems accessing it. * See http://pubs.opengroup.org/onlinepubs/009695399/functions/stat.html */ static int file_exists(const char *path) { int retval = 0; struct stat buffer; if (stat(path, &buffer) == 0) retval = 1; return retval; } /* This function is used to count lines in .memo and ~/.memorc * files. * * Count the lines of the file as a note is always one liner, * lines == note count. * * File pointer is rewinded to the beginning of the file. * * Returns the count or -1 if the file pointer is null. -2 is * returned when there are no lines. * * Caller must close fp after calling the function successfully. */ static int count_file_lines(FILE *fp) { int count = 0; int ch = 0; if (!fp) { fail(stderr,"%s: NULL file pointer\n", __func__); return -1; } /* Count lines by new line characters */ while (!feof(fp)) { ch = fgetc(fp); if (ch == '\n') count++; } /* Go to beginning of the file */ rewind(fp); /* return the count, ignoring the last empty line */ if (count == 0) return -2; return count - 1; } /* A simple error reporting function */ static void fail(FILE *out, const char *fmt, ...) { va_list ap; va_start(ap, fmt); vfprintf(out, fmt, ap); va_end(ap); } /* Get a FILE descriptor for temp file. * Caller is responsible for closing the * file pointer. * * Return NULL on failure. */ static FILE *get_memo_tmpfile_ptr() { FILE *fp = NULL; char *tmp = NULL; tmp = get_temp_memo_path(); if (tmp == NULL) { fail(stderr, "%s: error getting a temp file\n", __func__); return NULL; } fp = fopen(tmp, "w"); if (fp == NULL) { fail(stderr, "%s: error opening temp file\n", __func__); free(tmp); return NULL; } free(tmp); return fp; } /* Get open FILE* for .memo file. * Returns NULL of failure. * Caller must close the file pointer after calling the function * succesfully. */ static FILE *get_memo_file_ptr(char *mode) { FILE *fp = NULL; char *path = get_memo_file_path(); if (path == NULL) { fail(stderr,"%s: error getting ~./memo path\n", __func__); return NULL; } fp = fopen(path, mode); if (fp == NULL) { fail(stderr,"%s: error opening %s\n", __func__, path); return NULL; } free(path); return fp; } /* Function reads multiple lines from stdin until * the end of transmission (^D). * * Each line is assumed to be the content part of the note. * * Notes are added to the memo file. Returns -1 on failure, 0 on * success. */ static int add_notes_from_stdin() { /* First get the whole buffer from stdin. Then parse the buffer; * each note is separated by a new line character in the * buffer. Call add_note for each line. */ int length = 128; char *buffer = NULL; int count = 0; char ch; char *line = NULL; if ((buffer = malloc(sizeof(char) * length)) == NULL) { fail(stderr, "%s: malloc failed\n", __func__); return -1; } ch = getc(stdin); while (ch != EOF) { if (count == length) { length += 128; if ((buffer = realloc(buffer, length)) == NULL) { fail(stderr, "%s realloc failed\n", __func__); return -1; } } buffer[count] = ch; count++; ch = getc(stdin); } buffer[count] = '\0'; buffer = realloc(buffer, count + 1); line = strtok(buffer, "\n"); while (line != NULL) { add_note(line, NULL); line = strtok(NULL, "\n"); } free(buffer); return 0; } /* Reads a line from source pointed by FILE*. * * This function is used to read .memo as well as ~/.memorc * files line by line. * * Return NULL on failure. * Caller is responsible for freeing the return value */ static char *read_file_line(FILE *fp) { if (!fp) return NULL; int length = 128; char *buffer = NULL; buffer = malloc(sizeof(char) * length); if (buffer == NULL) { fail(stderr,"%s: malloc failed\n", __func__); return NULL; } int count = 0; char ch = getc(fp); /* Read char by char until the end of the line. * and allocate memory as needed. */ while ((ch != '\n') && (ch != EOF)) { if (count == length) { length += 128; buffer = realloc(buffer, length); if (buffer == NULL) { fail(stderr, "%s: realloc failed\n", __func__); return NULL; } } buffer[count] = ch; count++; ch = getc(fp); } buffer[count] = '\0'; buffer = realloc(buffer, count + 1); return buffer; } /* Simply read all the lines from the .memo file * and return the id of the last line plus one. * If the file is missing or is empty, return 1 * On error, returns -1 */ static int get_next_id() { int id = 0; FILE *fp = NULL; char *line = NULL; int lines = 0; int current = 0; fp = get_memo_file_ptr("r"); lines = count_file_lines(fp); if (lines == -1) { fail(stderr,"%s: counting lines failed\n", __func__); return -1; } if (lines == -2) { fclose(fp); return id + 1; } while (1) { line = read_file_line(fp); /* Check if we're at the last line */ if (line && current == lines) { id = get_note_id_from_line(line); free(line); break; } current++; if (line) free(line); } fclose(fp); return id + 1; } /* Show all notes. with status POSTPONED, postponed * notes are shown. With status UNDONE, only undone * notes are shown. Otherwise status is ignored and * all notes are displayed. * * Returns the number of notes. Returns -1 on failure */ static int show_notes(NoteStatus_t status) { FILE *fp = NULL; char *line; int count = 0; int lines = 0; /* Output count is used to calculate even and odd lines * when outputting undone or postponed notes. * When outputting normally, lines is used as the counter. */ int postponed_output_count = 0; int undone_output_count = 0; fp = get_memo_file_ptr("r"); lines = count_file_lines(fp); count = lines; if (lines == -1) { fail(stderr,"%s: counting lines failed\n", __func__); return -1; } /* Ignore empty note file and exit */ if (lines == -2) { fail(stderr,"You don't have any notes currently.\n", __func__); fclose(fp); return -1; } while (lines >= 0) { line = read_file_line(fp); if (line) { /* status is just used to know what kind of output we want. * we still need to check status the of the current line * separately. */ if (status == POSTPONED) { if (get_note_status(line) == POSTPONED) { postponed_output_count++; int odd_p = is_odd(postponed_output_count); output_postponed(line, odd_p); } } else if (status == UNDONE) { if (get_note_status(line) == UNDONE) { undone_output_count++; int odd_u = is_odd(undone_output_count); output_undone(line, odd_u); } } else { output_default(line, is_odd(lines)); } free(line); } lines--; } fclose(fp); return count; } /* Function returns the date string of the note. * * On success caller must free the return value. * NULL is returned on failure. */ static char *get_note_date(char *line) { char *date = NULL; char *tmpline = strdup(line); char *datetoken = NULL; if (tmpline == NULL) return NULL; datetoken = strtok(tmpline, "\t"); datetoken = strtok(NULL, "\t"); datetoken = strtok(NULL, "\t"); if (datetoken == NULL) { free(tmpline); return NULL; } date = malloc((strlen(datetoken) + 1) * sizeof(char)); if (date == NULL) { free(tmpline); return NULL; } strcpy(date, datetoken); free(tmpline); return date; } /* Function displays notes ordered by date. * * For example: * * 2014-11-01 * 1 U Release Memo 1.3 * 2 D Pay rent * 2014-11-02 * 3 D Go shopping * * Returns the count of the notes. On failure returns -1. */ static int show_notes_tree() { int count = 0; int lines = 0; FILE *fp = NULL; int date_index = 0; fp = get_memo_file_ptr("r"); lines = count_file_lines(fp); if (lines == -1) { fail(stderr, "%s: counting lines failed\n", __func__); return -1; } /* Ignore empty note file and exit */ if (lines == -2) { fclose(fp); return -1; } int n = lines; char *dates[lines + 1]; memset(dates, 0, sizeof(dates)); /* Get the date of each note and store the pointer * of it to dates array */ while (n >= 0) { char *line = read_file_line(fp); if (line) { char *date = get_note_date(line); int has_date = 0; if (date == NULL) { free(line); fclose(fp); fail(stderr, "%s problem getting date\n", __func__); return -1; } /* Prevent storing duplicate dates*/ for (int i = 0; i < date_index; i++) { if (dates[i]) { if (strcmp(dates[i], date) == 0) { has_date = 1; break; } } } /* If dates does not contain date, store it * otherwise free it */ if (!has_date) { dates[date_index] = date; date_index++; } else { free(date); } count++; free(line); } n--; } /* Sort the dates elements in the order of date. */ sort_dates_ascend(dates, date_index); /* Loop through all dates and print all notes for * the date. */ for (int i = 0; i <= lines; i++) { /* Rewind file pointer to beginning every time to * loop all the notes in the file. * It's possible that the array is not fully populated (because * it's allocated to have as many elements as we have notes, * however duplicate dates are not stored at all. * so do a check if the value is null. */ if (dates[i]) { n = lines; rewind(fp); printf("%s\n", dates[i]); while (n >= 0) { char *line = read_file_line(fp); if (line) { char *date = get_note_date(line); if (date == NULL) { free(line); fclose(fp); return -1; } if (strcmp(date, dates[i]) == 0) output_without_date(line, is_odd(i)); free(line); free(date); } n--; } free(dates[i]); } } fclose(fp); return count; } /* Function works like strstr, but ignores the case. * There's a function strcasestr, but it's nonstandard * GNU extension, so let's not use that. * * Return value must be freed by the caller. */ static char *case_strstr(const char *str1, const char *str2) { char *tmp1 = NULL; char *tmp2 = NULL; char *tmp3 = NULL; char *retval = NULL; tmp1 = strdup(str1); if (tmp1 == NULL) { fail(stderr, "%s: strdup failed\n", __func__); return NULL; } tmp2 = strdup(str2); if (tmp2 == NULL) { free(tmp1); fail(stderr, "%s: strdup failed\n", __func__); return NULL; } for (int i = 0; i < strlen(tmp1); i++) tmp1[i] = tolower(tmp1[i]); for (int i = 0; i < strlen(tmp2); i++) tmp2[i] = tolower(tmp2[i]); tmp3 = strstr(tmp1, tmp2); if (tmp3) { retval = strdup(tmp3); /* Sanity check * Inform the user that something went wrong * even the search term was found. Probably never happens. */ if (retval == NULL) { fail(stderr,"%s: search term found, but strdup fails\n", __func__); } } free(tmp1); free(tmp2); return retval; } /* Search if a note contains the search term. * Returns the count of found notes or -1 if function fails. */ static int search_notes(char *search) { FILE *fp = NULL; int count = 0; char *line; int lines = 0; fp = get_memo_file_ptr("r"); lines = count_file_lines(fp); if (lines == -1) { fail(stderr,"%s: counting lines failed\n", __func__); return -1; } /* Ignore empty note file and exit */ if (lines == -2) { fclose(fp); return -1; } while (lines >= 0) { line = read_file_line(fp); if (line) { char *token = NULL; token = strtok(search, " "); /* Loop through each word in the search string * and see if any of the words can be found */ while (token != NULL) { char *foundptr = case_strstr(line, token); if (foundptr){ output_default(line, is_odd(count)); count++; free(foundptr); /* found it, no point to continue */ break; } token = strtok(NULL, " "); } free(line); } lines--; } fclose(fp); return count; } /* Search using regular expressions (POSIX Basic Regular Expression syntax) * Returns the count of found notes or -1 if functions fails. */ static int search_regexp(const char *regexp) { int count = 0; regex_t regex; int ret; char *line = NULL; char lines = 0; FILE *fp = NULL; char buffer[100]; ret = regcomp(®ex, regexp, REG_ICASE); if (ret != 0) { fail(stderr, "%s: invalid regexp\n", __func__); return -1; } fp = get_memo_file_ptr("r"); lines = count_file_lines(fp); if (lines == -1) { regfree(®ex); fail(stderr,"%s: counting lines failed\n", __func__); return -1; } /* Ignore empty note file and exit */ if (lines == -2) { regfree(®ex); return -1; } while (lines >= 0) { line = read_file_line(fp); if (line) { ret = regexec(®ex, line, 0, NULL, 0); if (ret == 0) { output_default(line, is_odd(count)); count++; } else if (ret != 0 && ret != REG_NOMATCH) { /* Something went wrong while executing regexp. Clean up and exit loop. */ regerror(ret, ®ex, buffer, sizeof(buffer)); fail(stderr, "%s: %s\n", __func__, buffer); free(line); break; } free(line); } lines--; } regfree(®ex); fclose(fp); return count; } /* Replace note status old with new status in line.*/ static void note_status_replace(char *line, char old, char new) { while (*line) { if (*line == old) { *line = new; break; } line++; } } /* Get the note status from the note line. * Returns STATUS_ERROR on failure. */ static NoteStatus_t get_note_status(const char *line) { char *token = NULL; char *buffer = NULL; NoteStatus_t status; status = STATUS_ERROR; /* Sanity check for an empty line */ if(strlen(line) == 0) return status; buffer = malloc((strlen(line) + 1) * sizeof(char)); if (buffer == NULL) { fail(stderr, "%s malloc failed\n", __func__); return status; } strcpy(buffer, line); token = strtok(buffer, "\t"); token = strtok(NULL, "\t"); if (token == NULL) { fail(stderr, "%s: parsing line failed\n", __func__); free(buffer); return status; } if (strcmp(token, "U") == 0) status = UNDONE; else if (strcmp(token, "D") == 0) status = DONE; else if (strcmp(token, "P") == 0) status = POSTPONED; free(buffer); return status; } /* Simple helper function to mark note as done */ static void mark_as_done(FILE *fp, char *line) { if (get_note_status(line) == POSTPONED) note_status_replace(line, 'P', 'D'); else note_status_replace(line, 'U', 'D'); fprintf(fp, "%s\n", line); } /* Simple helper function to mark note as undone */ static void mark_as_undone(FILE *fp, char *line) { if (get_note_status(line) == POSTPONED) note_status_replace(line, 'P', 'U'); else note_status_replace(line, 'D', 'U'); fprintf(fp, "%s\n", line); } /* Simple helper function to mark note as postponed */ static void mark_as_postponed(FILE *fp, char *line) { /* Only UNDONE notes can be postponed */ if (get_note_status(line) == UNDONE) { note_status_replace(line, 'U', 'P'); fprintf(fp, "%s\n", line); } else { fprintf(fp, "%s\n", line); } } /* Returns hte id of the short note. On failure, returns -1. */ static int get_note_id_from_line(const char *line) { int id = -1; char *endptr; id = strtol(line, &endptr, 10); return id; } /* Mark note by status U is undone, D is done or P postponed. When * status is DELETE, the note with a matching id will be deleted. * * Function will create a temporary file to write the memo file with new * changes. Then the original file is replaced with the temp file. * id is ignored when status is DELETE_DONE or ALL_DONE. */ static int mark_note_status(NoteStatus_t status, int id) { FILE *fp = NULL; FILE *tmpfp = NULL; char *line = NULL; char *tmp; int lines = 0; fp = get_memo_file_ptr("r"); lines = count_file_lines(fp); if (lines == -1) { fail(stderr,"%s: counting lines failed\n", __func__); return -1; } /* Ignore empty note file and exit */ if (lines == -2) { fclose(fp); printf("Nothing to do. No notes found\n"); return -1; } tmp = get_temp_memo_path(); if (tmp == NULL) { fail(stderr,"%s: error getting a temp file\n", __func__); return -1; } char *memofile = get_memo_file_path(); if (memofile == NULL) { fail(stderr,"%s: failed to get ~/.memo file path\n", __func__); return -1; } tmpfp = fopen(tmp, "w"); if (tmpfp == NULL) { fail(stderr,"%s: error opening %s\n", __func__, tmp); free(memofile); return -1; } while (lines >= 0) { line = read_file_line(fp); if (line) { int curr = get_note_id_from_line(line); switch(status) { case DONE: if (curr == id) mark_as_done(tmpfp, line); else fprintf(tmpfp, "%s\n", line); break; case UNDONE: if (curr == id) mark_as_undone(tmpfp, line); else fprintf(tmpfp, "%s\n", line); break; case DELETE: /* Write all the other lines, except the one * with the matching id. This is a simple way * to delete the line from the file. */ if (curr != id) fprintf(tmpfp, "%s\n", line); break; case DELETE_DONE: if (get_note_status(line) != DONE) fprintf(tmpfp, "%s\n", line); break; case STATUS_ERROR: fail(stderr,"STATUS_ERROR, this shouldn't happen\n"); break; case ALL_DONE: note_status_replace(line, 'U', 'D'); fprintf(tmpfp, "%s\n", line); break; case POSTPONED: if (curr == id) mark_as_postponed(tmpfp, line); else fprintf(tmpfp, "%s\n", line); break; } free(line); } lines--; } fclose(fp); fclose(tmpfp); if (file_exists(memofile)) remove(memofile); rename(tmp, memofile); remove(tmp); free(memofile); free(tmp); return 0; } /* Function reads ~/.memorc for MARK_AS_DONE property * and marks all notes older than the property value as DONE. * * For example if you have MARK_AS_DONE=2014-12-13, this function * will mark all notes older than 2014-12-13 as DONE. * * Returns count of marked notes on success, -1 on failure. */ static int mark_old_as_done() { #ifdef _WIN32 return -1; #endif char *conf_path = NULL; FILE *fp; char *date = NULL; struct tm dc = {0}; time_t date_to_compare; int lines = 0; conf_path = get_memo_conf_path(); if (conf_path == NULL) return -1; if (!file_exists(conf_path)) { free(conf_path); return -1; } date = get_memo_conf_value("MARK_AS_DONE"); if (date == NULL) { free(conf_path); return -1; } if (is_valid_date_format(date, 0) == -1) { fail(stderr, "%s: error in ~/.memorc parsing\n", __func__); free(date); free(conf_path); return -1; } fp = get_memo_file_ptr("r"); lines = count_file_lines(fp); if (lines == -1) { free(date); free(conf_path); if (lines == -2) fclose(fp); return -1; } int id_array[lines]; int id_count = 0; /* Convert MARK_AS_DONE property value string * to a valid date */ strptime(date, "%Y-%m-%d", &dc); date_to_compare = mktime(&dc); /* Compare each note line date with the one read * from the ~/.memorc and store note id for later use * if note date is older */ while (lines >= 0) { char *line = read_file_line(fp); if (line) { int id = get_note_id_from_line(line); char *curr_date = get_note_date(line); if (curr_date == NULL) { free(line); free(date); free(conf_path); fclose(fp); } time_t note_time; struct tm nt = {0}; strptime(curr_date, "%Y-%m-%d", &nt); note_time = mktime(&nt); /* Store id codes of notes we want to mark as done * as we can't modify the file while we're reading it */ if (difftime(date_to_compare, note_time) > 0) { id_array[id_count] = id; id_count++; } free(curr_date); } free(line); lines--; } free(date); free(conf_path); fclose(fp); /* Loop through all the note id codes and mark corresponding * notes as DONE */ for (int i = 0; i < id_count; i++) mark_note_status(DONE, id_array[i]); return 0; } /* Function returns the corresponding terminal * escape sequence of the color. */ static char *color_to_escape_seq(char *color) { #define red "\033[0;31m" #define cyan "\033[0;36m" #define green "\033[0;32m" #define blue "\033[0;34m" #define black "\033[0;30m" #define brown "\033[0;33m" #define magenta "\033[0;35m" #define gray "\033[0;37m" #define none "\033[0m" if (strcmp(color, "red") == 0) return red; else if (strcmp(color, "cyan") == 0) return cyan; else if (strcmp(color, "green") == 0) return green; else if (strcmp(color, "blue") == 0) return blue; else if (strcmp(color, "black") == 0) return black; else if (strcmp(color, "brown") == 0) return brown; else if (strcmp(color, "magenta") == 0) return magenta; else if (strcmp(color, "gray") == 0) return gray; return none; } /* Function returns 1 if n is an even number. * 0 is returned if n is odd. */ static int is_odd(int n) { if ( n % 2) return 1; return 0; } /* Returns the color value of LINE_COLOR or ODD_LINE_COLOR in .memorc. * This function returns NULL if USE_COLORS is set to false. * * Use is_odd_line=0 to return the value of LINE_COLOR * property. Use is_odd_line=1 to get the value of ODD_LINE_COLOR. * * If LINE_COLOR/ODD_LINE_COLOR is not set, but USE_COLORS is set to true * function will return the default color for the line. * * Not supported on Windows, returns always NULL. * */ static char *get_line_color(int is_odd_line) { #ifdef _WIN32 return NULL; #endif char *usecolors = NULL; char *color = NULL; char *defaultclr = NULL; /* Default LINE_COLOR/ODD_LINE_COLOR. */ defaultclr = "magenta"; if (is_odd_line) defaultclr = "blue"; usecolors = get_memo_conf_value("USE_COLORS"); if (!usecolors) return NULL; if (strcmp(usecolors, "no") == 0) { free(usecolors); return NULL; } if (is_odd_line) color = get_memo_conf_value("ODD_LINE_COLOR"); else color = get_memo_conf_value("LINE_COLOR"); if (!color) { color = malloc((strlen(defaultclr) + 1) * sizeof(char)); if (!color) { fail(stderr, "%s malloc failed\n", __func__); return NULL; } strcpy(color, defaultclr); } char *value = color_to_escape_seq(color); free(color); free(usecolors); return value; } static void output(char *line, int is_odd_line) { char *color = NULL; color = get_line_color(is_odd_line); if (!color) { printf("%s\n", line); } else { printf("%s%s\n", color, line); /* Reset terminal colors */ printf("\033[0m"); } } /* This functions handles the output of one line. * Postponed notes are ignored. * * Set is_odd_line to 1 if the line to be outputted is odd. */ static void output_default(char *line, int is_odd_line) { if (get_note_status(line) != POSTPONED) output(line, is_odd_line); } /* Output notes which are postponed. * Called from show_notes when command line option -P * is used. * * Set is_odd_line to 1 if the line to be outputted is odd. */ static void output_postponed(char *line, int is_odd_line) { if (get_note_status(line) == POSTPONED) output(line, is_odd_line); } /* Output notes with status UNDONE. * Called when argument -u is passed for the program. * * Set is_odd_line to 1 if the line to be outputted is odd. */ static void output_undone(char *line, int is_odd_line) { if (get_note_status(line) == UNDONE) output(line, is_odd_line); } /* Functions outputs one note line without the date part */ static void output_without_date(char *line, int is_odd_line) { char *token = strtok(line, "\t"); if (token != NULL) printf("\t%s\t", token); else goto error; token = strtok(NULL, "\t"); if (token != NULL) printf("%s\t", token); else goto error; token = strtok(NULL, "\t"); token = strtok(NULL, "\t"); if (token != NULL) output(token, is_odd_line); else goto error; return; error: fail(stderr, "%s parsing line failed\n", __func__); } /* Export current .memo file to a html file * Return the path of the html file, or NULL on failure. */ static const char *export_html(const char *path) { FILE *fp = NULL; FILE *fpm = NULL; char *line = NULL; int lines = 0; fp = fopen(path, "w"); if (!fp) { fail(stderr, "%s: failed to open %s\n", __func__, path); return NULL; } fpm = get_memo_file_ptr("r"); lines = count_file_lines(fpm); if (lines == -1) { fail(stderr, "%s: counting lines failed\n", __func__); return NULL; } if (lines == -2) { printf("Nothing to export.\n"); return NULL; } fprintf(fp, "\n"); fprintf(fp, "\n\n"); fprintf(fp, "\n"); fprintf(fp, "Memo notes\n"); fprintf(fp, "\n"); fprintf(fp, "\n\n"); fprintf(fp, "

Notes from Memo

\n"); fprintf(fp, "\n"); while (lines >= 0) { line = read_file_line(fpm); if (line) { fprintf(fp, "\n", line); free(line); } lines--; } fprintf(fp, "
%s
\n\n\n"); fclose(fp); fclose(fpm); return path; } /* Exports notes as CSV. * * id,status,date,content * 1,U,2013-11-11,some note * * Function returns the path to the CSV file or NULL on failure. */ static const char *export_csv(const char *path) { FILE *fp = NULL; FILE *fpm = NULL; char *line = NULL; int lines = 0; fp = fopen(path, "w"); if(!fp) { fail(stderr, "%s failed to open %s\n", __func__, path); return NULL; } fpm = get_memo_file_ptr("r"); lines = count_file_lines(fpm); if(lines == -1) { fail(stderr, "%s: counting lines failed\n", __func__); return NULL; } /* Ignore empty file and return */ if(lines == -2) { printf("Nothing to export.\n"); return NULL; } fprintf(fp, "ID,Status,Date,Content\n"); while (lines >= 0) { line = read_file_line(fpm); if (line) { /* Replace each occurence of tab character * with a comma. */ for (int i = 0; i < strlen(line); i++) { if (line[i] == '\t') line[i] = ','; } fprintf(fp, "%s\n", line); free(line); } lines--; } fclose(fp); fclose(fpm); return path; } /* Show latest n notes */ static void show_latest(int n) { FILE *fp = NULL; char *line; int lines = 0; int start; int current = 0; int output_count = 0; fp = get_memo_file_ptr("r"); lines = count_file_lines(fp); if (lines != -1) { /* If n is bigger than the count of lines or smaller * than zero we will show all the lines. */ if (n > lines || n < 0) start = -1; else start = lines - n; while (lines >= 0) { line = read_file_line(fp); if (line) { if (current > start) { output_count++; output(line, is_odd(output_count)); } free(line); } lines--; current++; } fclose(fp); } else fail(stderr,"%s: counting lines failed\n", __func__); } /* Deletes all notes. Function actually * simply removes .memo file. * Returns 0 on success, -1 on failure. */ static int delete_all() { char *confirm = NULL; int ask = 1; confirm = get_memo_conf_value("MEMO_CONFIRM_DELETE"); if (confirm) { if (strcmp(confirm, "no") == 0) ask = 0; free(confirm); } char *path = get_memo_file_path(); if (path == NULL) { fail(stderr,"%s error getting .memo file path\n", __func__); return -1; } if (ask) { printf("Really delete (y/N)? "); char ch = getc(stdin); if (ch == 'y' || ch == 'Y') { if (remove(path) != 0) { fail(stderr, "%s error removing %s\n", __func__, path); } } } else { if (remove(path) != 0) fail(stderr,"%s error removing %s\n", __func__, path); } free(path); return 0; } /* Delete a note by id. * * Returns 0 on success and -1 on failure. */ static int delete_note(int id) { return mark_note_status(DELETE, id); } /* Return the path to $HOME/.memorc. On failure NULL is returned. * Caller is responsible for freeing the return value. */ static char *get_memo_conf_path() { char *env = NULL; char *conf_path = NULL; size_t len = 0; env = getenv("XDG_CONFIG_HOME"); if (env == NULL) env = getenv("HOME"); #ifdef _WIN32 if (env == NULL) env = getenv("USERPROFILE"); #endif if (env == NULL){ fail(stderr,"%s: getenv failed\n", __func__); return NULL; } /* +1 for \0 byte */ len = strlen(env) + 1; /* +8 to have space for \"/.memorc\" */ conf_path = malloc( (len + 8) * sizeof(char)); if (conf_path == NULL) { fail(stderr, "%s: malloc failed\n", __func__); return NULL; } strcpy(conf_path, env); #ifdef _WIN32 strcat(conf_path, "/_memorc"); #else strcat(conf_path, "/.memorc"); #endif return conf_path; } /* ~/.memorc file format is following: * * PROPERTY=value * * e.g MEMO_PATH=/home/niko/.memo * * This function returns the value of the property. NULL is returned on * failure. On success, caller must free the return value. */ static char *get_memo_conf_value(const char *prop) { char *retval = NULL; char *conf_path = NULL; FILE *fp = NULL; conf_path = get_memo_conf_path(); if (conf_path == NULL) return NULL; fp = fopen(conf_path, "r"); if (fp == NULL) { free(conf_path); return NULL; } int lines = count_file_lines(fp); if (lines == -1) { fail(stderr, "%s: counting lines failed\n", __func__); fclose(fp); free(conf_path); return NULL; } while (lines >= 0) { char *line = read_file_line(fp); if (line) { if (strncmp(line, prop, strlen(prop)) == 0) { /* Property found, get the value */ char *token = strtok(line, "="); token = strtok(NULL, "="); if (token == NULL) { /* property does not have * a value. fail. */ fail(stderr, "%s: no value\n", prop); free(line); break; } size_t len = strlen(token) + 1; retval = malloc(len * sizeof(char)); if (retval == NULL) { fail(stderr,"%s malloc\n", __func__); free(line); break; } strcpy(retval, token); free(line); break; } free(line); } lines--; } fclose(fp); free(conf_path); return retval; } /* Returns the default path. Default path is ~/.memo * * Caller must free the return value. On failure NULL is returned. */ static char *get_memo_default_path() { char *path = NULL; size_t len = 0; char *env = getenv("HOME"); #ifdef _WIN32 if (env == NULL) env = getenv("USERPROFILE"); #endif if (env == NULL){ fail(stderr,"%s: getenv(\"HOME\") failed\n", __func__); return NULL; } /* +1 for \0 byte */ len = strlen(env) + 1; /* +6 to have space for \"/.memo\" */ path = malloc( (len + 6) * sizeof(char)); if (path == NULL) { fail(stderr,"%s: malloc failed\n", __func__); return NULL; } strcpy(path, env); #ifdef _WIN32 strcat(path, "/_memo"); #else strcat(path, "/.memo"); #endif return path; } /* Function reads MEMO_PATH environment variable to see if it's set and * uses value from it as a path. When MEMO_PATH is not set, function * reads $HOME/.memorc file. If the file is not found $HOME/.memo is * used as a fallback path. * * Returns the path to .memo file or NULL on failure. Caller is * responsible for freeing the return value. */ static char *get_memo_file_path() { char *path = NULL; char *env_path = NULL; env_path = getenv("MEMO_PATH"); /* Try and see if environment variable MEMO_PATH is set * and use value from it as a path */ if (env_path != NULL) { /* +1 for \0 byte */ path = malloc((strlen(env_path) + 1) * sizeof(char)); if (path == NULL) { fail(stderr, "%s malloc failed\n", __func__); return NULL; } strcpy(path, env_path); return path; } char *conf_path = NULL; conf_path = get_memo_conf_path(); if (conf_path == NULL) return NULL; if (!file_exists(conf_path)) { /* Config file not found, so fallback to ~/.memo */ path = get_memo_default_path(); } else { /* Configuration file found, read .memo location from it */ path = get_memo_conf_value("MEMO_PATH"); if (path == NULL) { /* Failed to get the path. Most likely user did not * specify MEMO_PATH in the configuration file at all * and configuration file is used for setting other * properties like MEMO_CONFIRM_DELETE. * * Let's default to ~/.memo */ path = get_memo_default_path(); } } free(conf_path); return path; } /* Returns temporary .memo.tmp file. It will be in the same directory * as the original .memo file. * * Returns NULL on failure. */ static char *get_temp_memo_path() { char *orig = get_memo_file_path(); if (orig == NULL) return NULL; char *tmp = malloc(sizeof(char) * (strlen(orig) + 5)); if (tmp == NULL) { free(orig); fail(stderr,"%s: malloc failed\n", __func__); return NULL; } strcpy(tmp, orig); strcat(tmp, ".tmp"); free(orig); return tmp; } /* Remove new lines from the content. Sometimes user might want to type * multiline note. This functions makes it one liner. */ static void remove_content_newlines(char *content) { char *i = content; char *j = content; while (*j != '\0') { *i = *j++; if (*i != '\n') i++; } *i = '\0'; } /* Replaces part of the note. * data is the new part defined by NotePart_t. * * Original note line is modified. * * Caller is responsible for freeing the return value. * Returns new note line on success, NULL on failure. */ static char *note_part_replace(NotePart_t part, char *note_line, const char *data) { char *new_line = NULL; int size = ((strlen(note_line) + strlen(data)) + 1) * sizeof(char); new_line = malloc(size); if (new_line == NULL) { fail(stderr, "%s: malloc failed\n", __func__); return NULL; } char *token = NULL; /* Get the id and copy it */ if ((token = strtok(note_line, "\t")) != NULL) { if (part == NOTE_ID) { /* Replace the original id with data */ if (sprintf(new_line, "%s\t", data) < 0) goto error_clean_up; } else { /* Copy the original id */ if (sprintf(new_line, "%s\t", token) < 0) goto error_clean_up; } } else { goto error_clean_up; } /* Get the status code and copy it */ if ((token = strtok(NULL, "\t")) != NULL) { if (sprintf(new_line + strlen(new_line), "%s\t", token) < 0) goto error_clean_up; } else { goto error_clean_up; } /* Get the original date */ if ( (token = strtok(NULL, "\t")) == NULL) goto error_clean_up; if (part == NOTE_DATE) { /* Copy data as the new date */ if (sprintf(new_line + strlen(new_line), "%s\t", data) < 0) goto error_clean_up; } else { /* Copy the original date */ if (sprintf(new_line + strlen(new_line), "%s\t", token) < 0) goto error_clean_up; } /* Get the original note content */ if ( (token = strtok(NULL, "\t")) == NULL) goto error_clean_up; if (part == NOTE_CONTENT) { /* Copy the data as new content */ if (sprintf(new_line + strlen(new_line), "%s", data) < 0) goto error_clean_up; } else { /* Copy the original note content, do not write \n because * the token has it already. */ if (sprintf(new_line + strlen(new_line), "%s", token) < 0) goto error_clean_up; } return new_line; error_clean_up: fail(stderr, "%s: replacing note data failed\n", __func__); free(new_line); return NULL; } /* Function replaces a note content with data. * * Data can be either a valid date or content. Replace operation is * simply done by creating a temporary file, existing notes are written * line by line to it. Line that has matching id will be written with * new data. Then the original memo file is replaced with the temporary * one. * * Returns 0 on success, -1 on failure. */ static int replace_note(int id, const char *data) { FILE *tmpfp = NULL; FILE *fp = NULL; char *memofile = NULL; char *tmpfile = NULL; int lines = 0; tmpfp = get_memo_tmpfile_ptr(); if (tmpfp == NULL) return -1; fp = get_memo_file_ptr("r"); lines = count_file_lines(fp); if (lines == -1) { fail(stderr, "%s: counting lines failed\n", __func__); fclose(tmpfp); return -1; } /* Empty file, ignore. */ if (lines == -2) { fclose(fp); fclose(tmpfp); return -1; } memofile = get_memo_file_path(); if (memofile == NULL) { fail(stderr, "%s failed to get memo file path\n", __func__); fclose(fp); fclose(tmpfp); return -1; } tmpfile = get_temp_memo_path(); if (tmpfile == NULL) { fail(stderr, "%s failed to get memo tmp path\n", __func__); fclose(fp); fclose(tmpfp); free(memofile); return -1; } while (lines >= 0) { char *line = read_file_line(fp); if (line) { int curr_id = get_note_id_from_line(line); if (curr_id == id) { /* Found the note to be replaced * Check if user wants to replace the date * by validating the data as date. Otherwise * assume content is being replaced. */ if (is_valid_date_format(data, 1) == 0) { char *new_line = NULL; new_line = note_part_replace(NOTE_DATE, line, data); if (new_line == NULL) { printf("Unable to replace note %d\n", id); free(memofile); free(tmpfile); fclose(fp); fclose(tmpfp); return -1; } fprintf(tmpfp, "%s\n", new_line); free(new_line); } else { char *new_line = NULL; new_line = note_part_replace(NOTE_CONTENT, line, data); if (new_line == NULL) { printf("Unable to replace note %d\n", id); free(memofile); free(tmpfile); fclose(fp); fclose(tmpfp); return -1; } fprintf(tmpfp, "%s\n", new_line); free(new_line); } } else { fprintf(tmpfp, "%s\n", line); } free(line); } lines--; } fclose(fp); fclose(tmpfp); if (file_exists(memofile)) remove(memofile); rename(tmpfile, memofile); remove(tmpfile); free(memofile); free(tmpfile); return 0; } /* Simple helper function to convert integer to string. * * Returns the integer as string, on failure returns NULL. * Caller is responsible for freeing the return value. */ static char *integer_to_string(int id) { char *buffer = NULL; /* Really, this should be enough space to hold our integer * for the note id... */ buffer = malloc(15 * sizeof(char)); if (buffer == NULL) { fail(stderr, "%s: malloc failed\n", __func__); return NULL; } if (snprintf(buffer, 15, "%d", id) < 0) { fail(stderr, "%s: convert failed\n", __func__); free(buffer); return NULL; } return buffer; } /* Function organizes note id codes. * * In Memo, if you have notes with id codes 1,2,3 and user deletes note * 2, remaining notes will be 1 and 3. This function organizes those * id codes so that the codes would be 1 and 2. The reason why Memo does * not do this automatically is because one might want to be able * to trust that the id codes never change (for example if Memo is used * as a part of some script) * * Returns 0 on success, -1 on failure. */ static int organize_note_identifiers() { FILE *tmpfp = NULL; FILE *fp = NULL; char *memofile = NULL; char *tmpfile = NULL; int lines = 0; int id_counter = 1; tmpfp = get_memo_tmpfile_ptr(); if (tmpfp == NULL) return -1; fp = get_memo_file_ptr("r"); lines = count_file_lines(fp); if (lines == -1) { fail(stderr, "%s: counting lines failed\n", __func__); fclose(tmpfp); return -1; } /* An empty memo file, ignore and exit */ if (lines == -2) { fclose(fp); fclose(tmpfp); return -1; } memofile = get_memo_file_path(); if (memofile == NULL) { fail(stderr, "%s failed to get memo file path\n", __func__); fclose(fp); fclose(tmpfp); return -1; } tmpfile = get_temp_memo_path(); if (tmpfile == NULL) { fail(stderr, "%s failed to get memo tmp path\n", __func__); fclose(fp); fclose(tmpfp); free(memofile); return -1; } while (lines >= 0) { char *line = read_file_line(fp); if (line) { /* Replace each note id with the value * from id_counter which starts from one. * id_counter is increased for every line. */ char *new_line = NULL; char *id = integer_to_string(id_counter); if (id == NULL) { fail(stderr, "%s: fatal error\n", __func__); free(memofile); free(tmpfile); fclose(fp); fclose(tmpfp); return -1; } new_line = note_part_replace(NOTE_ID, line, id); if (new_line == NULL) { fail(stderr, "%s: fatal error\n", __func__); free(memofile); free(tmpfile); fclose(fp); fclose(tmpfp); return -1; } fprintf(tmpfp, "%s\n", new_line); id_counter++; free(id); free(new_line); free(line); } lines--; } fclose(fp); fclose(tmpfp); if (file_exists(memofile)) remove(memofile); rename(tmpfile, memofile); remove(tmpfile); free(memofile); free(tmpfile); return 0; } /* .memo file format is following: * * id status date content * | | | | * |- id |-U/D/P |- yyy-MM-dd |- actual note * * sections are separated by a tab character * * Parameter date can be NULL. If date is given in valid * format(yyyy-MM-dd) it will be used for creating the note. If date is * NULL, current date will be used instead. * * Note will be marked with status "U" which means it's "undone". "D" * means "done". With status P, note is marked as postponed. */ static int add_note(char *content, const char *date) { FILE *fp = NULL; time_t t; struct tm *ti; int id = -1; char note_date[11]; /* Do not add an empty note */ if (strlen(content) == 0) return -1; remove_content_newlines(content); fp = get_memo_file_ptr("a"); if (fp == NULL) { fail(stderr,"%s: Error opening ~/.memo\n", __func__); return -1; } id = get_next_id(); if (id == -1) id = 1; if (date != NULL) { /* Date is already validated, so just copy it * for later use. */ strcpy(note_date, date); } else { time(&t); ti = localtime(&t); strftime(note_date, 11, "%Y-%m-%d", ti); } fprintf(fp, "%d\t%s\t%s\t%s\n", id, "U", note_date, content); fclose(fp); return id; } static void usage() { #define HELP "\ SYNOPSIS\n\ \n\ memo [options]\n\ \n\ OPTIONS\n\ \n\ -a, --add [yyyy-MM-dd] Add a new note with optional date\n\ -d, --delete Delete note by id\n\ -D, --delete-all Delete all notes\n\ -e, --export Export notes a file\n\ Format must be either csv or html\n\ -f, --search Find notes by search term\n\ -F, --regex Find notes by regular expression\n\ -i, --stdin Read from stdin until ^D\n\ -l, --latest Show latest n notes\n\ -m, --set-done Mark note status as done\n\ -M, --set-undone Mark note status as undone\n\ -o, --list-date Show all notes organized by date\n\ -O, --organize Reorder and organize note id codes\n\ -p, --path Show current memo file path\n\ -P, --postpone [id] Show postponed or mark note as postponed\n\ -R, --delete-done Delete all notes marked as done\n\ -r, --replace [content]/[yyyy-MM-dd] Replace note content or date\n\ -s, --list Show all notes except postponed\n\ (Same as simply running memo)\n\ -T, --set-done-all Mark all notes as done\n\ -u, --list-undone Show only undone notes\n\ \n\ - Read from stdin\n\ -h, --help Show short help and exit. This page\n\ -V, --version Show version number of program\n\ \n\ For more information and examples see man memo(1).\n\ \n\ AUTHORS\n\ Copyright (C) 2014-2019 Niko Rosvall \n\ \n\ Released under license GPL-3+. For more information, see\n\ http://www.gnu.org/licenses\n\ " printf(HELP); } /* Function outputs currently used memo file path * to stdin. */ static void show_memo_file_path() { char *path = NULL; path = get_memo_file_path(); if (path == NULL) { fail(stderr,"%s: can't retrieve path\n", __func__); } else { printf("%s\n", path); free(path); } } /* Function sorts the dates elements in the order of date. * * Make the *dates[] again. */ static void sort_dates_ascend(char *dates[], int date_index) { int dates_int[date_index]; /* Remove "-" from the dates elements and convert them into integer. */ for (int i = 0; i < date_index; i++) { char *p = dates[i], *q = dates[i]; while((*p = *q++)) p += (*p != '-'); dates_int[i] = atoi(dates[i]); } /* Sort the dates_int elements in ascending order. */ qsort((void *)dates_int , date_index , sizeof(dates_int[0]), int_sort); /* For each of dates_int elements, * make a string in valid date format ("yyyy-mm-dd") and reallocate it to dates. */ for (int i = 0; i < date_index; i++) { dates[i][0] = '\0'; /* Pick up the 4-digit year from dates_int[i]. */ strcat(dates[i], integer_to_string(dates_int[i]/10000000)); strcat(dates[i], integer_to_string((dates_int[i]/1000000) % 10)); strcat(dates[i], integer_to_string((dates_int[i]/100000) % 10)); strcat(dates[i], integer_to_string((dates_int[i]/10000) % 10)); strcat(dates[i], "-"); /* Pick up the 2-digit month from dates_int[i]. */ strcat(dates[i], integer_to_string((dates_int[i]/1000) % 10)); strcat(dates[i], integer_to_string((dates_int[i]/100) % 10)); strcat(dates[i], "-"); /* Pick up the 2-digit day from dates_int[i]. */ strcat(dates[i], integer_to_string((dates_int[i]/10) % 10)); strcat(dates[i], integer_to_string(dates_int[i] % 10)); } } /* Comparator function needed for qsort function. * * Returns 1 if *a > *b, 0 if *a = *b, -1 if *a < *b. */ static int int_sort(const void *a, const void *b) { if (*(int *)a < *(int *)b) { return -1; } else if (*(int *)a == *(int *)b) { return 0; } return 1; } /* Program entry point */ int main(int argc, char *argv[]) { char *path = NULL; int c; char *stdinline = NULL; int has_valid_options = 0; int organize_note_ids = 0; path = get_memo_file_path(); if (path == NULL) return -1; if (!file_exists(path)) { int fd = open(path, O_RDWR | O_CREAT, S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH); if (fd == -1) { fail(stderr,"%s: failed to create empty memo\n", __func__); free(path); return -1; } close(fd); } opterr = 0; /* This function is applied only if there's MARK_AS_DONE * property available in ~/.memorc */ mark_old_as_done(); if (argc == 1) { /* No arguments given, so just show notes */ show_notes(-1); } static struct option long_options[] = { {"add", required_argument, 0, 'a'}, {"delete", required_argument, 0, 'd'}, {"delete-all", no_argument, 0, 'D'}, {"export", required_argument, 0, 'e'}, {"search", required_argument, 0, 'f'}, {"regex", required_argument, 0, 'F'}, {"stdin", no_argument, 0, 'i'}, {"latest", required_argument, 0, 'l'}, {"set-done", required_argument, 0, 'm'}, {"set-undone", required_argument, 0, 'M'}, {"by-date", no_argument, 0, 'o'}, {"organize", no_argument, 0, 'O'}, {"path", no_argument, 0, 'p'}, {"postpone", no_argument, 0, 'P'}, {"delete-done", no_argument, 0, 'R'}, {"replace", required_argument, 0, 'r'}, {"list", no_argument, 0, 's'}, {"set-done-all", no_argument, 0, 'T'}, {"list-undone", no_argument, 0, 'T'}, {"help", no_argument, 0, 'h'}, {"version", no_argument, 0, 'V'}, {0, 0, 0, 0} }; /* getopt_long stores the option index here. */ int option_index = 0; while ((c = getopt_long(argc, argv, "a:d:De:f:F:hil:m:M:oOpPr:RsTuV", long_options, &option_index)) != -1){ has_valid_options = 1; switch(c) { case 'a': if (argv[optind]) { if (is_valid_date_format(argv[optind], 0) == 0) add_note(optarg, argv[optind]); } else { add_note(optarg,NULL); } break; case 'd': delete_note(atoi(optarg)); break; case 'D': delete_all(); break; case 'e': if (argv[optind]) { if (strcmp(optarg, "csv") == 0) { export_csv(argv[optind]); } else if(strcmp(optarg, "html") == 0) { export_html(argv[optind]); } } break; case 'f': search_notes(optarg); break; case 'F': search_regexp(optarg); break; case 'h': usage(); break; case 'i': add_notes_from_stdin(); break; case 'o': show_notes_tree(); break; case 'O': organize_note_ids = 1; break; case 'l': show_latest(atoi(optarg)); break; case 'm': mark_note_status(DONE, atoi(optarg)); break; case 'M': mark_note_status(UNDONE, atoi(optarg)); break; case 'p': show_memo_file_path(); break; case 'P': if (argv[optind]) mark_note_status(POSTPONED, atoi(argv[optind])); else show_notes(POSTPONED); break; case 'r': { int id = atoi(optarg); if (argv[optind]) { replace_note(id, argv[optind]); } else { printf("Missing argument date or content, see -h\n"); free(path); return 0; } break; } case 'R': mark_note_status(DELETE_DONE, -1); break; case 's': show_notes(-1); break; case 'T': mark_note_status(ALL_DONE, -1); break; case 'u': show_notes(UNDONE); break; case 'V': printf("Memo version %s\n", VERSION); break; case '?': if (optopt == 'a') printf("-a missing an argument \n"); else if (optopt == 'd') printf("-d missing an argument \n"); else if (optopt == 'e') printf("-e missing an argument \n"); else if (optopt == 'f') printf("-f missing an argument \n"); else if (optopt == 'F') printf("-F missing an argument \n"); else if (optopt == 'l') printf("-l missing an argument \n"); else if (optopt == 'm') printf("-m missing an argument \n"); else if(optopt == 'M') printf("-M missing an argument \n"); else if(optopt == 'r') printf("-r missing an argument \n"); else printf("invalid option, see memo -h for help\n"); break; } } if (organize_note_ids) organize_note_identifiers(); /* Handle argument '-' to read line from stdin */ if (argc > 1 && *argv[argc - 1] == '-' && strlen(argv[argc - 1]) == 1) { has_valid_options = 1; stdinline = read_file_line(stdin); if (stdinline) { add_note(stdinline, NULL); free(stdinline); } } if (argc > 1 && !has_valid_options) printf("invalid input, see memo -h for help\n"); free(path); return 0; }