pax_global_header00006660000000000000000000000064124326765600014525gustar00rootroot0000000000000052 comment=a7119480dd2187cb4da9162ac1ec742d6e709bf9 odt2txt-0.5/000077500000000000000000000000001243267656000130015ustar00rootroot00000000000000odt2txt-0.5/GPL-2000066400000000000000000000431101243267656000135040ustar00rootroot00000000000000 GNU GENERAL PUBLIC LICENSE Version 2, June 1991 Copyright (C) 1989, 1991 Free Software Foundation, Inc. 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble The licenses for most software are designed to take away your freedom to share and change it. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change free software--to make sure the software is free for all its users. This General Public License applies to most of the Free Software Foundation's software and to any other program whose authors commit to using it. (Some other Free Software Foundation software is covered by the GNU Library General Public License instead.) You can apply it to your programs, too. When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for this service if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs; and that you know you can do these things. To protect your rights, we need to make restrictions that forbid anyone to deny you these rights or to ask you to surrender the rights. These restrictions translate to certain responsibilities for you if you distribute copies of the software, or if you modify it. For example, if you distribute copies of such a program, whether gratis or for a fee, you must give the recipients all the rights that you have. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights. We protect your rights with two steps: (1) copyright the software, and (2) offer you this license which gives you legal permission to copy, distribute and/or modify the software. Also, for each author's protection and ours, we want to make certain that everyone understands that there is no warranty for this free software. If the software is modified by someone else and passed on, we want its recipients to know that what they have is not the original, so that any problems introduced by others will not reflect on the original authors' reputations. Finally, any free program is threatened constantly by software patents. We wish to avoid the danger that redistributors of a free program will individually obtain patent licenses, in effect making the program proprietary. To prevent this, we have made it clear that any patent must be licensed for everyone's free use or not licensed at all. The precise terms and conditions for copying, distribution and modification follow. GNU GENERAL PUBLIC LICENSE TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 0. This License applies to any program or other work which contains a notice placed by the copyright holder saying it may be distributed under the terms of this General Public License. The "Program", below, refers to any such program or work, and a "work based on the Program" means either the Program or any derivative work under copyright law: that is to say, a work containing the Program or a portion of it, either verbatim or with modifications and/or translated into another language. (Hereinafter, translation is included without limitation in the term "modification".) Each licensee is addressed as "you". Activities other than copying, distribution and modification are not covered by this License; they are outside its scope. The act of running the Program is not restricted, and the output from the Program is covered only if its contents constitute a work based on the Program (independent of having been made by running the Program). Whether that is true depends on what the Program does. 1. You may copy and distribute verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice and disclaimer of warranty; keep intact all the notices that refer to this License and to the absence of any warranty; and give any other recipients of the Program a copy of this License along with the Program. You may charge a fee for the physical act of transferring a copy, and you may at your option offer warranty protection in exchange for a fee. 2. You may modify your copy or copies of the Program or any portion of it, thus forming a work based on the Program, and copy and distribute such modifications or work under the terms of Section 1 above, provided that you also meet all of these conditions: a) You must cause the modified files to carry prominent notices stating that you changed the files and the date of any change. b) You must cause any work that you distribute or publish, that in whole or in part contains or is derived from the Program or any part thereof, to be licensed as a whole at no charge to all third parties under the terms of this License. c) If the modified program normally reads commands interactively when run, you must cause it, when started running for such interactive use in the most ordinary way, to print or display an announcement including an appropriate copyright notice and a notice that there is no warranty (or else, saying that you provide a warranty) and that users may redistribute the program under these conditions, and telling the user how to view a copy of this License. (Exception: if the Program itself is interactive but does not normally print such an announcement, your work based on the Program is not required to print an announcement.) These requirements apply to the modified work as a whole. If identifiable sections of that work are not derived from the Program, and can be reasonably considered independent and separate works in themselves, then this License, and its terms, do not apply to those sections when you distribute them as separate works. But when you distribute the same sections as part of a whole which is a work based on the Program, the distribution of the whole must be on the terms of this License, whose permissions for other licensees extend to the entire whole, and thus to each and every part regardless of who wrote it. Thus, it is not the intent of this section to claim rights or contest your rights to work written entirely by you; rather, the intent is to exercise the right to control the distribution of derivative or collective works based on the Program. In addition, mere aggregation of another work not based on the Program with the Program (or with a work based on the Program) on a volume of a storage or distribution medium does not bring the other work under the scope of this License. 3. You may copy and distribute the Program (or a work based on it, under Section 2) in object code or executable form under the terms of Sections 1 and 2 above provided that you also do one of the following: a) Accompany it with the complete corresponding machine-readable source code, which must be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or, b) Accompany it with a written offer, valid for at least three years, to give any third party, for a charge no more than your cost of physically performing source distribution, a complete machine-readable copy of the corresponding source code, to be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or, c) Accompany it with the information you received as to the offer to distribute corresponding source code. (This alternative is allowed only for noncommercial distribution and only if you received the program in object code or executable form with such an offer, in accord with Subsection b above.) The source code for a work means the preferred form of the work for making modifications to it. For an executable work, complete source code means all the source code for all modules it contains, plus any associated interface definition files, plus the scripts used to control compilation and installation of the executable. However, as a special exception, the source code distributed need not include anything that is normally distributed (in either source or binary form) with the major components (compiler, kernel, and so on) of the operating system on which the executable runs, unless that component itself accompanies the executable. If distribution of executable or object code is made by offering access to copy from a designated place, then offering equivalent access to copy the source code from the same place counts as distribution of the source code, even though third parties are not compelled to copy the source along with the object code. 4. You may not copy, modify, sublicense, or distribute the Program except as expressly provided under this License. Any attempt otherwise to copy, modify, sublicense or distribute the Program is void, and will automatically terminate your rights under this License. However, parties who have received copies, or rights, from you under this License will not have their licenses terminated so long as such parties remain in full compliance. 5. You are not required to accept this License, since you have not signed it. However, nothing else grants you permission to modify or distribute the Program or its derivative works. These actions are prohibited by law if you do not accept this License. Therefore, by modifying or distributing the Program (or any work based on the Program), you indicate your acceptance of this License to do so, and all its terms and conditions for copying, distributing or modifying the Program or works based on it. 6. Each time you redistribute the Program (or any work based on the Program), the recipient automatically receives a license from the original licensor to copy, distribute or modify the Program subject to these terms and conditions. You may not impose any further restrictions on the recipients' exercise of the rights granted herein. You are not responsible for enforcing compliance by third parties to this License. 7. If, as a consequence of a court judgment or allegation of patent infringement or for any other reason (not limited to patent issues), conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot distribute so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not distribute the Program at all. For example, if a patent license would not permit royalty-free redistribution of the Program by all those who receive copies directly or indirectly through you, then the only way you could satisfy both it and this License would be to refrain entirely from distribution of the Program. If any portion of this section is held invalid or unenforceable under any particular circumstance, the balance of the section is intended to apply and the section as a whole is intended to apply in other circumstances. It is not the purpose of this section to induce you to infringe any patents or other property right claims or to contest validity of any such claims; this section has the sole purpose of protecting the integrity of the free software distribution system, which is implemented by public license practices. Many people have made generous contributions to the wide range of software distributed through that system in reliance on consistent application of that system; it is up to the author/donor to decide if he or she is willing to distribute software through any other system and a licensee cannot impose that choice. This section is intended to make thoroughly clear what is believed to be a consequence of the rest of this License. 8. If the distribution and/or use of the Program is restricted in certain countries either by patents or by copyrighted interfaces, the original copyright holder who places the Program under this License may add an explicit geographical distribution limitation excluding those countries, so that distribution is permitted only in or among countries not thus excluded. In such case, this License incorporates the limitation as if written in the body of this License. 9. The Free Software Foundation may publish revised and/or new versions of the General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Program specifies a version number of this License which applies to it and "any later version", you have the option of following the terms and conditions either of that version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of this License, you may choose any version ever published by the Free Software Foundation. 10. If you wish to incorporate parts of the Program into other free programs whose distribution conditions are different, write to the author to ask for permission. For software which is copyrighted by the Free Software Foundation, write to the Free Software Foundation; we sometimes make exceptions for this. Our decision will be guided by the two goals of preserving the free status of all derivatives of our free software and of promoting the sharing and reuse of software generally. NO WARRANTY 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. END OF TERMS AND CONDITIONS How to Apply These Terms to Your New Programs If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it 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 convey the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. 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 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA Also add information on how to contact you by electronic and paper mail. If the program is interactive, make it output a short notice like this when it starts in an interactive mode: Gnomovision version 69, Copyright (C) year name of author Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details. The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, the commands you use may be called something other than `show w' and `show c'; they could even be mouse-clicks or menu items--whatever suits your program. You should also get your employer (if you work as a programmer) or your school, if any, to sign a "copyright disclaimer" for the program, if necessary. Here is a sample; alter the names: Yoyodyne, Inc., hereby disclaims all copyright interest in the program `Gnomovision' (which makes passes at compilers) written by James Hacker. , 1 April 1989 Ty Coon, President of Vice This General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Library General Public License instead of this License. odt2txt-0.5/INSTALL000066400000000000000000000044651243267656000140430ustar00rootroot00000000000000 odt2txt is known to compile on Linux, Windows (Cygwin and native), Solaris, FreeBSD, OpenBSD and NetBSD. To build odt2txt you need GNU make on all platforms. On platforms other than Linux and Cygwin, it is usually called "gmake". Linux: A modern Linux system has everything you need in the libc. Just run "make" in the source directory. Solaris: Everything you need comes with the system. I have test-compiled odt2txt on Solaris 9 (sparc) and Solaris 10 (x86), both with gcc and the Sun C Compiler. FreeBSD/OpenBSD: You need to install libiconv from the ports. The regex library that comes with FreeBSD is extremely slow on my FreeBSD system (5.3, i386). Mac OS X: libiconv has to be installed separately. The Makefile contains support for a MacPorts installation: - install MacPorts http://www.macports.org/ - install libiconv in MacPorts $ sudo port install libiconv - run "make" in the source directory NetBSD: NetBSD > 2.0 comes with an iconv implementation, it has everything you need. HP-UX: If zlib is not already installed on the system, build it. Then build odt2txt with "gmake ZLIB_DIR=/path/to/zlib" Windows (Cygwin): You need to install libiconv. Windows (mingw32): This is a little harder, but will produce a binary that has no further dependencies. I don't have a Windows system here but I have a Debian Sarge system with a cross-compile environment. The resulting binary has been reported to work without problems. I guess the same process should work with a native mingw environment in a similar way. Install mingw32, mingw32-binutils and mingw32-runtime. Download and untar GNU libiconv, configure and build and install it: $ ./configure --host=i586-mingw32msvc --prefix=/usr/i586-mingw32msvc/ $ make $ su -c "make install" Download GNU regex-0.12, untar it (for example to /tmp/regex-0.12) and compile the source file: $ i586-mingw32msvc-gcc -DSTDC_HEADERS=1 -c regex.c Then go into the odt2txt source directory and build it: $ make CC=i586-mingw32msvc-gcc MINGW32=1 REGEX_DIR=/tmp/regex-0.12 The result should be a file named odt2txt.exe. The only dependency is the file libiconv-2.dll which was built from your iconv source directory. You can also link statically against libiconv if you add STATIC=1 ICONV_DIR= to the make command line. odt2txt-0.5/Makefile000066400000000000000000000044671243267656000144540ustar00rootroot00000000000000 UNAME_S := $(shell uname -s 2>/dev/null || echo unknown) UNAME_O := $(shell uname -o 2>/dev/null || echo unknown) ifdef DEBUG CFLAGS = -O0 -g -Wextra -DMEMDEBUG -DSTRBUF_CHECK #LDFLAGS = -lefence LDFLAGS += -g else CFLAGS = -O2 endif ifdef NO_ICONV CFLAGS += -DNO_ICONV endif LIBS = -lz ZIP_OBJS = ifdef HAVE_LIBZIP CFLAGS += -DHAVE_LIBZIP LIBS += -lzip else ZIP_OBJS = kunzip/fileio.o kunzip/zipfile.o endif OBJ = odt2txt.o regex.o mem.o strbuf.o $(ZIP_OBJS) TEST_OBJ = t/test-strbuf.o t/test-regex.o ALL_OBJ = $(OBJ) $(TEST_OBJ) INSTALL = install GROFF = groff DESTDIR = /usr/local PREFIX = BINDIR = $(PREFIX)/bin MANDIR = $(PREFIX)/share/man MAN1DIR = $(MANDIR)/man1 ifeq ($(UNAME_S),FreeBSD) CFLAGS += -DICONV_CHAR="const char" -I/usr/local/include LDFLAGS += -L/usr/local/lib LIBS += -liconv endif ifeq ($(UNAME_S),OpenBSD) CFLAGS += -DICONV_CHAR="const char" -I/usr/local/include LDFLAGS += -L/usr/local/lib LIBS += -liconv endif ifeq ($(UNAME_S),Darwin) CFLAGS += -I/opt/local/include LDFLAGS += -L/opt/local/lib LIBS += -liconv endif ifeq ($(UNAME_S),NetBSD) CFLAGS += -DICONV_CHAR="const char" endif ifeq ($(UNAME_S),SunOS) ifeq ($(CC),cc) ifdef DEBUG CFLAGS = -v -g -DMEMDEBUG -DSTRBUF_CHECK else CFLAGS = -xO3 endif endif CFLAGS += -DICONV_CHAR="const char" endif ifeq ($(UNAME_S),HP-UX) CFLAGS += -I$(ZLIB_DIR) LIBS = $(ZLIB_DIR)/libz.a endif ifeq ($(UNAME_O),Cygwin) CFLAGS += -DICONV_CHAR="const char" LIBS += -liconv EXT = .exe endif ifneq ($(MINGW32),) CFLAGS += -DICONV_CHAR="const char" -I$(REGEX_DIR) -I$(ZLIB_DIR) LIBS = $(REGEX_DIR)/regex.o ifdef STATIC LIBS += $(wildcard $(ICONV_DIR)/lib/.libs/*.o) LIBS += $(ZLIB_DIR)/zlib.a else LIBS += -liconv endif EXT = .exe endif BIN = odt2txt$(EXT) MAN = odt2txt.1 $(BIN): $(OBJ) $(CC) -o $@ $(LDFLAGS) $(OBJ) $(LIBS) t/test-strbuf: t/test-strbuf.o strbuf.o mem.o t/test-regex: t/test-regex.o regex.o strbuf.o mem.o $(ALL_OBJ): Makefile all: $(BIN) install: $(BIN) $(MAN) $(INSTALL) -d -m755 $(DESTDIR)$(BINDIR) $(INSTALL) $(BIN) $(DESTDIR)$(BINDIR) $(INSTALL) -d -m755 $(DESTDIR)$(MAN1DIR) $(INSTALL) $(MAN) $(DESTDIR)$(MAN1DIR) odt2txt.html: $(MAN) $(GROFF) -Thtml -man $(MAN) > $@ odt2txt.ps: $(MAN) $(GROFF) -Tps -man $(MAN) > $@ clean: rm -fr $(OBJ) $(BIN) odt2txt.ps odt2txt.html .PHONY: clean odt2txt-0.5/README.md000066400000000000000000000015601243267656000142620ustar00rootroot00000000000000# odt2txt A simple converter from OpenDocument Text to plain text odt2txt is a command-line tool which extracts the text out of OpenDocument Texts produced by LibreOffice, OpenOffice, StarOffice, KOffice and others. odt2txt can also extract text from some file formats similar to OpenDocument Text, such as OpenOffice.org XML, which was used by OpenOffice.org version 1.x and older StarOffice versions. To a lesser extent, odt2txt may be useful to extract content from OpenDocument spreadsheets and OpenDocument presentations. odt2txt is… * small * supports multiple output encodings * adopts to your locale * able to substitute common characters which the output charset does not contain with ascii look-a-likes * written in C, has few dependencies * portable (runs on Linux, Mac OS X, Windows, *BSD, Cygwin, Solaris, HP-UX) * licensed under GPL, version 2 odt2txt-0.5/kunzip/000077500000000000000000000000001243267656000143215ustar00rootroot00000000000000odt2txt-0.5/kunzip/fileio.c000066400000000000000000000020231243267656000157310ustar00rootroot00000000000000#include #include /* This code is Copyright 2005-2006 by Michael Kohn This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License, version 2 as published by the Free Software Foundation */ int read_int(FILE *in) { int c; c = getc(in); c = c | (getc(in) << 8); c = c | (getc(in) << 16); c = c | (getc(in) << 24); return c; } int read_word(FILE *in) { int c; c = getc(in); c = c | (getc(in) << 8); return c; } int read_chars(FILE *in, char *s, int count) { int t; for (t = 0; t < count; t++) { s[t] = getc(in); } s[t] = 0; return 0; } int read_int_b(FILE *in) { int c; c = getc(in); c = (c << 8) + getc(in); c = (c << 8) + getc(in); c = (c << 8) + getc(in); return c; } int read_word_b(FILE *in) { int c; c = getc(in); c = (c << 8) + getc(in); return c; } int read_buffer(FILE *in, unsigned char *buffer, int len) { int t; t = 0; while (t < len) { t = t + fread(buffer + t, 1, len - t, in); } return t; } odt2txt-0.5/kunzip/fileio.h000066400000000000000000000003231243267656000157370ustar00rootroot00000000000000 int read_int(FILE *in); int read_word(FILE *in); int read_chars(FILE *in, char *s, int count); int read_int_b(FILE *in); int read_word_b(FILE *in); int read_buffer(FILE *in, unsigned char *buffer, int len); odt2txt-0.5/kunzip/kunzip.h000066400000000000000000000035701243267656000160170ustar00rootroot00000000000000#include "../strbuf.h" /* ABOUT THIS FILE: kunzip is a library created by Michael Kohn for dealing with zip files. This kunzip.h is basically the the documentation on how to make calls to the library. If you need help, feel free to email Michael Kohn. /mike mike@mikekohn.net http://www.mikekohn.net/ */ STRBUF *kunzip_next_tobuf(char *zip_filename, int offset); /* kunzip_get_offset_by_name - Search through a zip archive for a filename that either partially or exactly matches. If offset is set to -1, the search will start at the start of the file, otherwise the search will start at the next file after the offset. Match Flags: bit 0: set to 1 if it should be exact filename match set to 0 if the archived filename only needs to contain that word bit 1: set to 1 if it should be case sensitive set to 0 if it should be case insensitive in other words: match_flags=0: case insensitive, partial match search match_flags=1: case insensitive, exact match search match_flags=2: case sensitive, partial match search match_flags=3: case insensitive, exact match search Examples: offset=kunzip_get_offset_by_name("test.zip","mike.c",0,-1); offset=kunzip_get_offset_by_name("test.zip","mike.c",0,offset); after the first line above runs, offset will point to the first file in test.zip that contains mike.c. After the second line runs, offset will point to the next file in the archive whos filename contains mike.c. */ int kunzip_get_offset_by_name(char *zip_filename, char *compressed_filename, int match_flags, int skip_offset); /* kunzip_get_version - Get the current kunzip library version. Example: char version[128]; kunzip_get_version(version); printf("%s\n",version); */ int kunzip_get_version(char *version_string); odt2txt-0.5/kunzip/zipfile.c000066400000000000000000000162451243267656000161370ustar00rootroot00000000000000#include #include #include #include #include #include #include #include #include "fileio.h" #include "zipfile.h" #include "kunzip.h" #include "../strbuf.h" #include "../mem.h" /* This code is Copyright 2005-2006 by Michael Kohn This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License, version 2 as published by the Free Software Foundation */ #define BUFFER_SIZE 16738 /* #define _GNU_SOURCE */ unsigned int copy_file_tobuf(FILE *in, STRBUF *out, int len) { unsigned char buffer[BUFFER_SIZE]; uLong checksum; int t, r; checksum = crc32(0L, Z_NULL, 0); t = 0; while (t < len) { if (t + BUFFER_SIZE < len) { r = BUFFER_SIZE; } else { r = len - t; } read_buffer(in, buffer, r); strbuf_append_n(out, (char *)buffer, r); checksum = crc32(checksum, buffer, r); t = t + r; } return checksum; } int read_zip_header(FILE *in, struct zip_local_file_header_t *local_file_header) { local_file_header->signature = read_int(in); if (local_file_header->signature != 0x04034b50) return -1; local_file_header->version = read_word(in); local_file_header->general_purpose_bit_flag = read_word(in); local_file_header->compression_method = read_word(in); local_file_header->last_mod_file_time = read_word(in); local_file_header->last_mod_file_date = read_word(in); local_file_header->crc_32 = read_int(in); local_file_header->compressed_size = read_int(in); local_file_header->uncompressed_size = read_int(in); local_file_header->file_name_length = read_word(in); local_file_header->extra_field_length = read_word(in); local_file_header->descriptor_length = 0; /* if the 4th bit in the general_purpose_bit_flag is set, crc32, compressed_size and uncompressed_size are written into a data descriptor that follows the compressed data */ if (local_file_header->general_purpose_bit_flag & 8) { long data_start = ftell(in); unsigned int signature; while (1) { signature = read_int(in); if (feof(in)) { fseek(in, data_start, SEEK_SET); return -1; } if (signature == 0x08074b50) { local_file_header->crc_32 = read_int(in); local_file_header->compressed_size = read_int(in); local_file_header->uncompressed_size = read_int(in); local_file_header->descriptor_length = 16; fseek(in, data_start, SEEK_SET); return 0; } fseek(in, -3, SEEK_CUR); } } return 0; } #ifdef DEBUG int print_zip_header(struct zip_local_file_header_t *local_file_header) { printf("ZIP LOCAL FILE HEADER\n"); printf("----------------------------------\n"); printf("Signature: %02x%02x%02x%02x\n", ((local_file_header->signature >> 24) & 255), ((local_file_header->signature >> 16) & 255), ((local_file_header->signature >> 8) & 255), (local_file_header->signature & 255)); printf("Version: %d\n", local_file_header->version); printf("General Purpose Bit Flag: %d\n", local_file_header->general_purpose_bit_flag); printf("Compression Method: %d\n", local_file_header->compression_method); printf("Last Mod File Time: %d\n", local_file_header->last_mod_file_time); printf("Last Mod File Date: %d\n", local_file_header->last_mod_file_date); printf("CRC-32: %d\n", local_file_header->crc_32); printf("Compressed Size: %d\n", local_file_header->compressed_size); printf("Uncompressed Size: %d\n", local_file_header->uncompressed_size); printf("File Name Length: %d\n", local_file_header->file_name_length); printf("Extra Field Length: %d\n", local_file_header->extra_field_length); printf("File Name: %s\n", local_file_header->file_name); return 0; } #endif STRBUF *kunzip_file_tobuf(FILE *in) { STRBUF *out; struct zip_local_file_header_t local_file_header; int checksum; long marker; if (read_zip_header(in, &local_file_header) == -1) return NULL; local_file_header.file_name = (char *)ymalloc(local_file_header.file_name_length + 1); local_file_header.extra_field = (unsigned char *)ymalloc(local_file_header.extra_field_length + 1); read_chars(in, local_file_header.file_name, local_file_header.file_name_length); read_chars(in, (char *)local_file_header.extra_field, local_file_header.extra_field_length); marker = ftell(in); #ifdef DEBUG print_zip_header(&local_file_header); #endif out = strbuf_new(); if (local_file_header.compression_method == 0) { checksum = copy_file_tobuf(in, out, local_file_header.uncompressed_size); } else if (local_file_header.compression_method == Z_DEFLATED) { (void)strbuf_append_inflate(out, in); checksum = strbuf_crc32(out); } else { fprintf(stderr, "Unknown compression method\n"); exit(EXIT_FAILURE); } if ((unsigned int)checksum != local_file_header.crc_32 && local_file_header.crc_32 != 0) { fprintf(stderr, "Warning: Checksum does not match: %d %d.\nPossibly the file" " is corrupted otr truncated.\n", checksum, local_file_header.crc_32); } yfree(local_file_header.file_name); yfree(local_file_header.extra_field); fseek(in, marker + local_file_header.compressed_size, SEEK_SET); if ((local_file_header.general_purpose_bit_flag & 8) != 0) { read_int(in); read_int(in); read_int(in); } return out; } STRBUF *kunzip_next_tobuf(char *zip_filename, int offset) { FILE *in; STRBUF *buf; in = fopen(zip_filename, "rb"); if (in == 0) { return NULL; } fseek(in, offset, SEEK_SET); buf = kunzip_file_tobuf(in); fclose(in); return buf; } /* Match Flags: bit 0: set to 1 if it should be exact filename match set to 0 if the archived filename only needs to contain that word bit 1: set to 1 if it should be case sensitive set to 0 if it should be case insensitive */ int kunzip_get_offset_by_name(char *zip_filename, char *compressed_filename, int match_flags, int skip_offset) { FILE *in; struct zip_local_file_header_t local_file_header; int i = 0, curr; char *name = 0; int name_size = 0; long marker; in = fopen(zip_filename, "rb"); if (in == 0) { return -1; } if (skip_offset != -1) { fseek(in, skip_offset, SEEK_SET); } while (1) { curr = ftell(in); i = read_zip_header(in, &local_file_header); if (i == -1) break; if (skip_offset < 0 || curr > skip_offset) { marker = ftell(in); /* nasty code.. please make it nice later */ if (name_size < local_file_header.file_name_length + 1) { if (name_size != 0) yfree(name); name_size = local_file_header.file_name_length + 1; name = ymalloc(name_size); } read_chars(in, name, local_file_header.file_name_length); name[local_file_header.file_name_length] = 0; fseek(in, marker, SEEK_SET); /* and part 2 of nasty code */ if ((match_flags & 1) == 1) { if (strcmp(compressed_filename, name) == 0) break; } else { if (strstr(name, compressed_filename) != 0) break; } } fseek(in, local_file_header.compressed_size + local_file_header.file_name_length + local_file_header.extra_field_length + local_file_header.descriptor_length, SEEK_CUR); } if (name_size != 0) yfree(name); fclose(in); if (i != -1) { return curr; } else { return -1; } } odt2txt-0.5/kunzip/zipfile.h000066400000000000000000000007611243267656000161400ustar00rootroot00000000000000 #define VERSION "Version v1.06 - November 14, 2006" #define COPYRIGHT "Copyright 2005-2006 - Michael Kohn " struct zip_local_file_header_t { unsigned int signature; int version; int general_purpose_bit_flag; int compression_method; int last_mod_file_time; int last_mod_file_date; unsigned int crc_32; int compressed_size; int uncompressed_size; int file_name_length; int extra_field_length; char *file_name; unsigned char *extra_field; int descriptor_length; }; odt2txt-0.5/mem.c000066400000000000000000000170351243267656000137310ustar00rootroot00000000000000/* * mem.c: memory allocation wrappers with a few simple checks * * Copyright (c) 2002-2009 Dennis Stosberg * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License, * version 2 as published by the Free Software Foundation */ #include "mem.h" #ifdef MEMDEBUG static void meminfo_add(void *p, size_t size, const char *file, int line); static void meminfo_rm(void *p, const char *file, int line); static MEMINFO *meminfo_getinfo(void *p); static void print_memory_stats(void); static void die(const char *format, ...); static void warn(const char *format, ...); static size_t mem_num_malloced = 0; static size_t mem_bytes_malloced = 0; static size_t mem_num_freed = 0; static size_t mem_bytes_freed = 0; static MEMINFO **meminfo = NULL; static size_t meminfo_size = 0; static size_t meminfo_count = 0; static unsigned char magic[] = { 0xFE, 0xDC, 0xBA, 0x98, 0x76, 0x54, 0x32, 0x10 }; /** * Adds information about an newly allocated memory region to the * meminfo structure. */ static void meminfo_add(void *p, size_t size, const char *file, int line) { if(!meminfo) if(atexit(print_memory_stats)) warn("Memory statistics will not be shown."); /* enlarge MEMINFO structure if necessary */ if(meminfo_count == meminfo_size) { meminfo_size = meminfo_size ? meminfo_size << 1 : 1; meminfo = realloc(meminfo, meminfo_size * sizeof(MEMINFO*)); } /* add information to structure */ meminfo[meminfo_count] = malloc(sizeof(MEMINFO)); meminfo[meminfo_count]->addr = p; meminfo[meminfo_count]->size = size; meminfo[meminfo_count]->file = file; meminfo[meminfo_count]->line = line; meminfo_count++; #ifdef MEMINFO_VERBOSE printf("allocated 0x%x at %s:%d\n", p, file, line); #endif mem_bytes_malloced += size; mem_num_malloced++; } /** * Removes information about a just freed memory region to the * meminfo structure. Halts the program if the region to be freed * has never been allocated at all. */ static void meminfo_rm(void *p, const char *file, int line) { size_t i; for(i = 0; i < meminfo_count; ++i) { if(p == meminfo[i]->addr) { #ifdef MEMINFO_VERBOSE fprintf(stderr, "freed 0x%x at %s:%d\n", p, file, line); fprintf(stderr, " was allocated at %s:%d\n", meminfo[i]->file, meminfo[i]->line); #endif mem_bytes_freed += meminfo[i]->size; free(meminfo[i]); meminfo[i] = meminfo[meminfo_count - 1]; meminfo_count--; mem_num_freed++; return; } } die("Tried to free a piece of memory at 0x%p in %s:%d" " which is not allocated", (void*)p, file, line); } /** * Returns the size of a malloc'ed region. */ static MEMINFO *meminfo_getinfo(void *p) { size_t i; for(i = 0; i < meminfo_count; ++i) if(p == meminfo[i]->addr) return(meminfo[i]); return(0); } /** * Prints statistics about allocated and deallocated memory to * stderr just before the program exits. If there are memory * regions left that were allocated but never freed, it will print * information on those regions as well. */ static void print_memory_stats(void) { size_t i; if(mem_num_malloced == mem_num_malloced && mem_bytes_malloced == mem_bytes_freed) return; fprintf(stderr, "Memory statistics: \n" " %lu allocations (%lu bytes)\n" " %lu deallocations (%lu bytes)\n" " %ld difference (%ld bytes)\n", (unsigned long)mem_num_malloced, (unsigned long)mem_bytes_malloced, (unsigned long)mem_num_freed, (unsigned long)mem_bytes_freed, (long)(mem_num_malloced - mem_num_freed), (long)(mem_bytes_malloced - mem_bytes_freed) ); if(meminfo_count) { fprintf(stderr, "%lu malloc'ed regions were never " "free'd:\n", (unsigned long)meminfo_count); for(i = 0; i < meminfo_count; ++i) { fprintf(stderr, " %p (%lu bytes) allocated at %s:%d\n", (void *)meminfo[i]->addr, (unsigned long)meminfo[i]->size, meminfo[i]->file, meminfo[i]->line); free(meminfo[i]); } free(meminfo); } } /** * Allocates memory and records information on the allocated * memory. It will halt the program if the memory region to be * allocated has a size of zero. */ void *ymalloc_dbg(size_t size, const char *file, int line) { void *p; if(!size) die("Trying to allocate 0 bytes at %s:%d", file, line); p = malloc(size + 2*sizeof(magic)); if(!p) die("Out of memory at %s:%d while trying to allocate %lu bytes", file, line, (unsigned long)size); meminfo_add(p, size, file, line); memcpy(p, &magic, sizeof(magic)); memcpy((char*)p + size + sizeof(magic), &magic, sizeof(magic)); return((char*)p + sizeof(magic)); } /** * Frees memory and removes information on the memory region. Halts * the program, if the region to be freed has never been allocated * at all. */ void yfree_dbg(void *p, const char *file, int line) { MEMINFO *info; if(!p) die("Trying to free null pointer at %s:%d", file, line); info = meminfo_getinfo((char*)p - sizeof(magic)); if(info == NULL) { die("Looks like we were asked to free a piece of memory" " that we never allocated: %s:%d", file, line); } /* Check, if region boundaries are intact. */ if(memcmp((char*)p - sizeof(magic), &magic, sizeof(magic)) || memcmp((char*)p + info->size, &magic, sizeof(magic))) { die("The boundaries of a region allocated at %s:%d were " "overwritten.", info->file, info->line); } free((char*)p - sizeof(magic)); meminfo_rm((char*)p - sizeof(magic), file, line); p = NULL; } /** * Allocates memory and records information on the allocated * memory. This function will halt the program if the memory * region to be allocated has a size of zero. */ void *ycalloc_dbg(size_t number, size_t size, const char *file, int line) { void *p; p = ymalloc_dbg(number * size, file, line); memset(p, 0, number * size); return(p); } /** * Reallocates memory and updates the information on the memory * region. This function will halt the program if new size of the * memory region is zero ot the region has never been allocated * with ymalloc or ycalloc. */ void *yrealloc_dbg(void *p, size_t size, const char *file, int line) { MEMINFO *area_info; if(!size) { die("Trying to reallocate 0 bytes at %s:%d", file, line); } if(!p) { p = ymalloc_dbg(size, file, line); return(p); } /* Check, if region boundaries are intact. */ area_info = meminfo_getinfo((char*)p - sizeof(magic)); if(memcmp((char*)p - sizeof(magic), &magic, sizeof(magic)) || memcmp((char*)p + area_info->size, &magic, sizeof(magic))) { die("The boundaries of a region allocated at %s:%d were " "overwritten.", area_info->file, area_info->line); } meminfo_rm((char*)p - sizeof(magic), file, line); p = realloc((char*)p - sizeof(magic), size + 2*sizeof(magic)); if(!p) die("Out of memory at %s:%d while trying to allocate %lu bytes", file, line, (unsigned long)size); /* realloc has copied the magic at the beginning of the memory area. We need to set the final magic only */ memcpy((char*)p + size + sizeof(magic), &magic, sizeof(magic)); meminfo_add(p, size, file, line); return((char*)p + sizeof(magic)); } /** * Prints an error message to stdout and halts the program */ static void warn(const char *format, ...) { va_list argp; va_start(argp, format); vfprintf(stderr, format, argp); va_end(argp); fprintf(stderr, "\n"); } /** * Prints an error message to stdout and halts the program */ static void die(const char *format, ...) { va_list argp; va_start(argp, format); vfprintf(stderr, format, argp); va_end(argp); fprintf(stderr, "\n"); exit(EXIT_FAILURE); } #endif odt2txt-0.5/mem.h000066400000000000000000000025151243267656000137330ustar00rootroot00000000000000/* * mem.c: memory allocation wrappers with a few simple checks * * Copyright (c) 2002-2009 Dennis Stosberg * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License, * version 2 as published by the Free Software Foundation */ #ifndef MEM_H #define MEM_H #include #include #include #include #include #ifdef MEMDEBUG /** * A container to keep the information about allocated memory. */ typedef struct { void *addr; size_t size; const char *file; int line; } MEMINFO; #define yfree(p) yfree_dbg(p, __FILE__, __LINE__) void yfree_dbg(void *p, const char *file, int line); #define ymalloc(size) ymalloc_dbg(size, __FILE__, __LINE__) void *ymalloc_dbg(size_t size, const char *file, int line); #define ycalloc(num, size) ymalloc_dbg(num, size, __FILE__, __LINE__) void *ycalloc_dbg(size_t number, size_t size, const char *file, int line); #define yrealloc(p, size) yrealloc_dbg(p, size, __FILE__, __LINE__) void *yrealloc_dbg(void *p, size_t size, const char *file, int line); #else #define yfree(p) free(p) #define ymalloc(size) malloc(size) #define ycalloc(num, size) calloc(num, size); #define yrealloc(p, size) realloc(p, size); #endif #endif /* MEM_H */ odt2txt-0.5/odt2txt.1000066400000000000000000000043211243267656000144730ustar00rootroot00000000000000.TH ODT2TXT "1" "2008-06-23" "odt2txt 0.5" "User Commands" .SH NAME odt2txt \- a simple converter from OpenDocument Text to plain text .SH SYNOPSIS .B odt2txt [OPTIONS] FILENAME .SH DESCRIPTION odt2txt is a command-line tool which extracts the text out of OpenDocument Texts, as produced by OpenOffice.org, KOffice, StarOffice and others. .PP odt2txt can also extract text from some file formats similar to OpenDocument Text, such as OpenOffice.org XML (*.sxw), which was used by OpenOffice.org version 1.x and older StarOffice versions. To a lesser extent, odt2txt may be useful to extract content from OpenDocument spreadsheets (*.ods) and OpenDocument presentations (*.odp). .PP The FILENAME argument is mandatory. .SH OPTIONS .TP \fB\-\-width\fR=\fIWIDTH\fR Wrap text lines after \fIWIDTH\fR characters. The default value is \fI65\fR, which means that any words which would extend beyond column \fI65\fR are moved to a new line. .IP If \fIWIDTH\fR is set to \fI\-1\fR then no lines will be broken .TP \fB\-\-output\fR=\fIFILE\fR Write output to \fIFILE\fR and not to standard output. .TP \fB\-\-subst\fR=\fISUBST\fR Select which non\-ascii characters shall be replaced by ascii look\-a\-likes. Valid values for \fISUBST\fR are \fIall\fR, \fIsome\fR and \fInone\fR. .IP \fB\-\-subst\fR=\fIall\fR Substitute all characters for which substitutions are known .IP \fB\-\-subst\fR=\fIsome\fR Substitute all characters which the output charset does not contain This is the default .IP \fB\-\-subst\fR=\fInone\fR Substitute no characters .TP \fB\-\-encoding\fR=\fIX\fR Do not try to autodetect the terminal encoding, but convert the document to encoding \fIX\fR unconditionally To find out, which terminal encoding will be used in automatic mode, use \fB\-\-encoding\fR=\fIshow\fR .TP \fB\-\-raw\fR Print raw XML .TP \fB\-\-version\fR Show version and copyright information .SH COPYRIGHT Copyright \(co 2006,2007 Dennis Stosberg .br Uses parts of the kunzip library, Copyright 2005,2006 by Michael Kohn .PP This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License, version 2 as published by the Free Software Foundation .SH SEE ALSO .TP https://github.com/dstosberg/odt2txt odt2txt-0.5/odt2txt.c000066400000000000000000000405741243267656000145670ustar00rootroot00000000000000/* * odt2txt.c: A simple (and stupid) converter from OpenDocument Text * to plain text. * * Copyright (c) 2006-2009 Dennis Stosberg * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License, * version 2 as published by the Free Software Foundation */ #include #include #include #include #ifdef NO_ICONV # define iconv_t int #else # include # ifdef WIN32 # include # else # include # endif #endif #include #include #include #include #include #include #include #include "mem.h" #include "regex.h" #include "strbuf.h" #ifdef HAVE_LIBZIP # include #else # include "kunzip/kunzip.h" #endif #define VERSION "0.5" static int opt_raw; static char *opt_encoding; static int opt_width = 63; static const char *opt_filename; static char *opt_output; #define SUBST_NONE 0 #define SUBST_SOME 1 #define SUBST_ALL 2 static int opt_subst = SUBST_SOME; #ifndef ICONV_CHAR #define ICONV_CHAR char #endif #ifdef iconvlist static void show_iconvlist(); #endif #define RS_O(a,b) (void)regex_subst(buf, (a), _REG_DEFAULT, (b)) #define RS_G(a,b) (void)regex_subst(buf, (a), _REG_GLOBAL, (b)) #define RS_E(a,b) (void)regex_subst(buf, (a), _REG_EXEC | _REG_GLOBAL, (void*)(b)) static char *guess_encoding(void); static void write_to_file(STRBUF *outbuf, const char *filename); struct subst { int unicode; const char *utf8; const char *ascii; }; static struct subst substs[] = { /* number, UTF-8 sequence, ascii substitution */ { 0x00A0, "\xC2\xA0", " " }, /* no-break space */ { 0x00A9, "\xC2\xA9", "(c)" }, /* copyright sign */ { 0x00AB, "\xC2\xAB", "<<" }, /* left double angle quote */ { 0x00AD, "\xC2\xAD", "-" }, /* soft hyphen */ { 0x00AE, "\xC2\xAE", "(r)" }, /* registered sign */ { 0x00BB, "\xC2\xBB", ">>" }, /* right double angle quote */ { 0x00BC, "\xC2\xBC", "1/4" }, /* one quarter */ { 0x00BD, "\xC2\xBD", "1/2" }, /* one half */ { 0x00BE, "\xC2\xBE", "3/4" }, /* three quarters */ { 0x00C4, "\xC3\x84", "Ae" }, /* german umlaut A */ { 0x00D6, "\xC3\x96", "Oe" }, /* german umlaut O */ { 0x00DC, "\xC3\x9C", "Ue" }, /* german umlaut U */ { 0x00DF, "\xC3\x9F", "ss" }, /* german sharp s */ { 0x00E4, "\xC3\xA4", "ae" }, /* german umlaut a */ { 0x00F6, "\xC3\xB6", "oe" }, /* german umlaut o */ { 0x00FC, "\xC3\xBC", "ue" }, /* german umlaut u */ { 0x2010, "\xE2\x80\x90", "-" }, /* hyphen */ { 0x2011, "\xE2\x80\x91", "-" }, /* non-breaking hyphen */ { 0x2012, "\xE2\x80\x92", "-" }, /* figure dash */ { 0x2013, "\xE2\x80\x93", "-" }, /* en dash */ { 0x2014, "\xE2\x80\x94", "--" }, /* em dash */ { 0x2015, "\xE2\x80\x95", "--" }, /* quotation dash */ { 0x2018, "\xE2\x80\x98", "`" }, /* single left quotation mark */ { 0x2019, "\xE2\x80\x99", "'" }, /* single right quotation mark */ { 0x201A, "\xE2\x80\x9A", "," }, /* german single right quotation mark */ { 0x201B, "\xE2\x80\x9B", "`" }, /* reversed right quotation mark */ { 0x201C, "\xE2\x80\x9C", "``" }, /* left quotation mark */ { 0x201D, "\xE2\x80\x9D", "''" }, /* right quotation mark */ { 0x201E, "\xE2\x80\x9E", ",," }, /* german left quotes */ { 0x2022, "\xE2\x80\xA2", "o " }, /* bullet */ { 0x2022, "\xE2\x80\xA3", "< " }, /* triangle bullet */ { 0x2025, "\xE2\x80\xA5", ".." }, /* double dot */ { 0x2026, "\xE2\x80\xA6", "..." }, /* ellipsis */ { 0x2030, "\xE2\x80\xB0", "o/oo" }, /* per mille */ { 0x2039, "\xE2\x80\xB9", "<" }, /* left single angle quote */ { 0x203A, "\xE2\x80\xBA", ">" }, /* right single angle quote */ { 0x20AC, "\xE2\x82\xAC", "EUR" }, /* euro currency symbol */ { 0x2190, "\xE2\x86\x90", "<-" }, /* left arrow */ { 0x2192, "\xE2\x86\x92", "->" }, /* right arrow */ { 0x2194, "\xE2\x86\x94", "<->"}, /* left right arrow */ { 0, NULL, NULL }, }; static void usage(void) { printf("odt2txt %s\n" "Converts an OpenDocument or OpenOffice.org XML File to raw text.\n\n" "Syntax: odt2txt [options] filename\n\n" "Options: --raw Print raw XML\n" #ifdef NO_ICONV " --encoding=X Ignored. odt2txt has been built without iconv support.\n" " Output will always be encoded in UTF-8\n" #else " --encoding=X Do not try to autodetect the terminal encoding, but\n" " convert the document to encoding X unconditionally\n" # ifdef iconvlist " You can list all supported encodings by specifying\n" " --encoding=list\n" # endif " To find out, which terminal encoding will be used in\n" " auto mode, use --encoding=show\n" #endif " --width=X Wrap text lines after X characters. Default: 65.\n" " If set to -1 then no lines will be broken\n" " --output=file Write output to file, instead of STDOUT\n" " --subst=X Select which non-ascii characters shall be replaced\n" " by ascii look-a-likes:\n" " --subst=all Substitute all characters for which\n" " substitutions are known\n" " --subst=some Substitute all characters which the\n" " output charset does not contain\n" " This is the default\n" " --subst=none Substitute no characters\n" " --version Show version and copyright information\n", VERSION); exit(EXIT_FAILURE); } static void version_info(void) { printf("odt2txt %s\n" "Copyright (c) 2006,2007 Dennis Stosberg \n" #ifndef HAVE_LIBZIP "Uses the kunzip library, Copyright 2005,2006 by Michael Kohn\n" #endif "\n" "This program is free software; you can redistribute it and/or\n" "modify it under the terms of the GNU General Public License,\n" "version 2 as published by the Free Software Foundation\n" "\n" "https://github.com/dstosberg/odt2txt\n", VERSION); exit(EXIT_SUCCESS); } static void yrealloc_buf(char **buf, char **mark, size_t len) { ptrdiff_t offset = *mark - *buf; *buf = yrealloc(*buf, len); *mark = *buf + offset; } #ifdef NO_ICONV static void finish_conv(iconv_t ic) { return; } static iconv_t init_conv(const char *input_enc, const char *output_enc) { return 0; } static STRBUF *conv(iconv_t ic, STRBUF *buf) { STRBUF *output; output = strbuf_new(); strbuf_append_n(output, strbuf_get(buf), strbuf_len(buf)); return output; } static void subst_doc(iconv_t ic, STRBUF *buf) { return; } static char *guess_encoding(void) { return NULL; } #else static iconv_t init_conv(const char *input_enc, const char *output_enc) { iconv_t ic; ic = iconv_open(output_enc, input_enc); if (ic == (iconv_t)-1) { if (errno == EINVAL) { fprintf(stderr, "warning: Conversion from %s to %s is not supported.\n", input_enc, opt_encoding); ic = iconv_open("us-ascii", input_enc); if (ic == (iconv_t)-1) { exit(EXIT_FAILURE); } fprintf(stderr, "warning: Using us-ascii as fall-back.\n"); } else { fprintf(stderr, "iconv_open returned: %s\n", strerror(errno)); exit(EXIT_FAILURE); } } return ic; } static void finish_conv(iconv_t ic) { if(iconv_close(ic) == -1) { fprintf(stderr, "iconv_close returned: %s\n", strerror(errno)); exit(EXIT_FAILURE); } } static STRBUF *conv(iconv_t ic, STRBUF *buf) { /* FIXME: This functionality belongs into strbuf.c */ ICONV_CHAR *doc; char *out, *outbuf; size_t inleft, outleft = 0; size_t r; size_t outlen = 0; const size_t alloc_step = 4096; STRBUF *output; inleft = strbuf_len(buf); doc = (ICONV_CHAR*)strbuf_get(buf); outlen = alloc_step; outleft = alloc_step; outbuf = ymalloc(alloc_step); out = outbuf; outleft = alloc_step; do { if (!outleft) { outlen += alloc_step; outleft += alloc_step; yrealloc_buf(&outbuf, &out, outlen); } r = iconv(ic, &doc, &inleft, &out, &outleft); if (r == (size_t)-1) { if(errno == E2BIG) { outlen += alloc_step; outleft += alloc_step; if (outlen > (strbuf_len(buf) << 3)) { fprintf(stderr, "Buffer grew to much. " "Corrupted document?\n"); exit(EXIT_FAILURE); } yrealloc_buf(&outbuf, &out, outlen); continue; } else if ((errno == EILSEQ) || (errno == EINVAL)) { char skip = 1; /* advance in source buffer */ if ((unsigned char)*doc > 0x80) skip += utf8_length[(unsigned char)*doc - 0x80]; doc += skip; inleft -= skip; /* advance in output buffer */ *out = '?'; out++; outleft--; continue; } fprintf(stderr, "iconv returned: %s\n", strerror(errno)); exit(EXIT_FAILURE); } } while(inleft != 0); if (!outleft) { outbuf = yrealloc(outbuf, outlen + 1); } *out = '\0'; output = strbuf_slurp_n(outbuf, (size_t)(out - outbuf)); strbuf_setopt(output, STRBUF_NULLOK); return output; } static void subst_doc(iconv_t ic, STRBUF *buf) { struct subst *s = substs; ICONV_CHAR *in; size_t inleft; const size_t outbuf_sz = 20; char *outbuf; char *out; size_t outleft; size_t r; if (opt_subst == SUBST_NONE) return; outbuf = ymalloc(outbuf_sz); while (s->unicode) { if (opt_subst == SUBST_ALL) { RS_G(s->utf8, s->ascii); } else { out = outbuf; outleft = outbuf_sz; in = (ICONV_CHAR*)s->utf8; inleft = strlen(in); r = iconv(ic, &in, &inleft, &out, &outleft); if (r == (size_t)-1) { if ((errno == EILSEQ) || (errno == EINVAL)) { RS_G(s->utf8, s->ascii); } else { fprintf(stderr, "iconv returned an unexpected error: %s\n", strerror(errno)); exit(EXIT_FAILURE); } } } s++; } yfree(outbuf); } static char *guess_encoding(void) { char *enc; char *tmp; enc = ymalloc(20); #ifdef WIN32 snprintf(enc, 20, "CP%u", GetACP()); #else tmp = nl_langinfo(CODESET); strncpy(enc, tmp, 20); #endif if(!enc) { fprintf(stderr, "warning: Could not detect console " "encoding. Assuming ISO-8859-1\n"); strncpy(enc, "ISO-8859-1", 20); } return enc; } #endif static STRBUF *read_from_zip(const char *zipfile, const char *filename) { int r = 0; STRBUF *content = NULL; #ifdef HAVE_LIBZIP int zip_error; struct zip *zip = NULL; struct zip_stat stat; struct zip_file *unzipped = NULL; char *buf = NULL; if ( !(zip = zip_open(zipfile, 0, &zip_error)) || (r = zip_name_locate(zip, filename, 0)) < 0 || (zip_stat_index(zip, r, ZIP_FL_UNCHANGED, &stat) < 0) || !(unzipped = zip_fopen_index(zip, r, ZIP_FL_UNCHANGED)) ) { if (unzipped) zip_fclose(unzipped); if (zip) zip_close(zip); r = -1; } #else r = kunzip_get_offset_by_name((char*)zipfile, (char*)filename, 3, -1); #endif if(-1 == r) { fprintf(stderr, "Can't read from %s: Is it an OpenDocument Text?\n", zipfile); exit(EXIT_FAILURE); } #ifdef HAVE_LIBZIP if ( !(buf = ymalloc(stat.size + 1)) || (zip_fread(unzipped, buf, stat.size) != stat.size) || !(content = strbuf_slurp_n(buf, stat.size)) ) { if (buf) yfree(buf); content = NULL; } zip_fclose(unzipped); zip_close(zip); #else content = kunzip_next_tobuf((char*)zipfile, r); #endif if (!content) { fprintf(stderr, "Can't extract %s from %s. Maybe the file is corrupted?\n", filename, zipfile); exit(EXIT_FAILURE); } return content; } static void format_doc(STRBUF *buf) { /* FIXME: Convert buffer to utf-8 first. Are there OpenOffice texts which are not utf8-encoded? */ /* headline, first level */ RS_E("]*outline-level=\"1\"[^>]*>([^<]*)<[^>]*>", &h1); RS_E("]*>([^<]*)<[^>]*>", &h2); /* other headlines */ RS_G("]*>", "\n\n"); /* normal paragraphs */ RS_G("", "\n\n"); RS_G("", " "); /* tabs */ RS_G("", "\n"); /* images */ RS_E("]*draw:name=\"([^\"]*)\"[^>]*>", &image); RS_G("<[^>]*>", ""); /* replace all remaining tags */ RS_G("\n +", "\n"); /* remove indentations, e.g. kword */ RS_G("\n{3,}", "\n\n"); /* remove large vertical spaces */ RS_G("'", "'"); /* common entities */ RS_G("&", "&"); RS_G(""", "\""); RS_G(">", ">"); RS_G("<", "<"); RS_O("^\n+", ""); /* blank lines at beginning and end of document */ RS_O("\n{2,}$", "\n"); } int main(int argc, const char **argv) { struct stat st; iconv_t ic; STRBUF *wbuf; STRBUF *docbuf; STRBUF *outbuf; int i = 1; (void)setlocale(LC_ALL, ""); while (argv[i]) { if (!strcmp(argv[i], "--raw")) { opt_raw = 1; i++; continue; } else if (!strncmp(argv[i], "--encoding=", 11)) { size_t arglen = strlen(argv[i]) - 10; #ifdef iconvlist if (!strcmp(argv[i] + 11, "list")) { show_iconvlist(); } #endif opt_encoding = ymalloc(arglen); memcpy(opt_encoding, argv[i] + 11, arglen); i++; continue; } else if (!strncmp(argv[i], "--width=", 8)) { opt_width = atoi(argv[i] + 8); if(opt_width < 3 && opt_width != -1) { fprintf(stderr, "Invalid value for width: %s\n", argv[i] + 8); exit(EXIT_FAILURE); } i++; continue; } else if (!strcmp(argv[i], "--force")) { // ignore this setting i++; continue; } else if (!strncmp(argv[i], "--output=", 9)) { if (*(argv[i] + 9) != '-') { size_t arglen = strlen(argv[i]) - 8; opt_output = ymalloc(arglen); memcpy(opt_output, argv[i] + 9, arglen); } i++; continue; } else if (!strncmp(argv[i], "--subst=", 8)) { if (!strcmp(argv[i] + 8, "none")) opt_subst = SUBST_NONE; else if (!strcmp(argv[i] + 8, "some")) opt_subst = SUBST_SOME; else if (!strcmp(argv[i] + 8, "all")) opt_subst = SUBST_ALL; else { fprintf(stderr, "Invalid value for --subst: %s\n", argv[i] + 8); exit(EXIT_FAILURE); } i++; continue; } else if (!strcmp(argv[i], "--help")) { usage(); } else if (!strcmp(argv[i], "--version") || !strcmp(argv[i], "-v")) { version_info(); } else if (!strcmp(argv[i], "-")) { usage(); } else { if(opt_filename) usage(); opt_filename = argv[i]; i++; continue; } } if(opt_encoding && !strcmp("show", opt_encoding)) { yfree(opt_encoding); opt_encoding = guess_encoding(); printf("%s\n", opt_encoding); yfree(opt_encoding); exit(EXIT_SUCCESS); } if(opt_raw) opt_width = -1; if(!opt_filename) usage(); if(!opt_encoding) { opt_encoding = guess_encoding(); } ic = init_conv("UTF-8", opt_encoding); if (0 != stat(opt_filename, &st)) { fprintf(stderr, "%s: %s\n", opt_filename, strerror(errno)); exit(EXIT_FAILURE); } /* read content.xml */ docbuf = read_from_zip(opt_filename, "content.xml"); if (!opt_raw) { subst_doc(ic, docbuf); format_doc(docbuf); } wbuf = wrap(docbuf, opt_width); /* remove all trailing whitespace */ (void) regex_subst(wbuf, " +\n", _REG_GLOBAL, "\n"); outbuf = conv(ic, wbuf); if (opt_output) write_to_file(outbuf, opt_output); else fwrite(strbuf_get(outbuf), strbuf_len(outbuf), 1, stdout); finish_conv(ic); strbuf_free(wbuf); strbuf_free(docbuf); strbuf_free(outbuf); #ifndef NO_ICONV yfree(opt_encoding); #endif if (opt_output) yfree(opt_output); return EXIT_SUCCESS; } static void write_to_file(STRBUF *outbuf, const char *filename) { int fd; ssize_t len; fd = open(filename, O_WRONLY | O_CREAT | O_TRUNC, 0644); if (fd == -1) { fprintf(stderr, "Can't open %s: %s\n", filename, strerror(errno)); exit(EXIT_FAILURE); } len = write(fd, strbuf_get(outbuf), strbuf_len(outbuf)); if (len == -1) { fprintf(stderr, "Can't write to %s: %s\n", filename, strerror(errno)); exit(EXIT_FAILURE); } close(fd); } #ifdef iconvlist static int print_one (unsigned int namescount, const char * const * names, void *data) { int i; for (i = 0; i < namescount; i++) { if (i > 0) putc(' ',stdout); fputs(names[i],stdout); } putc('\n',stdout); return 0; } static void show_iconvlist() { iconvlist(print_one, NULL); exit(EXIT_SUCCESS); } #endif odt2txt-0.5/regex.c000066400000000000000000000120721243267656000142610ustar00rootroot00000000000000/* * regex.c: String and regex operations for odt2txt * * Copyright (c) 2006-2009 Dennis Stosberg * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License, * version 2 as published by the Free Software Foundation */ #include "mem.h" #include "regex.h" #define BUF_SZ 4096 static char *headline(char line, const char *buf, regmatch_t matches[], size_t nmatch, size_t off); static size_t charlen_utf8(const char *s); static void print_regexp_err(int reg_errno, const regex_t *rx) { char *buf = ymalloc(BUF_SZ); regerror(reg_errno, rx, buf, BUF_SZ); fprintf(stderr, "%s\n", buf); yfree(buf); } int regex_subst(STRBUF *buf, const char *regex, int regopt, const void *subst) { int r; const char *bufp; size_t off = 0; const int i = 0; int match_count = 0; regex_t rx; const size_t nmatches = 10; regmatch_t matches[10]; r = regcomp(&rx, regex, REG_EXTENDED); if (r) { print_regexp_err(r, &rx); exit(EXIT_FAILURE); } do { if (off > strbuf_len(buf)) break; bufp = strbuf_get(buf) + off; #ifdef REG_STARTEND matches[0].rm_so = 0; matches[0].rm_eo = strbuf_len(buf) - off; if (0 != regexec(&rx, bufp, nmatches, matches, REG_STARTEND)) #else if (0 != regexec(&rx, bufp, nmatches, matches, 0)) #endif break; if (matches[i].rm_so != -1) { char *s; int subst_len; if (regopt & _REG_EXEC) { s = (*(char *(*) (const char *buf, regmatch_t matches[], size_t nmatch, size_t off))subst) (strbuf_get(buf), matches, nmatches, off); } else s = (char*)subst; subst_len = strbuf_subst(buf, matches[i].rm_so + off, matches[i].rm_eo + off, s); match_count++; if (regopt & _REG_EXEC) yfree(s); off += matches[i].rm_so; if (subst_len >= 0) off += subst_len + 1; } } while (regopt & _REG_GLOBAL); regfree(&rx); return match_count; } int regex_rm(STRBUF *buf, const char *regex, int regopt) { return regex_subst(buf, regex, regopt, ""); } char *underline(char linechar, const char *str) { size_t i; char *tmp; STRBUF *line; size_t charlen = charlen_utf8(str); if (str[0] == '\0') { tmp = ymalloc(1); tmp[0] = '\0'; return tmp; } line = strbuf_new(); strbuf_append(line, str); strbuf_append(line, "\n"); tmp = ymalloc(charlen); for (i = 0; i < charlen; i++) { tmp[i] = linechar; } strbuf_append_n(line, tmp, charlen); yfree(tmp); strbuf_append(line, "\n\n"); return strbuf_spit(line); } static char *headline(char line, const char *buf, regmatch_t matches[], size_t nmatch, size_t off) { const int i = 1; char *result; size_t len; char *match; len = matches[i].rm_eo - matches[i].rm_so; match = ymalloc(len + 1); memcpy(match, buf + matches[i].rm_so + off, len); match[len] = '\0' ; result = underline(line, match); yfree(match); return result; } char *h1(const char *buf, regmatch_t matches[], size_t nmatch, size_t off) { return headline('=', buf, matches, nmatch, off); } char *h2(const char *buf, regmatch_t matches[], size_t nmatch, size_t off) { return headline('-', buf, matches, nmatch, off); } char *image(const char *buf, regmatch_t matches[], size_t nmatch, size_t off) { const int i = 1; const char *prefix = "[-- Image: "; const char *postfix = " --]"; size_t pr_len, po_len, len; char *match; pr_len = strlen(prefix); len = matches[i].rm_eo - matches[i].rm_so; po_len = strlen(prefix); match = ymalloc(pr_len + len + po_len + 1); memcpy(match, prefix, pr_len); memcpy(match + pr_len, buf + matches[i].rm_so + off, len); memcpy(match + pr_len + len, postfix, po_len); match[pr_len + len + po_len] = '\0' ; return match; } static size_t charlen_utf8(const char *s) { size_t count = 0; unsigned char *t = (unsigned char*) s; while (*t != '\0') { if (*t > 0x80) t += utf8_length[*t - 0x80]; count++; t++; } return count; } STRBUF *wrap(STRBUF *buf, int width) { const char *lf = "\n"; const size_t lflen = strlen(lf); const char *bufp; const char *last; const char *lastspace = 0; size_t linelen = 0; STRBUF *out = strbuf_new(); bufp = strbuf_get(buf); last = bufp; if (width == -1) { strbuf_append_n(out, strbuf_get(buf), strbuf_len(buf)); return out; } strbuf_append_n(out, lf, lflen); while(bufp - strbuf_get(buf) < (ptrdiff_t)strbuf_len(buf)) { if (*bufp == ' ') lastspace = bufp; else if (*bufp == '\n') { strbuf_append_n(out, last, (size_t)(bufp - last)); do { strbuf_append_n(out, lf, lflen); } while (*++bufp == '\n'); lastspace = NULL; while(*bufp == ' ') { bufp++; } last = bufp; linelen = 0; } if (NULL != lastspace && (int)linelen > width) { strbuf_append_n(out, last, (size_t)(lastspace - last)); strbuf_append_n(out, lf, lflen); last = lastspace; lastspace = NULL; linelen = (size_t)(bufp - last); while(*last == ' ') { last++; } if(last > bufp) bufp = last; } bufp++; linelen++; if ((unsigned char)*bufp > 0x80) bufp += utf8_length[(unsigned char)*bufp - 0x80]; } strbuf_append_n(out, "\n", 1); return out; } odt2txt-0.5/regex.h000066400000000000000000000044741243267656000142750ustar00rootroot00000000000000/* * regex.c: String and regex operations for odt2txt * * Copyright (c) 2006-2009 Dennis Stosberg * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License, * version 2 as published by the Free Software Foundation */ #ifndef REGEX_H #define REGEX_H #include #include #include #include #include #include "strbuf.h" #define _REG_DEFAULT 0 /* Stop after first match, to be removed */ #define _REG_GLOBAL 1 /* Find all matches of regexp */ #define _REG_EXEC 2 /* subst is a function pointer */ /* * Deletes match(es) of regex from *buf. * * Returns the number of matches that were deleted. */ int regex_rm(STRBUF *buf, const char *regex, int regopt); /* * Replaces match(es) of regex from *buf with subst. */ int regex_subst(STRBUF *buf, const char *regex, int regopt, const void *subst); /* * Returns a pointer to a new string with two lines. The first line * contains str, the second line contains strlen(str) copies of * linechar. */ char *underline(char linechar, const char *str); /* * Wrappers around underline, to be used as argument to regex_subst * when regopt is _REG_EXEC. * * They replace the match in buf with underline('=',match) or * underline('-',match) respectively. */ char *h1(const char *buf, regmatch_t matches[], size_t nmatch, size_t off); char *h2(const char *buf, regmatch_t matches[], size_t nmatch, size_t off); /* * Replace match with the name of the image frame */ char *image(const char *buf, regmatch_t matches[], size_t nmatch, size_t off); /* * Copies the contents of buf to a new string buffer, wrapped to a * maximal line width of width characters. */ STRBUF *wrap(STRBUF *buf, int width); /* * number of characters that follow in the byte sequence */ static const char utf8_length[128] = { 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, /* 0x80-0x8f */ 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, /* 0x90-0x9f */ 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, /* 0xa0-0xaf */ 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, /* 0xb0-0xbf */ 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, /* 0xc0-0xcf */ 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, /* 0xd0-0xdf */ 2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2, /* 0xe0-0xef */ 3,3,3,3,3,3,3,3,4,4,4,4,5,5,0,0 /* 0xf0-0xff */ }; #endif /* REGEX_H */ odt2txt-0.5/strbuf.c000066400000000000000000000130621243267656000144540ustar00rootroot00000000000000/* * strbuf.c: A simple string buffer * * Copyright (c) 2006-2009 Dennis Stosberg * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License, * version 2 as published by the Free Software Foundation */ #include "strbuf.h" static const size_t strbuf_start_sz = 128; static const size_t strbuf_grow_sz = 128; static void strbuf_grow(STRBUF *buf); /* enlarge a buffer by strbuf_grow_sz */ #ifdef STRBUF_CHECK static void die(const char *format, ...) { va_list argp; va_start(argp, format); vfprintf(stderr, format, argp); va_end(argp); fprintf(stderr, "\n"); exit(EXIT_FAILURE); } static void strbuf_check(STRBUF *buf) { if (!buf) die("buf is null"); if (!buf->data) die("buf->data is null"); if (!(buf->opt & STRBUF_NULLOK) && strlen(buf->data) != buf->len) die("length mismatch. strlen says %u, len says %u", (unsigned int)strlen(buf->data), buf->len); if (buf->len + 1 > buf->buf_sz) die("overlap"); } #else #define strbuf_check(a) #endif STRBUF *strbuf_new(void) { STRBUF *buf = ymalloc(sizeof(STRBUF)); buf->buf_sz = strbuf_start_sz; buf->data = ymalloc(strbuf_start_sz); buf->len = 0; buf->data[0] = '\0'; buf->opt = 0; strbuf_check(buf); return buf; } void strbuf_free(STRBUF *buf) { strbuf_check(buf); yfree(buf->data); yfree(buf); } void strbuf_shrink(STRBUF *buf) { strbuf_check(buf); buf->buf_sz = buf->len + 1; buf->data = yrealloc(buf->data, buf->buf_sz); strbuf_check(buf); } size_t strbuf_append_n(STRBUF *buf, const char *str, size_t n) { strbuf_check(buf); if (n == 0) return buf->len; while (buf->len + n + 1 > buf->buf_sz) strbuf_grow(buf); memcpy(buf->data + buf->len, str, n); buf->len += n; *(buf->data + buf->len) = 0; strbuf_check(buf); return buf->len; } size_t strbuf_append(STRBUF *buf, const char *str) { return strbuf_append_n(buf, str, strlen(str)); } const char *strbuf_get(STRBUF *buf) { strbuf_check(buf); return buf->data; } size_t strbuf_len(STRBUF *buf) { strbuf_check(buf); return buf->len; } int strbuf_subst(STRBUF *buf, size_t start, size_t stop, const char *subst) { size_t len; size_t subst_len; int diff; strbuf_check(buf); if (start > stop) { size_t tmp = start; start = stop; stop = tmp; } len = stop - start; subst_len = strlen(subst); diff = subst_len - len; if (0 > diff) { memcpy(buf->data + start, subst, subst_len); memmove(buf->data + start + subst_len, buf->data + stop, buf->len - stop + 1); } else if (0 == diff) { memcpy(buf->data + start, subst, subst_len); } else { /* 0 < diff */ while (buf->len + diff + 1 > buf->buf_sz) strbuf_grow(buf); memmove(buf->data + start + subst_len, buf->data + stop, buf->len - stop + 1); memcpy(buf->data + start, subst, subst_len); } buf->len += diff; strbuf_check(buf); return diff; } size_t strbuf_append_inflate(STRBUF *buf, FILE *in) { size_t len; z_stream strm; Bytef readbuf[1024]; int z_ret; int nullok; strbuf_check(buf); /* save NULLOK flag */ nullok = (buf->opt & STRBUF_NULLOK) ? 1 : 0; strbuf_setopt(buf, STRBUF_NULLOK); /* zlib init */ strm.zalloc = Z_NULL; strm.zfree = Z_NULL; strm.opaque = Z_NULL; strm.next_in = Z_NULL; strm.avail_in = 0; z_ret = inflateInit2(&strm, -15); if (z_ret != Z_OK) { fprintf(stderr, "A: zlib returned error: %d\n", z_ret); exit(EXIT_FAILURE); } do { int f_err; strm.avail_in = (uInt)fread(readbuf, 1, sizeof(readbuf), in); f_err = ferror(in); if (f_err) { (void)inflateEnd(&strm); fprintf(stderr, "stdio error: %d\n", f_err); exit(EXIT_FAILURE); /* TODO: errmsg? continue? */ } if (strm.avail_in == 0) break; strm.next_in = readbuf; do { size_t bytes_inflated; while (buf->buf_sz < buf->len + sizeof(readbuf) * 2) strbuf_grow(buf); strm.next_out = (Bytef*)(buf->data + buf->len); strm.avail_out = (uInt)(buf->buf_sz - buf->len); z_ret = inflate(&strm, Z_SYNC_FLUSH); switch (z_ret) { case Z_NEED_DICT: case Z_DATA_ERROR: case Z_MEM_ERROR: (void)inflateEnd(&strm); fprintf(stderr, "B: zlib returned error: %d\n", z_ret); exit(EXIT_FAILURE); } bytes_inflated = (buf->buf_sz - buf->len) - strm.avail_out; buf->len += bytes_inflated; } while (strm.avail_out == 0); } while (z_ret != Z_STREAM_END); /* terminate buffer */ if (buf->len + 1 > buf->buf_sz) strbuf_grow(buf); *(buf->data + buf->len) = '\0'; /* restore NULLOK option */ if (!nullok) strbuf_unsetopt(buf, STRBUF_NULLOK); strbuf_check(buf); len = (size_t)strm.total_out; (void)inflateEnd(&strm); if (z_ret != Z_STREAM_END) { fprintf(stderr, "ERR\n"); exit(EXIT_FAILURE); } return len; } static void strbuf_grow(STRBUF *buf) { buf->buf_sz += strbuf_grow_sz; buf->data = yrealloc(buf->data, buf->buf_sz); strbuf_check(buf); } STRBUF *strbuf_slurp(char *str) { return strbuf_slurp_n(str, strlen(str)); } STRBUF *strbuf_slurp_n(char *str, size_t len) { STRBUF *buf = ymalloc(sizeof(STRBUF)); buf->len = len; buf->buf_sz = len + 1; buf->data = yrealloc(str, buf->buf_sz); *(buf->data + len) = '\0'; buf->opt = 0; return buf; } char *strbuf_spit(STRBUF *buf) { char *data; strbuf_check(buf); strbuf_shrink(buf); data = buf->data; yfree(buf); return data; } unsigned int strbuf_crc32(STRBUF *buf) { uLong crc = crc32(0L, Z_NULL, 0); crc = crc32(crc, (Bytef *)buf->data, buf->len); return (unsigned int)crc; } void strbuf_setopt(STRBUF *buf, enum strbuf_opt opt) { buf->opt |= opt; } void strbuf_unsetopt(STRBUF *buf, enum strbuf_opt opt) { buf->opt &= ~opt; } odt2txt-0.5/strbuf.h000066400000000000000000000050621243267656000144620ustar00rootroot00000000000000/* * strbuf.c: A simple string buffer * * Copyright (c) 2006-2009 Dennis Stosberg * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License, * version 2 as published by the Free Software Foundation */ #ifndef STRBUF_H #define STRBUF_H #include "mem.h" #include "zlib.h" typedef struct strbuf { char *data; size_t len; size_t buf_sz; int opt; } STRBUF; enum strbuf_opt { STRBUF_NULLOK = 1 }; /* * Initialize a new empty string buffer. */ STRBUF *strbuf_new(void); /* * Free a string buffer. */ void strbuf_free(STRBUF *buf); /* * Appends the n first characters from str to the string buffer. * * Returns the new length of the string buffer. */ size_t strbuf_append_n(STRBUF *buf, const char *str, size_t n); /* * Appends str to the string buffer. * * Returns the new length of the string buffer. */ size_t strbuf_append(STRBUF *buf, const char *str); /* * Reads a zlib-compressed data stream from in and appends * it to the buffer out. Returns the number of appended characters. */ size_t strbuf_append_inflate(STRBUF *buf, FILE *in); /* * Returns a pointer to the contained string. */ const char *strbuf_get(STRBUF *buf); /* * Returns the length of the contained string. */ size_t strbuf_len(STRBUF *buf); /* * Reallocs the data structure in the string buffer to use not more * memory than necessary. */ void strbuf_shrink(STRBUF *buf); /* * Creates a string buffer from a *char without copying. */ STRBUF *strbuf_slurp(char *str); STRBUF *strbuf_slurp_n(char *str, size_t len); /* * Returns the contained string and destroys the string buffer. */ char *strbuf_spit(STRBUF *buf); /* * Substitute characters in the string buffer buf from start * (inclusive) to end (exclusive) and replace them with *subst. The * first character in the string has the index 0. * * Returns the change of the length of the string contained at *buf. * The return value is negative, if the string is shortened, zero if * the length is unchanged and positive if the length increases. * * If start is bigger than stop, their values are automatically * swapped. */ int strbuf_subst(STRBUF *buf, size_t start, size_t stop, const char *subst); /* * Set options for the string buffer */ void strbuf_setopt(STRBUF *buf, enum strbuf_opt opt); /* * Unset an option for the string buffer */ void strbuf_unsetopt(STRBUF *buf, enum strbuf_opt opt); /* * Return the crc32 checksum of the buffer content. */ unsigned int strbuf_crc32(STRBUF *buf); #endif /* STRBUF_H */ odt2txt-0.5/t/000077500000000000000000000000001243267656000132445ustar00rootroot00000000000000odt2txt-0.5/t/test-regex.c000066400000000000000000000044071243267656000155040ustar00rootroot00000000000000 #include #include #include #include #include "../mem.h" #include "../strbuf.h" #include "../regex.h" int main(int argc, char **argv) { STRBUF *buf; char *test1 = "When shall we three meet again?"; char *test2 = "In thunder, lightning, or in rain?"; char *test3 = "do do do do do do do do do do " "do do do do do do do do do do " "do do do do do do do do do do " "do do do do do do do do do do " "do do do do do do do do do do "; char *c; /* test optimization for multiple matches */ buf = strbuf_new(); strbuf_append(buf, test2); assert( 6 == regex_subst(buf, "n", _REG_GLOBAL, "")); assert(!strcmp(strbuf_get(buf), "I thuder, lightig, or i rai?")); assert( 3 == regex_subst(buf, "r", _REG_GLOBAL, "R")); assert(!strcmp(strbuf_get(buf), "I thudeR, lightig, oR i Rai?")); assert( 3 == regex_subst(buf, "R", _REG_GLOBAL, "R")); assert(!strcmp(strbuf_get(buf), "I thudeR, lightig, oR i Rai?")); assert( 3 == regex_subst(buf, "R", _REG_GLOBAL, "RRR")); assert(!strcmp(strbuf_get(buf), "I thudeRRR, lightig, oRRR i RRRai?")); assert( 9 == regex_subst(buf, "R", _REG_GLOBAL, "RR")); assert(!strcmp(strbuf_get(buf), "I thudeRRRRRR, lightig, oRRRRRR i RRRRRRai?")); assert( 3 == regex_rm(buf, "R+", _REG_GLOBAL)); assert(!strcmp(strbuf_get(buf), "I thude, lightig, o i ai?")); strbuf_free(buf); /* global rm to empty string */ buf = strbuf_new(); strbuf_append(buf, test3); assert(50 == regex_rm(buf, "do", _REG_GLOBAL)); assert(50 == regex_rm(buf, " ", _REG_GLOBAL)); assert(!strcmp(strbuf_get(buf), "")); strbuf_free(buf); /* simple patterns */ buf = strbuf_new(); strbuf_append(buf, "abcd35ef8gh6i"); assert( 1 == regex_rm(buf, "[0-9]{2}", _REG_GLOBAL)); assert( 2 == regex_rm(buf, "[0-9]", _REG_GLOBAL)); assert(!strcmp(strbuf_get(buf), "abcdefghi")); strbuf_free(buf); /* underline 1 */ c = underline('=', "Brave new world"); assert(!strcmp(c, "Brave new world\n===============\n\n")); yfree(c); /* underline 2 */ c = underline('-', ""); assert(!strcmp(c, "")); yfree(c); /* underline 3 */ c = underline('B', "AAAAAA"); assert(!strcmp(c, "AAAAAA\nBBBBBB\n\n")); yfree(c); /* underline 4 */ c = underline('-', ""); assert(!strcmp(c, "")); yfree(c); printf("ALL HAPPY\n"); return(EXIT_SUCCESS); } odt2txt-0.5/t/test-strbuf.c000066400000000000000000000043371243267656000157010ustar00rootroot00000000000000 #include #include #include #include #include "../mem.h" #include "../strbuf.h" int main(int argc, char **argv) { STRBUF *buf; char *test1 = "When shall we three meet again?"; char *test2 = "In thunder, lightning, or in rain?"; char *test3 = "do do do do do do do do do do " "do do do do do do do do do do " "do do do do do do do do do do " "do do do do do do do do do do " "do do do do do do do do do do "; char *c; /* trivial */ buf = strbuf_new(); strbuf_append(buf, "Hello "); strbuf_append(buf, "you!"); assert(!strcmp(strbuf_get(buf), "Hello you!")); strbuf_shrink(buf); strbuf_free(buf); buf = strbuf_new(); assert(strlen(test1) == strbuf_append(buf, test1)); /* success: shorter substitution */ assert( -2 == strbuf_subst(buf, 5, 10, "can")); assert((!strcmp(strbuf_get(buf), "When can we three meet again?"))); /* success: same length */ assert( 0 == strbuf_subst(buf, 5, 8, "CAN")); assert((!strcmp(strbuf_get(buf), "When CAN we three meet again?"))); /* success: longer substitution, without realloc */ assert( 1 == strbuf_subst(buf, 5, 8, "must")); assert((!strcmp(strbuf_get(buf), "When must we three meet again?"))); /* success: longer substitution, with realloc */ strbuf_shrink(buf); assert(14 == strbuf_subst(buf, 4, 9, ", do you think, can")); assert((!strcmp(strbuf_get(buf), "When, do you think, can we three meet again?"))); strbuf_free(buf); buf = strbuf_new(); strbuf_append(buf, test2); /* delete last char */ assert( -1 == strbuf_subst(buf, strbuf_len(buf) - 1, strbuf_len(buf), "")); /* delete first char */ assert( -1 == strbuf_subst(buf, 0, 1, "")); assert(!strcmp("n thunder, lightning, or in rain", strbuf_get(buf))); /* delete completely */ assert( 0 - strbuf_len(buf) == strbuf_subst(buf, 0, strbuf_len(buf), "")); assert(!strcmp("", strbuf_get(buf))); /* insert a string */ assert( strlen(test3) == strbuf_subst(buf, 0, 0, test3)); assert(!strcmp(test3, strbuf_get(buf))); strbuf_free(buf); /* slurp */ c = ymalloc(strlen(test2) + 1); memcpy(c, test2, strlen(test2) + 1); buf = strbuf_create_slurp(c); assert(!strcmp(test2, strbuf_get(buf))); strbuf_free(buf); printf("ALL HAPPY\n"); return(EXIT_SUCCESS); }