./0000700000175000017500000000000011546766220010504 5ustar takakitakaki./PyHyphen-1.0beta1/0000775000175000017500000000000011546766220013475 5ustar takakitakaki./PyHyphen-1.0beta1/PKG-INFO0000666000175000017500000003534111546030414014567 0ustar takakitakakiMetadata-Version: 1.1 Name: PyHyphen Version: 1.0beta1 Summary: The hyphenation library of OpenOffice and FireFox wrapped for Python Home-page: http://pyhyphen.googlecode.com Author: Dr. Leo Author-email: fhaxbox66@googlemail.com License: UNKNOWN Description: ================================= PyHyphen - hyphenation for Python ================================= (c) 2008-2011 Dr. Leo Contact: fhaxbox66@googlemail.com Project home: http://pyhyphen.googlecode.com Mailing list: http://groups.google.com/group/pyhyphen .. contents:: Change log ====================== New in version 1.0 * Upgraded the C library libhyphen to v2.7 which brings significant improvements, most notably correct treatment of * already hyphenated words such as 'Python-powered' * use a CSV file from the oo website with meta information on dictionaries for installation of dictionaries and instantiation of hyphenators. Apps can access the metadata on all downloadable dicts through the new module-level attribute hyphen.dict_info or for each hyphenator through the 'info' attribute, * Hyphenator objects have a 'info' attribute which is a Python dictionary with meta information on the hyphenation dictionary. The 'language' attribute is deprecated. *Note:* These new features add complexity to the installation process as the metadata and dictionary files are downloaded at install time. These features have to be tested in various environments before declaring the package stable. * Streamlined the installation process * The en_US hyphenation dictionary has been removed from the package. Instead, the dictionaries for en_US and the local language are automatically downloaded at install time. * restructured the package and merged 2.x and 3.x setup files * switch from svn to hg * added win32 binary of the C extension module for Python32, currently no binaries for Python 2.4 and 2.5 New in version 0.10 * added win32 binary for Python 2.7 * renamed 'hyphenator' class to to more conventional 'Hyphenator'. 'hyphenator' is deprecated. New in version 0.9.3: * added win32 binary of the C extension for Python 3.1 * added 'syllables' method to the hyphenator (can yield inconsistent results in languages with non-standard hyphenation) New in version 0.9.2 * make it compile with Python 3.0.1 * add win32 binary of the C extension for Python 3.0 New in version 0.9.1 * full support for Python 3.0 * merged 3.0 sources with the 2.x distribution. New in Version 0.9: * removed the 'inserted' method from the hyphenator class as it is not used in practice the word to be hyphenated must now be unicode (utf-8 encoded strings raise TypeError). The restriction to unicode is safer and more 3.0-compliant. * fixed important bug in 'pairs' method that could cause a unicode error if 'word' was not encodable to the dictionary's encoding. In the latter case, the new version returns an empty list (consistent with other cases where the word is not hyphenable). * the configuration script has been simplified and improved: it does not raise ImportError even if the package cannot be imported. This tolerance is needed to create a Debian package. New in Version 0.8 - supports Python 2.x and 3.0 (in 2 separate distributions)) - contains the new C library hyphen-2.4 which implements an extended algorithm supporting: - compound words (dictionaries are under development in the OpenOffice community)) - parameters to fix the minimal number of characters to be cut off by hyphenation (lmin, rmin, compound_lmin and compound_rmin). ) This may require code changes in existing apps. - new en_US dictionary. - many minor improvements under the hood 1. Overview ================ The gole of the PyHyphen project is to provide Python with a high quality hyphenation facility. PyHyphen consists of the package 'hyphen' and the module 'textwrap2'. The source distribution supports Python 2.4 or higher, including Python 3.2. 1.1 Content of the hyphen package ------------------------------------------ The 'hyphen' module defines the following: - at top level the definition of the class 'Hyphenator' each instance of which can hyphenate and wrap words using a dictionary compatible with the hyphenation feature of OpenOffice and Mozilla. - the module dictools contains useful functions such as downloading and installing dictionaries from a configurable repository. After installation of PyHyphen, the OpenOffice repository is used by default. 'dictools.install_dict-info' downloads metadata on all available hyphenation dictionaries from the OpenOffice website and stores it in a pickled file. - hyphen.dict_info: a dict object with metadata on all hyphenation dictionaries downloadable from the OpenOffice website. - config is a configuration file initialized at install time with default values for the directory where dictionaries are searched, and the repository for downloads of dictionaries. Initial values are the package root and the OpenOffice repository for dictionaries. - hnj' is the C extension module that does all the ground work. It contains the C library libhyphen. It supports non-standard hyphenation with replacements as well as compound word hyphenation. Note that hyphenation dictionaries are invisible to the Python programmer. But each hyphenator object has an attribute 'info' which is a dict object containing metadata on the hyphenation dictionary of this Hyphenator instance. The former 'language' attribute, a string of the form 'll_CC' is deprecated as from v1.0. 1.2 The module 'textwrap2' ------------------------------ This module is an enhanced though backwards compatible version of the module 'textwrap' from the Python standard library. Not very surprisingly, it adds hyphenation functionality to 'textwrap'. To this end, a new key word parameter 'use_hyphenator' has been added to the __init__ method of the TextWrapper class which defaults to None. It can be initialized with any hyphenator object. Note that until version 0.7 this keyword parameter was named 'use_hyphens'. So older code may need to be changed.' 1.3 hyphen_test ------------------------------- (no longer part of the distribution as of version 0.9.1; please clone the hg repository to get it) This Python script is a framework for running large tests of the hyphen package. A test is a list of 3 elements: a text file (typically a word list), its encoding and a list of strings specifying a dictionary to be applied to the word list. Adding a test is as easy as writing a function call. All results are logged. 2. Code example ====================== :: >>>from hyphen import Hyphenator from hyphen.dictools import * # Download and install some dictionaries in the default directory using the default # repository, usually the OpenOffice website for lang in ['de_DE', 'fr_FR', 'en_UK', 'ru_RU']: if not is_installed(lang): install(lang) # Create some hyphenators h_de = Hyphenator('de_DE') h_en = Hyphenator('en_US') # Now hyphenate some words # Note: the following examples are written in Python 3.x syntax. # If you use Python 2.x, you must add the 'u' prefixes as Hyphenator methods expect unicode objects. h_en.pairs('beautiful' [['beau', 'tiful'], [u'beauti', 'ful']] h_en.wrap('beautiful', 6) ['beau-', 'tiful'] h_en.wrap('beautiful', 7) ['beauti-', 'ful'] h_en.syllables('beautiful') ['beau', 'ti', 'ful'] h_en.info {'file_name': 'hyph_en_US.zip', 'country_code': 'US', 'name': 'hyph_en_US', 'long_descr': 'English (United States)', 'language_code': 'en'} from textwrap2 import fill print fill('very long text...', width = 40, use_hyphens = h_en) 3. Compiling and installing ================================ 3.1 General requirements --------------------------- PyHyphen works with Python 2.4 or higher, including 3.2. There are pre-compiled binaries of the hnj module for win32 and Python 2.6 to 3.2. On other platforms you will need a build environment such as gcc, make 3.2 Compiling and installing from source ---------------------------------------------- Choose and download the source distribution from http://cheeseshop.python.org/pypi/PyHyphen and unpack it in a temporary directory. Then cd to this directory. You can compile and install the hyphen package as well as the module textwrap2 by entering at the command line somethin like: $python setup.py install The setup script will first check the Python version and copy the required version-specific files. Second, setup.py searches in ./bin for a pre-compiled binary of hnj for your platform. If there is a binary that looks ok, this version is installed. Otherwise, hnj is compiled from source. On Windows you will need MSVC 2003 (Python 2.4 and 2.5) or MSVC 2008 (for Python2.6 or higher), mingw or whatever fits to your Python distribution. If the distribution comes with a binary of 'hnj' that fits to your platform and python version, you can still force a compilation from source by entering $python setup.py install --force_build_ext Under Linux you may need root privileges, so you may want to enter something like $sudo python setup.py install After compiling and installing the hyphen package, config.py is adjusted as follows: - the package directory becomes the local default path for hyphenation dictionaries - the OpenOffice website becomes the default repository from which dictionaries are downloaded. Thereafter, the setup script tries to re-import the hyphen package to install a default set of dictionaries, unless the command line contains the 'no_dictionaries' command after 'install'. The script then tries to install the metadata file by calling hyphen.dictools.install_dict_info. Then, the hyphenation dictionaries for en_US (commonly used) and the local language, if different, are installed. 4. How to get dictionaries? ================================= Information on all hyphenation dictionaries available on the OpenOffice website is stored in hyphen.dict_info. You can also visit http://wiki.services.openoffice.org/wiki/Dictionaries for a complete list. Then use the dictools.install function to download and install the dictionary locally. 5. What's under the hood? ============================== the C extension module 'hnj' used by the hyphenator class defined in __init__.py contains the C library libhyphen which is used by OpenOffice.org, Mozilla and alike. The C sources have not been changed, let alone hnjmalloc.c which has been slightly modify to use pythonic memory management and error handling. For further information on the hyphenation library and available dictionaries visit http://wiki.services.openoffice.org/wiki/Dictionaries. 6. Testing ============== This requires cloning the hg repository, as the test.py module is no longer part of the source distribution. Please see the instructions in Demo/hyphen_test.py. All you need is a text file, and its encoding. Copy the text file into the Demo/input directory, add a new function call to hyphen_test.py, run it and read the .log file and the files created in the output directory. There you will see the results for each word. You can specify a list of dictionaries to be used. Then, hyphen_test will create an output file for each dictionary used with a given word list. 7. Contributing and reporting bugs ===================================== Contributions, comments, bug reports, criticism and praise can be sent to the author. The sources of PyHyphen are found in a Mercurial repository at http://pyhyphen.googlecode.com This is also where you can submit bug reports. Platform: UNKNOWN Classifier: Intended Audience :: Developers Classifier: Development Status :: 4 - Beta Classifier: License :: OSI Approved Classifier: Operating System :: OS Independent Classifier: Programming Language :: Python Classifier: Programming Language :: C Classifier: Topic :: Text Processing Classifier: Topic :: Text Processing :: Linguistic Provides: hyphen Provides: textwrap2 ./PyHyphen-1.0beta1/bin/0000775000175000017500000000000011546766220014245 5ustar takakitakaki./PyHyphen-1.0beta1/bin/hnj.win32-3.1.pyd0000666000175000017500000005100011474454010016767 0ustar takakitakakiMZ@ !L!This program cannot be run in DOS mode. $,Nh/h/h/Oj/v}hj/v}nj/v}j/aWhk/h/+/v}xx/v}ii/v}ji/Richh/PEL,L!  2;P=&@XE RPpdHQ@P.text02 `.rdataP 6@@.data ` @@.rsrcpL@@.relocN@B~V@td$u@u^S\$ VWpd$@uL$h0QQ+PRQu_^[t6w W Q|=U-QXRfu]_^[tw PQf_^[̃4f4cUl$PVuC{|U_^][QSUl$VW@3ҹ{j |$JT$ŃH$@u+OQWUShT$0D$(L$ ;^_V4^][YS3ҹ{D$t8d$JƊ:utX:Yuu3t ũ[ËB[VSG PVSG H u@G(RPtG(G W( @G O(@DG @G(D G W( @DG O(@DG PW ^V4@C(Wxu jWuPQRK(DS(DL$ S(DL$ LS(DD_^́X$\SUhi33P\$l$4xPD$;u ]3[XV3Wt$ ;t|9l$4rh, U3hDj{RT$,}j0j|@G G((O(iW(B G(hO(io,GGGo;t$(oT$$n3EREEjE UEtP teFH t u@ t uH t u@H t u@H t u@uEiŐ:u*tH:NuuT$(333J$1T$(3Ʌ3J$F+ȍQ @uV$W$D$$PL$@jdQtP =|$<%5pPj T$@hiRփ j D$@hiPփ uL$IQlPjT$@hiRփ uD$JPlPGjL$@hiQփ uT$QRlPGdjD$@hiPփ uL$RQlPG9jT$@hiRփ D$Dl$Dt< t< uEEu|$<t1ōPd$@u+‹FP<VUS3_Op@u+ƍDH;GL$ L(8,uW+;AwwhPT$lPUFVD$ӃUD$@D$P@u+ˆD$D$P@u+‹FPL$VQS`l$$3\$8L$<I< }%<0|<9 ,A䈄,EƄ,0Aэ,Ƅ,3D$0l$u!$0IE,0t$<.u D$l$$3 <.$p@u+@;sc $ tE}D$;u؈L$| T$+;t$Ap@u+@;r*L$L$$.l$uL$\$S$D$,D$ōH$@u+FP|VUSD$$@3O(W(L$HLL$"W(LL$#u$qAu+΃|$W(L l$0MMD$\$S$D$4L$ED$MW(4@\2D$2u jSuPQRO(D1W(D2L$ ؋W(D2L$0LW(D2D2M|$SD$$PL$@jdQtP D$4\$3l$T$D$,tME8t,L$pQ؃}T$FR؃|Et O(@\ muD$@={D$|T$RD$$t$$3ۃ\$3wD$$PdP_^u L$$T$ J,D$ ][XUW|$ 39o ~DSV3ۋw(t PFt Pvt V}E;o |^[G,t PGt PRG(PFW@_]́SUV$ F=}D$ PȉD$ 3.~$t$ 3@C;$ |l$ $ +.CF+~P$(j0P 33WL$)t8$i(@L|3~w8t@;|G u3SOD@tLt=yu7΍yIAuT$++B>t$(ʋ8}FA>uL$l$A;ˉL$T$$S$(3~sʋ󤋴$$;0_}+R j0Q D$;t U^]3[D$w $p%3ÍIj%j%j%d%d%j%j%Ul$ V33Ʌ~FT$ W|$t5Ft@F;|>.F3;t$8>~$Vj0R ;l$$zD$$L$(t4$R(DmL<3~w8t@;|o u3Ol$H(TmэыJL$JR L$T$Vd$Fu|$$++G|$tQ|$0u7$~-t$\$$+މL$0I3uT$L$t$ ׉ 38tlT$T$,+ЋȉT$4$NJ0:};0t1D$\$,t#\$;|D$;D$߉T$4D$,AF9uD$$@;D$8D$$T$83~$w‹$;}%$$+Rj0QK $ $$$$3]|$0ID$:l$|+;t:uo?uj$<WPWP$ WP$$$ 3;:9@;|D$ T$D$4x@u+NjGP L$8WQU D$ / $l ?у+։T$L$ $L$$D$ tF;$<9L$t!T$R D$$P L$Q $z,$3d}*$$ $D$L$T$ $.4V VD$ VD$ UD$0 D$,3~͋T$@;|$3, $I$D ED$$u$;+ǃD$4D$(D(3$91}$92tr94tmj=PhP $ T$8̓+ T$(LL$T$0 T$D$0D$ ut +$ +D$(.DL$$$LD$(@#$3R$+I#$Q$RQT$0RL$(QL$DT$(RQT.RP$PD$`H,3D$8&$ L$|$4L$,1L$41T$<$$;$8t$9uh$WPWP$ WP$$ 3I;:9@;$|ۋD$ D$ $ T$$L$ D$8D$F;$L$(T(T) t4$:t($:t<tT$(B+I @u|$$$3$T$@;|l$$;$$$$$$$P$Q$R$P$WUSQH,VRQ,$u/$ $$R$WUSPB$VQPE $u/$$$Q$WUSRQ$VPR D$$;t!5PP֋T$$R֋D$P֋L$8QփD$(_^T$4][;t P3̋D$u"PhiP@PP V39t$D$#S\$(Ul$ +W~l$ D$l$$dPSVW(j1E3PEdeEh*tUE-PhPt;@$ЃEMd Y_^[]ËE3=‹ËeE3Md Y_^[]%P%P%P%XPU} u=8Qu u(P3@] h>d5D$l$l$+SVW(j1E3PeuEEEEdËMd Y__^[]QËUuuu uh?h(j]ËU(jeeSWN@;t t У,j`VEPPu3uP3P3 P3EP$PE3E3;uO@ u 5(j։5,j^_[%TP%PP%LP%HP; (ju%@PU(`k \kXkTk5Pk=Lkfxkf lkfHkfDkf%@kf-V:U(UUUTTTTTTpT`TPT;g;{;q<=>SJUPRUV:U(UUUTTTTTTpT`TPTUnhandledExceptionFilterSetUnhandledExceptionFilterIsDebuggerPresentKERNEL32.dll,LrXhXlXpXzXhnj.pydPyInit_hnjSUMMARY: apply(word: unicode object, mode: int) -> hyphenated word (return type depends on value of mode) Note: 'hnjmodule' should normally be called only from the convenience interface provided bythe hyphen.hyphenator class. word: must be lower-cased to be hyphenated correctly. Capital letters are restored according to the value of 'mode'. The encoded representation of 'word' may have at most 100 bytes including the terminating ''. mode: the 3 least significant bits are interpreted as flags with the following meaning: - mode & 1 = 0: return a string with '=' inserted at the hyphenation points - mode & 1 = 1: return a list of lists of the form [before_hyphen, after_hyphen] - mode & 2 = 1: return a capitalized word - mode & 4 = 1: return an upper-cased word =esiWord to be hyphenated may have at most 100 characters.Cannot hyphenate word.applyc`siiiiCannot load hyphen dictionary.Wrapper class for the hnj_hyphen library contained in this module. Usage: hyphenator_(dict_file_name: string) The init method will try to load a hyphenation dictionary with the filename passed. If an error occurs when trying to load the dictionary, IOError is raised. Dictionary files compatible with hnjmodule can be downloaded at the OpenOffice website. This class should normally be instantiated only by the convenience interface provided by the hyphen.hyphenator class. hnjmodule.hyphenator_e0cc`hnjmodule.Strfhnjmodule.NulltghnjThis C extension module is a wrapper around the hyphenation library 'hyphen-2.3.1' (2008-02-19). It should normally be imported and invoked only by the convenience interface provided by the hyphen.hyphenator class. LhPh4jhnj.errorerrorStrNullhyphenator_rUTF-8NEXTLEVELLEFTHYPHENMINRIGHTHYPHENMINCOMPOUNDLEFTHYPHENMINCOMPOUNDRIGHTHYPHENMINNOHYPHENerror - bad, non UTF-8 input: %s N@D0 HXp PADPADDINGXXPADDINGPADDINGXXPADDINGPADDL0W0s00001161=1D1O1b11111F2g2{2222q3A455.555H666666666666667 777&71777?7I7Q7Z7_7m7r7z777777 ;3;~;<<<=(=A=V=k=======>>? @,22`5p5t5x5|555566F77777777288*<3??001S2Y2c245p5677777777%8.858:8P8\8z88888888899!9&929B9H9O9f9l99999999::*:2:]:d:i:n:u::::::(;U;;;;;;;<<56><>B>S>_>m>>>>>?#?/?7???K?o?w??????????????????@40 000!0-060;0A0K0T0_0k0p00000000P $1<1@111111122`$3335506L6l6677<9@9H9./PyHyphen-1.0beta1/bin/hnj.win32-2.6.pyd0000666000175000017500000005000011474442376017006 0ustar takakitakakiMZ@ !L!This program cannot be run in DOS mode. $,Nh/h/h/Oj/v}dj/v}bj/v}sj/aWdk/h/*/v}tx/v}ei/v}fi/Richh/PEL)L!  2F;P6 XB RPpL@Q@P.textZ02 `.rdatabP 6@@.data ` @@.rsrcpJ@@.relocL@B~V@td$u@u^S\$ VWpd$@uL$h(QQ+PRQu_^[t6w WQ|=U- QXRfu]_^[tw P Qf_^[̃4fcUl$PVuC{|U_^][QSUl$VW@3ҹ{j |$JT$ŃH$@u+OQWUShT$0D$(L$ ;^_V4^][YS3ҹ{D$t8d$JƊ:utX:Yuu3t ũ[ËB[VSG PVSG H u@G(RPtG(G W( @G O(@DG @G(D G W( @DG O(@DG PW ^V4@C(Wxu jWuPQRK(DS(DL$ S(DL$ LS(DD_^́X$\SUhlh33P\$l$4tPD$;u ]3[XV3Wt$ ;t|9l$4rh, U3h4i{RT$,}j0j|@G G((O(iW(B G(hO(io,GGGo;t$(oT$$n3EREEjE UEpP teFH t u@ t uH t u@H t u@H t u@uEphŐ:u*tH:NuuT$(333J$1T$(3Ʌ3J$F+ȍQ @uV$W$D$$PL$@jdQpP =|$<%5lPj T$@hxhRփ j D$@hhPփ uL$IQhPjT$@hhRփ uD$JPhPGjL$@hhQփ uT$QRhPGdjD$@hhPփ uL$RQhPG9jT$@hhRփ D$Dl$Dt< t< uEEu|$<t1ōPd$@u+‹FP<VUS3_Op@u+ƍDH;GL$ L(8,uW+;AwwdPT$hPUFVD$ӃUD$@D$P@u+ˆD$D$P@u+‹FPL$VQS`l$$3\$8L$<I< }%<0|<9 ,A䈄,EƄ,0Aэ,Ƅ,3D$0l$u!$0IE,0t$<.u D$l$$3 <.$p@u+@;sc $ tE}D$;u؈L$| T$+;t$Ap@u+@;r*L$L$$.l$uL$\$S$D$,D$ōH$@u+FP|VUSD$$@3O(W(L$HLL$"W(LL$#u$qAu+΃|$W(L l$0MMD$\$S$D$4L$ED$MW(4@\2D$2u jSuPQRO(D1W(D2L$ ؋W(D2L$0LW(D2D2M|$SD$$PL$@jdQpP D$4\$3l$T$D$,tME8t,L$pQ؃}T$FR؃|Et O(@\ muD$@={D$|T$RD$$t$$3ۃ\$3wD$$P`P_^u L$$T$ J,D$ ][XUW|$ 39o ~DSV3ۋw(t PFt Pvt V}E;o |^[G,t PGt PRG(PFW@_]́SUV$ F=}D$ PȉD$ 3.~$t$ 3@C;$ |l$ $ +.CF+~P$(j0P 33WL$)t8$i(@L|3~w8t@;|G u3SOD@tLt=yu7΍yIAuT$++B>t$(ʋ8}FA>uL$l$A;ˉL$T$$S$(3~sʋ󤋴$$;0_}+R j0Q D$;t U^]3[D$w $%3ÍI % % %%% % %Ul$ V33Ʌ~FT$ W|$t5Ft@F;|>.F3;t$8>~$Vj0R ;l$$zD$$L$(t4$R(DmL<3~w8t@;|o u3Ol$H(TmэыJL$JR L$T$Vd$Fu|$$++G|$tQ|$0u7$~-t$\$$+މL$0I3uT$L$t$ ׉ 38tlT$T$,+ЋȉT$4$NJ0:};0t1D$\$,t#\$;|D$;D$߉T$4D$,AF9uD$$@;D$8D$$T$83~$w‹$;}%$$+Rj0QK $ $$$$3]|$0ID$:l$|+;t:uo?uj$<WPWP$ WP$$$ 3;:9@;|D$ T$D$4x@u+NjGP L$8WQU D$ / $l ?у+։T$L$ $L$$D$ tF;$<9L$t!T$R D$$P L$Q $z,$3d}*$$ $D$L$T$ $.4V VD$ VD$ UD$0 D$,3~͋T$@;|$3, $I$D ED$$u$;+ǃD$4D$(D(3$91}$92tr94tmj=PdP $ T$8̓+ T$(LL$T$0 T$D$0D$ ut +$ +D$(.DL$$$LD$(@#$3R$+I#$Q$RQT$0RL$(QL$DT$(RQT.RP$PD$`H,3D$8&$ L$|$4L$,1L$41T$<$$;$8t$9uh$WPWP$ WP$$ 3I;:9@;$|ۋD$ D$ $ T$$L$ D$8D$F;$L$(T(T) t4$:t($:t<tT$(B+I @u|$$$3$T$@;|l$$;$$$$$$$P$Q$R$P$WUSQH,VRQ,$u/$ $$R$WUSPB$VQPE $u/$$$Q$WUSRQ$VPR D$$;t!5|PP֋T$$R֋D$P֋L$8QփD$(_^T$4][;t P3̋D$u"PhhP@PP V39t$D$#S\$(Ul$ +W~l$ D$l$$dPSVWi1E3PEdeEh*tUE-PhPt;@$ЃEMd Y_^[]ËE3=‹ËeE3Md Y_^[]%P%P%P%XPU} u=0Qu u(P3@] he>d5D$l$l$+SVWi1E3PeuEEEEdËMd Y__^[]QËUuuu uh8?hi]ËUieeSWN@;t t Уi`VEPPu3uP3P3 P3EP$PE3E3;uO@ u 5i։5i^_[%TP%PP%LP%HP; iu%@PU(Pj LjHjDj5@j=;;;;<==S.UPRUUnhandledExceptionFilterSetUnhandledExceptionFilterIsDebuggerPresentKERNEL32.dll)LRXHXLXPXZXhnj.pydinithnjSUMMARY: apply(word: unicode object, mode: int) -> hyphenated word (return type depends on value of mode) Note: 'hnj' should normally be called only from the convenience interface provided bythe hyphen.hyphenator class. word: must be lower-cased to be hyphenated correctly. Through the flags in mode, the caller can provide information on whether the word was originally capitalized, lower-cased or upper-cased. Capital letters are restored according to the value of 'mode'. The encoded representation of 'word' may have at most 100 bytes including the terminating ''. mode: the 3 least significant bits are interpreted as flags with the following meaning: - mode & 1 = 0: return a string with '=' inserted at the hyphenation points - mode & 1 = 1: return a list of lists of the form [before_hyphen, after_hyphen] - mode & 2 = 1: return a capitalized word - mode & 4 = 1: return an upper-cased word =esiWord to be hyphenated may have at most 100 characters.Cannot hyphenate word.apply$d`siiiiCannot load hyphen dictionary.Wrapper class for the hnj_hyphen library contained in this module. Usage: hyphenator_(dict_file_name: string, lmin, rmin, compound_lmin, compound_rmin: integer) The init method will try to load a hyphenation dictionary with the filename passed. If an error occurs when trying to load the dictionary, IOError is raised. Dictionary files compatible with hnj can be downloaded at the OpenOffice website. This class should normally be instantiated only by the convenience interface provided by the hyphen.hyphenator class. hyphenator_f xd,dPhnjThis C extension module is a wrapper around the hyphenation library 'hyphen-2.4' (2008-05). It should normally be imported and invoked only by the convenience interface provided by the hyphen.hyphenator class. hnj.errorerrorhyphenator_cannot initialize module hnj.rUTF-8NEXTLEVELLEFTHYPHENMINRIGHTHYPHENMINCOMPOUNDLEFTHYPHENMINCOMPOUNDRIGHTHYPHENMINNOHYPHENerror - bad, non UTF-8 input: %s N@D0 HXp PADPADDINGXXPADDINGPADDINGXXPADDINGPADDL0W0s00001161=1D1O1b11111D2g2r2222p3?455.555o6v6666666666666 7777#7)7/74797@7I7S7Y7::;;)<<<<<< = =6=K=a=v==I>>> D1255555 5$5(5>666(7,7074787<7@77<8;;;>???011124566(777M7\7r7x7~77777778"8,878M8V8n888888888889 9-929C9[9s9y9999999: :::":3:P:]:u:::=;j;x;;;;;;;;;5<:<[<`<==/=M=a=g======= >*>w>|>>>>>>>>??"?(?.?4?:?J?Z?`?f?l?r?x??????????????????@ 00 0%0+010G0N0V0P 14181|11111122`,404846667$7./PyHyphen-1.0beta1/bin/hnj.win32-3.2.pyd0000666000175000017500000005100011546012676017000 0ustar takakitakakiMZ@ !L!This program cannot be run in DOS mode. $, hj|hj|hj|Ojj|v8jj|v8jj|v8mj|hj}+j|v8xj|v8ij|v8ij|Richhj|PEL/xM!  2;P@XE RPpdHQ@P.text02 `.rdataP 6@@.data ` @@.rsrcpL@@.relocN@B~V@td$u@u^S\$ VWpd$@uL$h0QQ+PRQu_^[t6w W Q|=U-QXRfu]_^[tw PQf_^[̃4f4cUl$PVuC{|U_^][QSUl$VW@3ҹ{j |$JT$ŃH$@u+OQWUShT$0D$(L$ ;^_V4^][YS3ҹ{D$t8d$JƊ:utX:Yuu3t ũ[ËB[VSG PVSG H u@G(RPtG(G W( @G O(@DG @G(D G W( @DG O(@DG PW ^V4@C(Wxu jWuPQRK(DS(DL$ S(DL$ LS(DD_^́X$\SUhi33P\$l$4xPD$;u ]3[XV3Wt$ ;t|9l$4rh, U3hDj{RT$,}j0j|@G G((O(iW(B G(hO(io,GGGo;t$(oT$$n3EREEjE UEtP teFH t u@ t uH t u@H t u@H t u@uEiŐ:u*tH:NuuT$(333J$1T$(3Ʌ3J$F+ȍQ @uV$W$D$$PL$@jdQtP =|$<%5pPj T$@hiRփ j D$@hiPփ uL$IQlPjT$@hiRփ uD$JPlPGjL$@hiQփ uT$QRlPGdjD$@hiPփ uL$RQlPG9jT$@hiRփ D$Dl$Dt< t< uEEu|$<t1ōPd$@u+‹FP<VUS3_Op@u+ƍDH;GL$ L(8,uW+;AwwhPT$lPUFVD$ӃUD$@D$P@u+ˆD$D$P@u+‹FPL$VQS`l$$3\$8L$<I< }%<0|<9 ,A䈄,EƄ,0Aэ,Ƅ,3D$0l$u!$0IE,0t$<.u D$l$$3 <.$p@u+@;sc $ tE}D$;u؈L$| T$+;t$Ap@u+@;r*L$L$$.l$uL$\$S$D$,D$ōH$@u+FP|VUSD$$@3O(W(L$HLL$"W(LL$#u$qAu+΃|$W(L l$0MMD$\$S$D$4L$ED$MW(4@\2D$2u jSuPQRO(D1W(D2L$ ؋W(D2L$0LW(D2D2M|$SD$$PL$@jdQtP D$4\$3l$T$D$,tME8t,L$pQ؃}T$FR؃|Et O(@\ muD$@={D$|T$RD$$t$$3ۃ\$3wD$$PdP_^u L$$T$ J,D$ ][XUW|$ 39o ~DSV3ۋw(t PFt Pvt V}E;o |^[G,t PGt PRG(PFW@_]́SUV$ F=}D$ PȉD$ 3.~$t$ 3@C;$ |l$ $ +.CF+~P$(j0P 33WL$)t8$i(@L|3~w8t@;|G u3SOD@tLt=yu7΍yIAuT$++B>t$(ʋ8}FA>uL$l$A;ˉL$T$$S$(3~sʋ󤋴$$;0_}+R j0Q D$;t U^]3[D$w $p%3ÍIj%j%j%d%d%j%j%Ul$ V33Ʌ~FT$ W|$t5Ft@F;|>.F3;t$8>~$Vj0R ;l$$zD$$L$(t4$R(DmL<3~w8t@;|o u3Ol$H(TmэыJL$JR L$T$Vd$Fu|$$++G|$tQ|$0u7$~-t$\$$+މL$0I3uT$L$t$ ׉ 38tlT$T$,+ЋȉT$4$NJ0:};0t1D$\$,t#\$;|D$;D$߉T$4D$,AF9uD$$@;D$8D$$T$83~$w‹$;}%$$+Rj0QK $ $$$$3]|$0ID$:l$|+;t:uo?uj$<WPWP$ WP$$$ 3;:9@;|D$ T$D$4x@u+NjGP L$8WQU D$ / $l ?у+։T$L$ $L$$D$ tF;$<9L$t!T$R D$$P L$Q $z,$3d}*$$ $D$L$T$ $.4V VD$ VD$ UD$0 D$,3~͋T$@;|$3, $I$D ED$$u$;+ǃD$4D$(D(3$91}$92tr94tmj=PhP $ T$8̓+ T$(LL$T$0 T$D$0D$ ut +$ +D$(.DL$$$LD$(@#$3R$+I#$Q$RQT$0RL$(QL$DT$(RQT.RP$PD$`H,3D$8&$ L$|$4L$,1L$41T$<$$;$8t$9uh$WPWP$ WP$$ 3I;:9@;$|ۋD$ D$ $ T$$L$ D$8D$F;$L$(T(T) t4$:t($:t<tT$(B+I @u|$$$3$T$@;|l$$;$$$$$$$P$Q$R$P$WUSQH,VRQ,$u/$ $$R$WUSPB$VQPE $u/$$$Q$WUSRQ$VPR D$$;t!5PP֋T$$R֋D$P֋L$8QփD$(_^T$4][;t P3̋D$u"PhiP@PP V39t$D$#S\$(Ul$ +W~l$ D$l$$dPSVW(j1E3PEdeEh*tUE-PhPt;@$ЃEMd Y_^[]ËE3=‹ËeE3Md Y_^[]%P%P%P%XPU} u=8Qu u(P3@] h>d5D$l$l$+SVW(j1E3PeuEEEEdËMd Y__^[]QËUuuu uh?h(j]ËU(jeeSWN@;t t У,j`VEPPu3uP3P3 P3EP$PE3E3;uO@ u 5(j։5,j^_[%TP%PP%LP%HP; (ju%@PU(`k \kXkTk5Pk=Lkfxkf lkfHkfDkf%@kf-;g;{;q<=>SFUPRUUnhandledExceptionFilterSetUnhandledExceptionFilterIsDebuggerPresentKERNEL32.dll/xMrXhXlXpXzXhnj.pydPyInit_hnjSUMMARY: apply(word: unicode object, mode: int) -> hyphenated word (return type depends on value of mode) Note: 'hnjmodule' should normally be called only from the convenience interface provided bythe hyphen.hyphenator class. word: must be lower-cased to be hyphenated correctly. Capital letters are restored according to the value of 'mode'. The encoded representation of 'word' may have at most 100 bytes including the terminating ''. mode: the 3 least significant bits are interpreted as flags with the following meaning: - mode & 1 = 0: return a string with '=' inserted at the hyphenation points - mode & 1 = 1: return a list of lists of the form [before_hyphen, after_hyphen] - mode & 2 = 1: return a capitalized word - mode & 4 = 1: return an upper-cased word =esiWord to be hyphenated may have at most 100 characters.Cannot hyphenate word.applyc`siiiiCannot load hyphen dictionary.Wrapper class for the hnj_hyphen library contained in this module. Usage: hyphenator_(dict_file_name: string) The init method will try to load a hyphenation dictionary with the filename passed. If an error occurs when trying to load the dictionary, IOError is raised. Dictionary files compatible with hnjmodule can be downloaded at the OpenOffice website. This class should normally be instantiated only by the convenience interface provided by the hyphen.hyphenator class. hnjmodule.hyphenator_e0cc`hnjmodule.Strfhnjmodule.NulltghnjThis C extension module is a wrapper around the hyphenation library 'hyphen-2.3.1' (2008-02-19). It should normally be imported and invoked only by the convenience interface provided by the hyphen.hyphenator class. LhPh4jhnj.errorerrorStrNullhyphenator_rUTF-8NEXTLEVELLEFTHYPHENMINRIGHTHYPHENMINCOMPOUNDLEFTHYPHENMINCOMPOUNDRIGHTHYPHENMINNOHYPHENerror - bad, non UTF-8 input: %s N@D0 HXp PADPADDINGXXPADDINGPADDINGXXPADDINGPADDL0W0s00001161=1D1O1b11111F2g2{2222q3A455.555H666666666666667 777&71777?7I7Q7Z7_7m7r7z777777 ;3;~;<<<=(=A=V=k=======>>? @,22`5p5t5x5|555566F77777777288*<3??001S2Y2c245p5677777777%8.858:8P8\8z88888888899!9&929B9H9O9f9l99999999::*:2:]:d:i:n:u::::::(;U;;;;;;;<<56><>B>S>_>m>>>>>?#?/?7???K?o?w??????????????????@40 000!0-060;0A0K0T0_0k0p00000000P $1<1@111111122`$3335506L6l6677<9@9H9./PyHyphen-1.0beta1/bin/hnj.win32-2.7.pyd0000666000175000017500000005000011474454010016773 0ustar takakitakakiMZ@ !L!This program cannot be run in DOS mode. $, hjxhjxhjxOjjxv8jjxv8jjxv8mjxhjy*jxv8xjxv8ijxv8ijxRichhjxPELL!  2V;P0 XB RPpL@Q@P.textj02 `.rdatabP 6@@.data ` @@.rsrcpJ@@.relocL@B~V@td$u@u^S\$ VWpd$@uL$h(QQ+PRQu_^[t6w WQ|=U- QXRfu]_^[tw P Qf_^[̃4fcUl$PVuC{|U_^][QSUl$VW@3ҹ{j |$JT$ŃH$@u+OQWUShT$0D$(L$ ;^_V4^][YS3ҹ{D$t8d$JƊ:utX:Yuu3t ũ[ËB[VSG PVSG H u@G(RPtG(G W( @G O(@DG @G(D G W( @DG O(@DG PW ^V4@C(Wxu jWuPQRK(DS(DL$ S(DL$ LS(DD_^́X$\SUhlh33P\$l$4tPD$;u ]3[XV3Wt$ ;t|9l$4rh, U3h4i{RT$,}j0j|@G G((O(iW(B G(hO(io,GGGo;t$(oT$$n3EREEjE UEpP teFH t u@ t uH t u@H t u@H t u@uEphŐ:u*tH:NuuT$(333J$1T$(3Ʌ3J$F+ȍQ @uV$W$D$$PL$@jdQpP =|$<%5lPj T$@hxhRփ j D$@hhPփ uL$IQhPjT$@hhRփ uD$JPhPGjL$@hhQփ uT$QRhPGdjD$@hhPփ uL$RQhPG9jT$@hhRփ D$Dl$Dt< t< uEEu|$<t1ōPd$@u+‹FP<VUS3_Op@u+ƍDH;GL$ L(8,uW+;AwwdPT$hPUFVD$ӃUD$@D$P@u+ˆD$D$P@u+‹FPL$VQS`l$$3\$8L$<I< }%<0|<9 ,A䈄,EƄ,0Aэ,Ƅ,3D$0l$u!$0IE,0t$<.u D$l$$3 <.$p@u+@;sc $ tE}D$;u؈L$| T$+;t$Ap@u+@;r*L$L$$.l$uL$\$S$D$,D$ōH$@u+FP|VUSD$$@3O(W(L$HLL$"W(LL$#u$qAu+΃|$W(L l$0MMD$\$S$D$4L$ED$MW(4@\2D$2u jSuPQRO(D1W(D2L$ ؋W(D2L$0LW(D2D2M|$SD$$PL$@jdQpP D$4\$3l$T$D$,tME8t,L$pQ؃}T$FR؃|Et O(@\ muD$@={D$|T$RD$$t$$3ۃ\$3wD$$P`P_^u L$$T$ J,D$ ][XUW|$ 39o ~DSV3ۋw(t PFt Pvt V}E;o |^[G,t PGt PRG(PFW@_]́SUV$ F=}D$ PȉD$ 3.~$t$ 3@C;$ |l$ $ +.CF+~P$(j0P 33WL$)t8$i(@L|3~w8t@;|G u3SOD@tLt=yu7΍yIAuT$++B>t$(ʋ8}FA>uL$l$A;ˉL$T$$S$(3~sʋ󤋴$$;0_}+R j0Q D$;t U^]3[D$w $ %3ÍI%%%%%%%Ul$ V33Ʌ~FT$ W|$t5Ft@F;|>.F3;t$8>~$Vj0R ;l$$zD$$L$(t4$R(DmL<3~w8t@;|o u3Ol$H(TmэыJL$JR L$T$Vd$Fu|$$++G|$tQ|$0u7$~-t$\$$+މL$0I3uT$L$t$ ׉ 38tlT$T$,+ЋȉT$4$NJ0:};0t1D$\$,t#\$;|D$;D$߉T$4D$,AF9uD$$@;D$8D$$T$83~$w‹$;}%$$+Rj0QK $ $$$$3]|$0ID$:l$|+;t:uo?uj$<WPWP$ WP$$$ 3;:9@;|D$ T$D$4x@u+NjGP L$8WQU D$ / $l ?у+։T$L$ $L$$D$ tF;$<9L$t!T$R D$$P L$Q $z,$3d}*$$ $D$L$T$ $.4V VD$ VD$ UD$0 D$,3~͋T$@;|$3, $I$D ED$$u$;+ǃD$4D$(D(3$91}$92tr94tmj=PdP $ T$8̓+ T$(LL$T$0 T$D$0D$ ut +$ +D$(.DL$$$LD$(@#$3R$+I#$Q$RQT$0RL$(QL$DT$(RQT.RP$PD$`H,3D$8&$ L$|$4L$,1L$41T$<$$;$8t$9uh$WPWP$ WP$$ 3I;:9@;$|ۋD$ D$ $ T$$L$ D$8D$F;$L$(T(T) t4$:t($:t<tT$(B+I @u|$$$3$T$@;|l$$;$$$$$$$P$Q$R$P$WUSQH,VRQ,$u/$ $$R$WUSPB$VQPE $u/$$$Q$WUSRQ$VPR D$$;t!5|PP֋T$$R֋D$P֋L$8QփD$(_^T$4][;t P3̋D$u"PhhP@PP V39t$D$#S\$(Ul$ +W~l$ D$l$$dPSVWi1E3PEdeEh*tUE-PhPt;@$ЃEMd Y_^[]ËE3=‹ËeE3Md Y_^[]%P%P%P%XPU} u=0Qu u(P3@] hu>d5D$l$l$+SVWi1E3PeuEEEEdËMd Y__^[]QËUuuu uhH?hi]ËUieeSWN@;t t Уi`VEPPu3uP3P3 P3EP$PE3E3;uO@ u 5i։5i^_[%TP%PP%LP%HP; iu%@PU(Pj LjHjDj5@j=K;;+;!<==S.UPRUUnhandledExceptionFilterSetUnhandledExceptionFilterIsDebuggerPresentKERNEL32.dllLRXHXLXPXZXhnj.pydinithnjSUMMARY: apply(word: unicode object, mode: int) -> hyphenated word (return type depends on value of mode) Note: 'hnj' should normally be called only from the convenience interface provided bythe hyphen.hyphenator class. word: must be lower-cased to be hyphenated correctly. Through the flags in mode, the caller can provide information on whether the word was originally capitalized, lower-cased or upper-cased. Capital letters are restored according to the value of 'mode'. The encoded representation of 'word' may have at most 100 bytes including the terminating ''. mode: the 3 least significant bits are interpreted as flags with the following meaning: - mode & 1 = 0: return a string with '=' inserted at the hyphenation points - mode & 1 = 1: return a list of lists of the form [before_hyphen, after_hyphen] - mode & 2 = 1: return a capitalized word - mode & 4 = 1: return an upper-cased word =esiWord to be hyphenated may have at most 100 characters.Cannot hyphenate word.apply$d`siiiiCannot load hyphen dictionary.Wrapper class for the hnj_hyphen library contained in this module. Usage: hyphenator_(dict_file_name: string, lmin, rmin, compound_lmin, compound_rmin: integer) The init method will try to load a hyphenation dictionary with the filename passed. If an error occurs when trying to load the dictionary, IOError is raised. Dictionary files compatible with hnj can be downloaded at the OpenOffice website. This class should normally be instantiated only by the convenience interface provided by the hyphen.hyphenator class. hyphenator_f0xd,d`hnjThis C extension module is a wrapper around the hyphenation library 'hyphen-2.4' (2008-05). It should normally be imported and invoked only by the convenience interface provided by the hyphen.hyphenator class. hnj.errorerrorhyphenator_cannot initialize module hnj.rUTF-8NEXTLEVELLEFTHYPHENMINRIGHTHYPHENMINCOMPOUNDLEFTHYPHENMINCOMPOUNDRIGHTHYPHENMINNOHYPHENerror - bad, non UTF-8 input: %s N@D0 HXp PADPADDINGXXPADDINGPADDINGXXPADDINGPADDL0W0s00001161=1D1O1b11111F2g2{2222q3A455.5556666666666667 777'7-73797?7D7I7P7Y7c7i7::.;;9<<<<<==0=F=[=q===Y>>> D125 5$5(5,5054585N66687<7@7D7H7L7P77L8;;;)>???0 12 224 56687G7]7l777777778 8*828<8G8]8f8~8888888888899=9B9S9k99999999 ::::%:2:C:`:m:::;M;z;;;;;;;;;>>:>>>>>>>>>>?'?2?8?>?D?J?Z?j?p?v?|??????????????????@ 000 00050;0A0W0^0f0P 14181|11111122`,404846667$7./PyHyphen-1.0beta1/LICENSE.txt0000666000175000017500000006565010774422430015330 0ustar takakitakakiWithout prejudice to the license governing the use of the Python standard module textwrap on which textwrap2 is based, PyHyphen is licensed under the same terms as the underlying C library hyphen-2.3.1. The essential parts of the license terms of hyphen-2.3.1 are quoted hereunder. Extract from the license information of hyphen-2.3.1 library ============================================================ GPL 2.0/LGPL 2.1/MPL 1.1 tri-license Software distributed under these licenses is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the licences for the specific language governing rights and limitations under the licenses. The contents of this software may be used under the terms of the GNU General Public License Version 2 or later (the "GPL"), or the GNU Lesser General Public License Version 2.1 or later (the "LGPL", see COPYING.LGPL) or the Mozilla Public License Version 1.1 or later (the "MPL", see COPYING.MPL). =========================================== GNU LESSER GENERAL PUBLIC LICENSE Version 2.1, February 1999 Copyright (C) 1991, 1999 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. [This is the first released version of the Lesser GPL. It also counts as the successor of the GNU Library Public License, version 2, hence the version number 2.1.] Preamble The licenses for most software are designed to take away your freedom to share and change it. By contrast, the GNU General Public Licenses are intended to guarantee your freedom to share and change free software--to make sure the software is free for all its users. This license, the Lesser General Public License, applies to some specially designated software packages--typically libraries--of the Free Software Foundation and other authors who decide to use it. You can use it too, but we suggest you first think carefully about whether this license or the ordinary General Public License is the better strategy to use in any particular case, based on the explanations below. When we speak of free software, we are referring to freedom of use, 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 and use pieces of it in new free programs; and that you are informed that you can do these things. To protect your rights, we need to make restrictions that forbid distributors to deny you these rights or to ask you to surrender these rights. These restrictions translate to certain responsibilities for you if you distribute copies of the library or if you modify it. For example, if you distribute copies of the library, whether gratis or for a fee, you must give the recipients all the rights that we gave you. You must make sure that they, too, receive or can get the source code. If you link other code with the library, you must provide complete object files to the recipients, so that they can relink them with the library after making changes to the library and recompiling it. And you must show them these terms so they know their rights. We protect your rights with a two-step method: (1) we copyright the library, and (2) we offer you this license, which gives you legal permission to copy, distribute and/or modify the library. To protect each distributor, we want to make it very clear that there is no warranty for the free library. Also, if the library is modified by someone else and passed on, the recipients should know that what they have is not the original version, so that the original author's reputation will not be affected by problems that might be introduced by others. ^L Finally, software patents pose a constant threat to the existence of any free program. We wish to make sure that a company cannot effectively restrict the users of a free program by obtaining a restrictive license from a patent holder. Therefore, we insist that any patent license obtained for a version of the library must be consistent with the full freedom of use specified in this license. Most GNU software, including some libraries, is covered by the ordinary GNU General Public License. This license, the GNU Lesser General Public License, applies to certain designated libraries, and is quite different from the ordinary General Public License. We use this license for certain libraries in order to permit linking those libraries into non-free programs. When a program is linked with a library, whether statically or using a shared library, the combination of the two is legally speaking a combined work, a derivative of the original library. The ordinary General Public License therefore permits such linking only if the entire combination fits its criteria of freedom. The Lesser General Public License permits more lax criteria for linking other code with the library. We call this license the "Lesser" General Public License because it does Less to protect the user's freedom than the ordinary General Public License. It also provides other free software developers Less of an advantage over competing non-free programs. These disadvantages are the reason we use the ordinary General Public License for many libraries. However, the Lesser license provides advantages in certain special circumstances. For example, on rare occasions, there may be a special need to encourage the widest possible use of a certain library, so that it becomes a de-facto standard. To achieve this, non-free programs must be allowed to use the library. A more frequent case is that a free library does the same job as widely used non-free libraries. In this case, there is little to gain by limiting the free library to free software only, so we use the Lesser General Public License. In other cases, permission to use a particular library in non-free programs enables a greater number of people to use a large body of free software. For example, permission to use the GNU C Library in non-free programs enables many more people to use the whole GNU operating system, as well as its variant, the GNU/Linux operating system. Although the Lesser General Public License is Less protective of the users' freedom, it does ensure that the user of a program that is linked with the Library has the freedom and the wherewithal to run that program using a modified version of the Library. The precise terms and conditions for copying, distribution and modification follow. Pay close attention to the difference between a "work based on the library" and a "work that uses the library". The former contains code derived from the library, whereas the latter must be combined with the library in order to run. ^L GNU LESSER GENERAL PUBLIC LICENSE TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 0. This License Agreement applies to any software library or other program which contains a notice placed by the copyright holder or other authorized party saying it may be distributed under the terms of this Lesser General Public License (also called "this License"). Each licensee is addressed as "you". A "library" means a collection of software functions and/or data prepared so as to be conveniently linked with application programs (which use some of those functions and data) to form executables. The "Library", below, refers to any such software library or work which has been distributed under these terms. A "work based on the Library" means either the Library or any derivative work under copyright law: that is to say, a work containing the Library or a portion of it, either verbatim or with modifications and/or translated straightforwardly into another language. (Hereinafter, translation is included without limitation in the term "modification".) "Source code" for a work means the preferred form of the work for making modifications to it. For a library, 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 library. Activities other than copying, distribution and modification are not covered by this License; they are outside its scope. The act of running a program using the Library is not restricted, and output from such a program is covered only if its contents constitute a work based on the Library (independent of the use of the Library in a tool for writing it). Whether that is true depends on what the Library does and what the program that uses the Library does. 1. You may copy and distribute verbatim copies of the Library's complete 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 distribute a copy of this License along with the Library. 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 Library or any portion of it, thus forming a work based on the Library, 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) The modified work must itself be a software library. b) You must cause the files modified to carry prominent notices stating that you changed the files and the date of any change. c) You must cause the whole of the work to be licensed at no charge to all third parties under the terms of this License. d) If a facility in the modified Library refers to a function or a table of data to be supplied by an application program that uses the facility, other than as an argument passed when the facility is invoked, then you must make a good faith effort to ensure that, in the event an application does not supply such function or table, the facility still operates, and performs whatever part of its purpose remains meaningful. (For example, a function in a library to compute square roots has a purpose that is entirely well-defined independent of the application. Therefore, Subsection 2d requires that any application-supplied function or table used by this function must be optional: if the application does not supply it, the square root function must still compute square roots.) These requirements apply to the modified work as a whole. If identifiable sections of that work are not derived from the Library, 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 Library, 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 Library. In addition, mere aggregation of another work not based on the Library with the Library (or with a work based on the Library) on a volume of a storage or distribution medium does not bring the other work under the scope of this License. 3. You may opt to apply the terms of the ordinary GNU General Public License instead of this License to a given copy of the Library. To do this, you must alter all the notices that refer to this License, so that they refer to the ordinary GNU General Public License, version 2, instead of to this License. (If a newer version than version 2 of the ordinary GNU General Public License has appeared, then you can specify that version instead if you wish.) Do not make any other change in these notices. ^L Once this change is made in a given copy, it is irreversible for that copy, so the ordinary GNU General Public License applies to all subsequent copies and derivative works made from that copy. This option is useful when you wish to copy part of the code of the Library into a program that is not a library. 4. You may copy and distribute the Library (or a portion or derivative of it, under Section 2) in object code or executable form under the terms of Sections 1 and 2 above provided that you 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. If distribution of 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 satisfies the requirement to distribute the source code, even though third parties are not compelled to copy the source along with the object code. 5. A program that contains no derivative of any portion of the Library, but is designed to work with the Library by being compiled or linked with it, is called a "work that uses the Library". Such a work, in isolation, is not a derivative work of the Library, and therefore falls outside the scope of this License. However, linking a "work that uses the Library" with the Library creates an executable that is a derivative of the Library (because it contains portions of the Library), rather than a "work that uses the library". The executable is therefore covered by this License. Section 6 states terms for distribution of such executables. When a "work that uses the Library" uses material from a header file that is part of the Library, the object code for the work may be a derivative work of the Library even though the source code is not. Whether this is true is especially significant if the work can be linked without the Library, or if the work is itself a library. The threshold for this to be true is not precisely defined by law. If such an object file uses only numerical parameters, data structure layouts and accessors, and small macros and small inline functions (ten lines or less in length), then the use of the object file is unrestricted, regardless of whether it is legally a derivative work. (Executables containing this object code plus portions of the Library will still fall under Section 6.) Otherwise, if the work is a derivative of the Library, you may distribute the object code for the work under the terms of Section 6. Any executables containing that work also fall under Section 6, whether or not they are linked directly with the Library itself. ^L 6. As an exception to the Sections above, you may also combine or link a "work that uses the Library" with the Library to produce a work containing portions of the Library, and distribute that work under terms of your choice, provided that the terms permit modification of the work for the customer's own use and reverse engineering for debugging such modifications. You must give prominent notice with each copy of the work that the Library is used in it and that the Library and its use are covered by this License. You must supply a copy of this License. If the work during execution displays copyright notices, you must include the copyright notice for the Library among them, as well as a reference directing the user to the copy of this License. Also, you must do one of these things: a) Accompany the work with the complete corresponding machine-readable source code for the Library including whatever changes were used in the work (which must be distributed under Sections 1 and 2 above); and, if the work is an executable linked with the Library, with the complete machine-readable "work that uses the Library", as object code and/or source code, so that the user can modify the Library and then relink to produce a modified executable containing the modified Library. (It is understood that the user who changes the contents of definitions files in the Library will not necessarily be able to recompile the application to use the modified definitions.) b) Use a suitable shared library mechanism for linking with the Library. A suitable mechanism is one that (1) uses at run time a copy of the library already present on the user's computer system, rather than copying library functions into the executable, and (2) will operate properly with a modified version of the library, if the user installs one, as long as the modified version is interface-compatible with the version that the work was made with. c) Accompany the work with a written offer, valid for at least three years, to give the same user the materials specified in Subsection 6a, above, for a charge no more than the cost of performing this distribution. d) If distribution of the work is made by offering access to copy from a designated place, offer equivalent access to copy the above specified materials from the same place. e) Verify that the user has already received a copy of these materials or that you have already sent this user a copy. For an executable, the required form of the "work that uses the Library" must include any data and utility programs needed for reproducing the executable from it. However, as a special exception, the materials to be 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. It may happen that this requirement contradicts the license restrictions of other proprietary libraries that do not normally accompany the operating system. Such a contradiction means you cannot use both them and the Library together in an executable that you distribute. ^L 7. You may place library facilities that are a work based on the Library side-by-side in a single library together with other library facilities not covered by this License, and distribute such a combined library, provided that the separate distribution of the work based on the Library and of the other library facilities is otherwise permitted, and provided that you do these two things: a) Accompany the combined library with a copy of the same work based on the Library, uncombined with any other library facilities. This must be distributed under the terms of the Sections above. b) Give prominent notice with the combined library of the fact that part of it is a work based on the Library, and explaining where to find the accompanying uncombined form of the same work. 8. You may not copy, modify, sublicense, link with, or distribute the Library except as expressly provided under this License. Any attempt otherwise to copy, modify, sublicense, link with, or distribute the Library 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. 9. 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 Library or its derivative works. These actions are prohibited by law if you do not accept this License. Therefore, by modifying or distributing the Library (or any work based on the Library), you indicate your acceptance of this License to do so, and all its terms and conditions for copying, distributing or modifying the Library or works based on it. 10. Each time you redistribute the Library (or any work based on the Library), the recipient automatically receives a license from the original licensor to copy, distribute, link with or modify the Library 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 with this License. ^L 11. 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 Library at all. For example, if a patent license would not permit royalty-free redistribution of the Library 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 Library. 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. 12. If the distribution and/or use of the Library is restricted in certain countries either by patents or by copyrighted interfaces, the original copyright holder who places the Library 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. 13. The Free Software Foundation may publish revised and/or new versions of the Lesser 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 Library 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 Library does not specify a license version number, you may choose any version ever published by the Free Software Foundation. ^L 14. If you wish to incorporate parts of the Library into other free programs whose distribution conditions are incompatible with these, 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 15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE LIBRARY "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 LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 16. 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 LIBRARY 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 LIBRARY (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 LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. END OF TERMS AND CONDITIONS ^L How to Apply These Terms to Your New Libraries If you develop a new library, and you want it to be of the greatest possible use to the public, we recommend making it free software that everyone can redistribute and change. You can do so by permitting redistribution under these terms (or, alternatively, under the terms of the ordinary General Public License). To apply these terms, attach the following notices to the library. 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 library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; 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. You should also get your employer (if you work as a programmer) or your school, if any, to sign a "copyright disclaimer" for the library, if necessary. Here is a sample; alter the names: Yoyodyne, Inc., hereby disclaims all copyright interest in the library `Frob' (a library for tweaking knobs) written by James Random Hacker. , 1 April 1990 Ty Coon, President of Vice That's all there is to it! ./PyHyphen-1.0beta1/src/0000775000175000017500000000000011546766220014264 5ustar takakitakaki./PyHyphen-1.0beta1/src/hnjmodule.c0000666000175000017500000003323211546030414016407 0ustar takakitakaki#include "Python.h" #include "structmember.h" #include "hyphen.h" #include "string.h" /* String constants for calls of Py_Unicode_FromEncodedObject etc.*/ static const char unicode_errors[] = "strict"; /* is raised if hnj_hyphen returns an error while trying to hyphenate a word*/ static PyObject *ErrorObject; /* ----------------------------------------------------- */ /* Declarations for objects of type hyphenator_ */ /* type object to store the hyphenation dictionary. Its only method is 'apply' which calls the core function 'hnj_hyphenate2'' from the wrapped library 'hnj_hyphen-2.3' */ typedef struct { PyObject_HEAD HyphenDict *dict; int lmin, rmin, compound_lmin, compound_rmin; } HyDictobject; static PyTypeObject HyDict_type; /* ---------------------------------------------------------------- */ static char HyDict_apply__doc__[] = "SUMMARY:\n\ apply(word: unicode object, mode: int) -> hyphenated word (return type depends on value of mode)\n\n\ Note: 'hnj' should normally be called only from the convenience interface provided by\ the hyphen.hyphenator class.\n\n\ word: must be lower-cased to be hyphenated correctly. Through the flags in mode,\n\ the caller can provide information on whether the word was originally capitalized, \n\ lower-cased or upper-cased. Capital letters are restored \n\ according to the value of 'mode'. The encoded representation of 'word'\n\ may have at most 100 bytes including the terminating '\0'.\n\ mode: the 3 least significant bits are interpreted as flags with the following meaning:\n\ - mode & 1 = 0: return a string with '=' inserted at the hyphenation points\n\ - mode & 1 = 1: return a list of lists of the form [before_hyphen, after_hyphen]\n\ - mode & 2 = 1: return a capitalized word\n\ - mode & 4 = 1: return an upper-cased word\n"; /* get a pointer to the nth 8-bit or UTF-8 character of the word */ /* This is required because some operations are done at utf8 string level. */ static char * hindex(char * word, int n, int utf8) { int j = 0; while (j < n) { j++; word++; while (utf8 && ((((unsigned char) *word) >> 6) == 2)) word++; } return word; } /* Depending on the value of 'mode', convert a utf8 C string to PyUnicode or PyString (utf8), handle also capitalization and upper case words. */ static PyObject * prepare_result(char *word, char *encoding, int mode) { Py_UNICODE * ch_u; PyObject *result; int len_s, i; /* first convert the C string to unicode. */ if (!(result = PyUnicode_Decode(word, strlen(word), encoding, unicode_errors))) return NULL; if (mode & 4) { /* capitalize entire word */ ch_u = PyUnicode_AS_UNICODE(result); len_s = PyUnicode_GetSize(result); for (i=0; i <= len_s; i++) { *ch_u = Py_UNICODE_TOUPPER(*ch_u); ch_u++; } } else { if (mode & 2) { /* capitalize first letter */ ch_u = PyUnicode_AS_UNICODE(result); *ch_u = Py_UNICODE_TOUPPER(*ch_u); } } /* return a unicode object */ return result; } /* core function of the hyphenator_ object type */ static PyObject * HyDict_apply(HyDictobject *self, PyObject *args) { const char separator[] = "="; char *hyphenated_word, *hyphens, *word_str; char ** rep = NULL; char r; int * pos = NULL; int * cut = NULL; unsigned int wd_size, hyph_count, i, j, k, mode; PyObject *result, *s1, *s2, *separator_u = NULL; /* mode: bit0 === 1: return a tuple, otherwise a word with '=' inserted at the positions of possible hyphenations. bit1 == 1: word must be capitalized before returning bit2 == 1: entire word must be uppered before returning */ /* parse and check arguments */ if (!PyArg_ParseTuple(args, "esi", &self->dict->cset, &word_str, &mode)) return NULL; wd_size = strlen(word_str); if (wd_size >= MAX_CHARS) { PyErr_SetString(PyExc_ValueError, "Word to be hyphenated may have at most 100 characters."); PyMem_Free(word_str); return NULL; } /* allocate memory for the return values of the core function hnj_hyphenate2*/ hyphens = (char *) PyMem_Malloc(wd_size + 5); hyphenated_word = (char *) PyMem_Malloc(wd_size * 3); /* now actually try the hyphenation*/ if (hnj_hyphen_hyphenate3(self->dict, word_str, wd_size, hyphens, hyphenated_word, &rep, &pos, &cut, self->lmin, self->rmin, self->compound_lmin, self->compound_rmin)) { PyMem_Free(hyphens); PyMem_Free(hyphenated_word); PyMem_Free(word_str); PyErr_SetString(ErrorObject, "Cannot hyphenate word."); return NULL; } /* Count possible hyphenations. This is done by checking bit 0 of each */ /* char of 'hyphens' which is 0 if and only if the word can be hyphened */ /* at that position. Then proceed to */ /* the real work, i.d. returning a unicode object with inserted '=' at each */ /* possible hyphenation, or return a list of lists of two unicode objects */ /* representing a possible hyphenation each. Note that the string */ /* is useful only in languages without non-standard hyphenation, as */ /* the string could contain more than one replacement, whereas */ /* we are only interested in one replacement at the hyphenation position */ /* we choose. */ /* If no hyphenations were found, a string with 0 inserted '=', i.e. the original word, */ /* or an empty list (with 0 pairs) is returned. */ hyph_count = 0; for (i=0; (i+1) < strlen(hyphens); i++) { if (hyphens[i] & 1) hyph_count++; } /* Do we need to return a string with inserted '=', or a list of pairs? */ if (!(mode & 1)) { /* Prepare for returning a unicode obj of the form 'before_hyphen=after_hyphen. */ if (!(result = prepare_result(hyphenated_word, self->dict->cset, mode))) { PyMem_Free(hyphenated_word); PyMem_Free(word_str); PyMem_Free(hyphens); return NULL; } PyMem_Free(hyphenated_word); } else { PyMem_Free(hyphenated_word); /* construct a list of lists of two unicode objects. Each inner list */ /* represents a possible hyphenation. */ /* First create the outer list. Each element will be a list of two strings or unicode objects. */ if (!(result = PyList_New(hyph_count))) { PyMem_Free(hyphens); PyMem_Free(word_str); return NULL; } /* now fill the resulting list from left to right with the pairs */ j=0; hyph_count = 0; /* The following is needed to split the word (in which an '=' indicates the */ /* hyphen position) */ separator_u = PyUnicode_Decode(separator, 1, self->dict->cset, unicode_errors); for (i = 0; (i + 1) < strlen(word_str); i++) { /* j-th character utf8? Then just increment j */ if (self->dict->utf8 && ((((unsigned char) word_str[i]) >> 6) == 2)) continue; /* Is here a hyphen? */ if ((hyphens[j] & 1)) { /* Build the hyphenated word at C string level. */ /* first, handle non-standard hyphenation with replacement. */ if (rep && rep[j]) { /* determine the position within word_str where to insert rep[j] */ /* do the replacement by appending the three substrings: */ hyphenated_word = (char *) PyMem_Malloc(strlen(word_str) + strlen(rep[j])+1); k = hindex(word_str, j - pos[j] + 1, self->dict->utf8) - word_str; r = word_str[k]; word_str[k] = 0; strcpy(hyphenated_word, word_str); strcat(hyphenated_word, rep[j]); word_str[k] = r; strcat(hyphenated_word, hindex(word_str + k, cut[j], self->dict->utf8)); } else { /* build the word in case of standard hyphenation. */ /* An '=' will be inserted so that the */ /* resulting string has the same format as in the non-standard case. */ hyphenated_word = (char *) PyMem_Malloc(strlen(word_str) + 2); k = hindex(word_str, j + 1, self->dict->utf8) - word_str; r = word_str[k]; word_str[k] = 0; strcpy(hyphenated_word, word_str); strcat(hyphenated_word, separator); word_str[k] = r; strcat(hyphenated_word, word_str + k); } /* Now prepare the resulting unicode object according to the value of mode */ if (!(s1 = prepare_result(hyphenated_word, self->dict->cset, mode))) { PyMem_Free(hyphenated_word); PyMem_Free(hyphens); PyMem_Free(word_str); return NULL; } PyMem_Free(hyphenated_word); /* split it into two parts at the position of the '=' */ /* and write the resulting list into the tuple */ if (!((s2 = PyUnicode_Split(s1, separator_u, 1)) && (!PyList_SetItem(result, hyph_count++, s2)))) { Py_XDECREF(s2); Py_DECREF(s1); PyMem_Free(hyphens); PyMem_Free(word_str); return NULL; } Py_DECREF(s1); } /* finished with current hyphen */ j++; } /* for loop*/ Py_DECREF(separator_u); } /* end of else construct a list */ PyMem_Free(hyphens); PyMem_Free(word_str); return result; } static struct PyMethodDef HyDict_methods[] = { {"apply", (PyCFunction)HyDict_apply, METH_VARARGS, HyDict_apply__doc__}, {NULL, NULL} /* sentinel */ }; /* ---------- */ static void HyDict_dealloc(HyDictobject *self) { if (self->dict) hnj_hyphen_free(self->dict); self->ob_type->tp_free((PyObject*) self); } static int HyDict_init(HyDictobject *self, PyObject *args) { char* fn; if (!PyArg_ParseTuple(args, "siiii", &fn, &self->lmin, &self->rmin, &self->compound_lmin, &self->compound_rmin)) return -1; if (!(self->dict = hnj_hyphen_load(fn))) { if (!PyErr_Occurred()) PyErr_SetString(PyExc_IOError, "Cannot load hyphen dictionary."); return -1; } return 0; } static char HyDict_type__doc__[] = "Wrapper class for the hnj_hyphen library contained in this module.\n\n\ Usage: hyphenator_(dict_file_name: string, lmin, rmin, compound_lmin, compound_rmin: integer)\n\ The init method will try to load a hyphenation dictionary with the filename passed.\n\ If an error occurs when trying to load the dictionary, IOError is raised.\n\ Dictionary files compatible with hnj can be downloaded at the OpenOffice website.\n\n\ This class should normally be instantiated only by the convenience interface provided by\n\ the hyphen.hyphenator class.\n" ; static PyTypeObject HyDict_type = { PyObject_HEAD_INIT(NULL) 0, /*ob_size*/ "hyphenator_", /*tp_name*/ sizeof(HyDictobject), /*tp_basicsize*/ 0, /*tp_itemsize*/ /* methods */ (destructor)HyDict_dealloc, /*tp_dealloc*/ (printfunc)0, /*tp_print*/ 0, /*tp_getattr*/ (setattrfunc)0, /*tp_setattr*/ (cmpfunc)0, /*tp_compare*/ (reprfunc)0, /*tp_repr*/ 0, /*tp_as_number*/ 0, /*tp_as_sequence*/ 0, /*tp_as_mapping*/ (hashfunc)0, /*tp_hash*/ (ternaryfunc)0, /*tp_call*/ (reprfunc)0, /*tp_str*/ 0, /*tp_getattro*/ 0, /*tp_setattro*/ 0, /*tp_as_buffer*/ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /*tp_flags*/ HyDict_type__doc__, /* Documentation string */ 0, /* tp_traverse */ 0, /* tp_clear */ 0, /* tp_richcompare */ 0, /* tp_weaklistoffset */ 0, /* tp_iter */ 0, /* tp_iternext */ HyDict_methods, /* tp_methods */ 0, /* tp_members */ 0, /* tp_getset */ 0, /* tp_base */ 0, /* tp_dict */ 0, /* tp_descr_get */ 0, /* tp_descr_set */ 0, /* tp_dictoffset */ (initproc)HyDict_init, /* tp_init */ 0, /* tp_alloc */ 0, /* tp_new */ }; /* End of code for hyphenator_ objects */ /* -------------------------------------------------------- */ /* List of methods defined in the module */ static struct PyMethodDef hnj_methods[] = { {NULL, (PyCFunction)NULL, 0, NULL} /* sentinel */ }; static char hnj_module_documentation[] = "This C extension module is a wrapper around the hyphenation library 'hyphen-2.4' (2008-05).\n\ It should normally be imported and invoked only by the convenience interface provided\n\ by the hyphen.hyphenator class.\n" ; PyMODINIT_FUNC inithnj(void) { PyObject *m, *d; HyDict_type.tp_new = PyType_GenericNew; if (PyType_Ready(&HyDict_type) < 0) return; /* Create the module and add the functions */ m = Py_InitModule3("hnj", hnj_methods, hnj_module_documentation); if (m == NULL) return; /* Add some symbolic constants to the module */ d = PyModule_GetDict(m); ErrorObject = PyString_FromString("hnj.error"); PyDict_SetItemString(d, "error", ErrorObject); Py_INCREF(&HyDict_type); PyModule_AddObject(m, "hyphenator_", (PyObject *)&HyDict_type); /* Check for errors */ if (PyErr_Occurred()) Py_FatalError("cannot initialize module hnj."); } ./PyHyphen-1.0beta1/src/hyphen.c0000666000175000017500000007745511474442376015752 0ustar takakitakaki/* Libhnj is dual licensed under LGPL and MPL. Boilerplate for both * licenses follows. */ /* LibHnj - a library for high quality hyphenation and justification * Copyright (C) 1998 Raph Levien, * (C) 2001 ALTLinux, Moscow (http://www.alt-linux.org), * (C) 2001 Peter Novodvorsky (nidd@cs.msu.su) * (C) 2006, 2007, 2008, 2010 László Németh (nemeth at OOo) * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Library General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Library General Public License for more details. * * You should have received a copy of the GNU Library General Public * License along with this library; if not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * Boston, MA 02111-1307 USA. */ /* * The contents of this file are subject to the Mozilla Public License * Version 1.0 (the "MPL"); you may not use this file except in * compliance with the MPL. You may obtain a copy of the MPL at * http://www.mozilla.org/MPL/ * * Software distributed under the MPL is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the MPL * for the specific language governing rights and limitations under the * MPL. * */ #include /* for NULL, malloc */ #include /* for fprintf */ #include /* for strdup */ #ifdef UNX #include /* for exit */ #endif #define noVERBOSE /* calculate hyphenmin values with long ligature length (2 or 3 characters * instead of 1 or 2) for comparison with hyphenation without ligatures */ #define noLONG_LIGATURE #ifdef LONG_LIGATURE #define LIG_xx 1 #define LIG_xxx 2 #else #define LIG_xx 0 #define LIG_xxx 1 #endif #include "hnjalloc.h" #include "hyphen.h" static char * hnj_strdup (const char *s) { char *new; int l; l = strlen (s); new = hnj_malloc (l + 1); memcpy (new, s, l); new[l] = 0; return new; } /* remove cross-platform text line end characters */ void hnj_strchomp(char * s) { int k = strlen(s); if ((k > 0) && ((*(s+k-1)=='\r') || (*(s+k-1)=='\n'))) *(s+k-1) = '\0'; if ((k > 1) && (*(s+k-2) == '\r')) *(s+k-2) = '\0'; } /* a little bit of a hash table implementation. This simply maps strings to state numbers */ typedef struct _HashTab HashTab; typedef struct _HashEntry HashEntry; /* A cheap, but effective, hack. */ #define HASH_SIZE 31627 struct _HashTab { HashEntry *entries[HASH_SIZE]; }; struct _HashEntry { HashEntry *next; char *key; int val; }; /* a char* hash function from ASU - adapted from Gtk+ */ static unsigned int hnj_string_hash (const char *s) { const char *p; unsigned int h=0, g; for(p = s; *p != '\0'; p += 1) { h = ( h << 4 ) + *p; if ( ( g = h & 0xf0000000 ) ) { h = h ^ (g >> 24); h = h ^ g; } } return h /* % M */; } static HashTab * hnj_hash_new (void) { HashTab *hashtab; int i; hashtab = hnj_malloc (sizeof(HashTab)); for (i = 0; i < HASH_SIZE; i++) hashtab->entries[i] = NULL; return hashtab; } static void hnj_hash_free (HashTab *hashtab) { int i; HashEntry *e, *next; for (i = 0; i < HASH_SIZE; i++) for (e = hashtab->entries[i]; e; e = next) { next = e->next; hnj_free (e->key); hnj_free (e); } hnj_free (hashtab); } /* assumes that key is not already present! */ static void hnj_hash_insert (HashTab *hashtab, const char *key, int val) { int i; HashEntry *e; i = hnj_string_hash (key) % HASH_SIZE; e = hnj_malloc (sizeof(HashEntry)); e->next = hashtab->entries[i]; e->key = hnj_strdup (key); e->val = val; hashtab->entries[i] = e; } /* return val if found, otherwise -1 */ static int hnj_hash_lookup (HashTab *hashtab, const char *key) { int i; HashEntry *e; i = hnj_string_hash (key) % HASH_SIZE; for (e = hashtab->entries[i]; e; e = e->next) if (!strcmp (key, e->key)) return e->val; return -1; } /* Get the state number, allocating a new state if necessary. */ static int hnj_get_state (HyphenDict *dict, HashTab *hashtab, const char *string) { int state_num; state_num = hnj_hash_lookup (hashtab, string); if (state_num >= 0) return state_num; hnj_hash_insert (hashtab, string, dict->num_states); /* predicate is true if dict->num_states is a power of two */ if (!(dict->num_states & (dict->num_states - 1))) { dict->states = hnj_realloc (dict->states, (dict->num_states << 1) * sizeof(HyphenState)); } dict->states[dict->num_states].match = NULL; dict->states[dict->num_states].repl = NULL; dict->states[dict->num_states].fallback_state = -1; dict->states[dict->num_states].num_trans = 0; dict->states[dict->num_states].trans = NULL; return dict->num_states++; } /* add a transition from state1 to state2 through ch - assumes that the transition does not already exist */ static void hnj_add_trans (HyphenDict *dict, int state1, int state2, char ch) { int num_trans; num_trans = dict->states[state1].num_trans; if (num_trans == 0) { dict->states[state1].trans = hnj_malloc (sizeof(HyphenTrans)); } else if (!(num_trans & (num_trans - 1))) { dict->states[state1].trans = hnj_realloc (dict->states[state1].trans, (num_trans << 1) * sizeof(HyphenTrans)); } dict->states[state1].trans[num_trans].ch = ch; dict->states[state1].trans[num_trans].new_state = state2; dict->states[state1].num_trans++; } #ifdef VERBOSE HashTab *global; static char * get_state_str (int state) { int i; HashEntry *e; for (i = 0; i < HASH_SIZE; i++) for (e = global->entries[i]; e; e = e->next) if (e->val == state) return e->key; return NULL; } #endif HyphenDict * hnj_hyphen_load (const char *fn) { HyphenDict *dict[2]; HashTab *hashtab; FILE *f; char buf[MAX_CHARS]; char word[MAX_CHARS]; char pattern[MAX_CHARS]; char * repl; signed char replindex; signed char replcut; int state_num = 0, last_state; int i, j, k; char ch; int found; HashEntry *e; int nextlevel = 0; f = fopen (fn, "r"); if (f == NULL) return NULL; // loading one or two dictionaries (separated by NEXTLEVEL keyword) for (k = 0; k == 0 || (k == 1 && nextlevel); k++) { hashtab = hnj_hash_new (); #ifdef VERBOSE global = hashtab; #endif hnj_hash_insert (hashtab, "", 0); dict[k] = hnj_malloc (sizeof(HyphenDict)); dict[k]->num_states = 1; dict[k]->states = hnj_malloc (sizeof(HyphenState)); dict[k]->states[0].match = NULL; dict[k]->states[0].repl = NULL; dict[k]->states[0].fallback_state = -1; dict[k]->states[0].num_trans = 0; dict[k]->states[0].trans = NULL; dict[k]->nextlevel = NULL; dict[k]->lhmin = 0; dict[k]->rhmin = 0; dict[k]->clhmin = 0; dict[k]->crhmin = 0; dict[k]->nohyphen = NULL; dict[k]->nohyphenl = 0; /* read in character set info */ if (k == 0) { for (i=0;icset[i]= 0; if (fgets(dict[k]->cset, sizeof(dict[k]->cset),f) != NULL) { for (i=0;icset[i] == '\r') || (dict[k]->cset[i] == '\n')) dict[k]->cset[i] = 0; } else { dict[k]->cset[0] = 0; } dict[k]->utf8 = (strcmp(dict[k]->cset, "UTF-8") == 0); } else { strcpy(dict[k]->cset, dict[0]->cset); dict[k]->utf8 = dict[0]->utf8; } while (fgets (buf, sizeof(buf), f) != NULL) { if (buf[0] != '%') { if (strncmp(buf, "NEXTLEVEL", 9) == 0) { nextlevel = 1; break; } else if (strncmp(buf, "LEFTHYPHENMIN", 13) == 0) { dict[k]->lhmin = atoi(buf + 13); continue; } else if (strncmp(buf, "RIGHTHYPHENMIN", 14) == 0) { dict[k]->rhmin = atoi(buf + 14); continue; } else if (strncmp(buf, "COMPOUNDLEFTHYPHENMIN", 21) == 0) { dict[k]->clhmin = atoi(buf + 21); continue; } else if (strncmp(buf, "COMPOUNDRIGHTHYPHENMIN", 22) == 0) { dict[k]->crhmin = atoi(buf + 22); continue; } else if (strncmp(buf, "NOHYPHEN", 8) == 0) { char * space = buf + 8; while (*space != '\0' && (*space == ' ' || *space == '\t')) space++; if (*buf != '\0') dict[k]->nohyphen = hnj_strdup(space); if (dict[k]->nohyphen) { char * nhe = dict[k]->nohyphen + strlen(dict[k]->nohyphen) - 1; *nhe = 0; for (nhe = nhe - 1; nhe > dict[k]->nohyphen; nhe--) { if (*nhe == ',') { dict[k]->nohyphenl++; *nhe = 0; } } } continue; } j = 0; pattern[j] = '0'; repl = strchr(buf, '/'); replindex = 0; replcut = 0; if (repl) { char * index = strchr(repl + 1, ','); *repl = '\0'; if (index) { char * index2 = strchr(index + 1, ','); *index = '\0'; if (index2) { *index2 = '\0'; replindex = (signed char) atoi(index + 1) - 1; replcut = (signed char) atoi(index2 + 1); } } else { hnj_strchomp(repl + 1); replindex = 0; replcut = (signed char) strlen(buf); } repl = hnj_strdup(repl + 1); } for (i = 0; ((buf[i] > ' ') || (buf[i] < 0)); i++) { if (buf[i] >= '0' && buf[i] <= '9') pattern[j] = buf[i]; else { word[j] = buf[i]; pattern[++j] = '0'; } } word[j] = '\0'; pattern[j + 1] = '\0'; i = 0; if (!repl) { /* Optimize away leading zeroes */ for (; pattern[i] == '0'; i++); } else { if (*word == '.') i++; /* convert UTF-8 char. positions of discretionary hyph. replacements to 8-bit */ if (dict[k]->utf8) { int pu = -1; /* unicode character position */ int ps = -1; /* unicode start position (original replindex) */ int pc = (*word == '.') ? 1: 0; /* 8-bit character position */ for (; pc < (strlen(word) + 1); pc++) { /* beginning of an UTF-8 character (not '10' start bits) */ if ((((unsigned char) word[pc]) >> 6) != 2) pu++; if ((ps < 0) && (replindex == pu)) { ps = replindex; replindex = (signed char) pc; } if ((ps >= 0) && ((pu - ps) == replcut)) { replcut = (signed char) (pc - replindex); break; } } if (*word == '.') replindex--; } } #ifdef VERBOSE printf ("word %s pattern %s, j = %d repl: %s\n", word, pattern + i, j, repl); #endif found = hnj_hash_lookup (hashtab, word); state_num = hnj_get_state (dict[k], hashtab, word); dict[k]->states[state_num].match = hnj_strdup (pattern + i); dict[k]->states[state_num].repl = repl; dict[k]->states[state_num].replindex = replindex; if (!replcut) { dict[k]->states[state_num].replcut = (signed char) strlen(word); } else { dict[k]->states[state_num].replcut = replcut; } /* now, put in the prefix transitions */ for (; found < 0 ;j--) { last_state = state_num; ch = word[j - 1]; word[j - 1] = '\0'; found = hnj_hash_lookup (hashtab, word); state_num = hnj_get_state (dict[k], hashtab, word); hnj_add_trans (dict[k], state_num, last_state, ch); } } } /* Could do unioning of matches here (instead of the preprocessor script). If we did, the pseudocode would look something like this: foreach state in the hash table foreach i = [1..length(state) - 1] state to check is substr (state, i) look it up if found, and if there is a match, union the match in. It's also possible to avoid the quadratic blowup by doing the search in order of increasing state string sizes - then you can break the loop after finding the first match. This step should be optional in any case - if there is a preprocessed rule table, it's always faster to use that. */ /* put in the fallback states */ for (i = 0; i < HASH_SIZE; i++) for (e = hashtab->entries[i]; e; e = e->next) { if (*(e->key)) for (j = 1; 1; j++) { state_num = hnj_hash_lookup (hashtab, e->key + j); if (state_num >= 0) break; } /* KBH: FIXME state 0 fallback_state should always be -1? */ if (e->val) dict[k]->states[e->val].fallback_state = state_num; } #ifdef VERBOSE for (i = 0; i < HASH_SIZE; i++) for (e = hashtab->entries[i]; e; e = e->next) { printf ("%d string %s state %d, fallback=%d\n", i, e->key, e->val, dict[k]->states[e->val].fallback_state); for (j = 0; j < dict[k]->states[e->val].num_trans; j++) printf (" %c->%d\n", dict[k]->states[e->val].trans[j].ch, dict[k]->states[e->val].trans[j].new_state); } #endif #ifndef VERBOSE hnj_hash_free (hashtab); #endif state_num = 0; } fclose(f); if (k == 2) dict[0]->nextlevel = dict[1]; return dict[0]; } void hnj_hyphen_free (HyphenDict *dict) { int state_num; HyphenState *hstate; for (state_num = 0; state_num < dict->num_states; state_num++) { hstate = &dict->states[state_num]; if (hstate->match) hnj_free (hstate->match); if (hstate->repl) hnj_free (hstate->repl); if (hstate->trans) hnj_free (hstate->trans); } if (dict->nextlevel) hnj_hyphen_free(dict->nextlevel); if (dict->nohyphen) hnj_free(dict->nohyphen); hnj_free (dict->states); hnj_free (dict); } #define MAX_WORD 256 int hnj_hyphen_hyphenate (HyphenDict *dict, const char *word, int word_size, char *hyphens) { char prep_word_buf[MAX_WORD]; char *prep_word; int i, j, k; int state; char ch; HyphenState *hstate; char *match; int offset; if (word_size + 3 < MAX_WORD) prep_word = prep_word_buf; else prep_word = hnj_malloc (word_size + 3); j = 0; prep_word[j++] = '.'; for (i = 0; i < word_size; i++) prep_word[j++] = word[i]; prep_word[j++] = '.'; prep_word[j] = '\0'; for (i = 0; i < word_size + 5; i++) hyphens[i] = '0'; #ifdef VERBOSE printf ("prep_word = %s\n", prep_word); #endif /* now, run the finite state machine */ state = 0; for (i = 0; i < j; i++) { ch = prep_word[i]; for (;;) { if (state == -1) { /* return 1; */ /* KBH: FIXME shouldn't this be as follows? */ state = 0; goto try_next_letter; } #ifdef VERBOSE char *state_str; state_str = get_state_str (state); for (k = 0; k < i - strlen (state_str); k++) putchar (' '); printf ("%s", state_str); #endif hstate = &dict->states[state]; for (k = 0; k < hstate->num_trans; k++) if (hstate->trans[k].ch == ch) { state = hstate->trans[k].new_state; goto found_state; } state = hstate->fallback_state; #ifdef VERBOSE printf (" falling back, fallback_state %d\n", state); #endif } found_state: #ifdef VERBOSE printf ("found state %d\n",state); #endif /* Additional optimization is possible here - especially, elimination of trailing zeroes from the match. Leading zeroes have already been optimized. */ match = dict->states[state].match; /* replacing rules not handled by hyphen_hyphenate() */ if (match && !dict->states[state].repl) { offset = i + 1 - strlen (match); #ifdef VERBOSE for (k = 0; k < offset; k++) putchar (' '); printf ("%s\n", match); #endif /* This is a linear search because I tried a binary search and found it to be just a teeny bit slower. */ for (k = 0; match[k]; k++) if (hyphens[offset + k] < match[k]) hyphens[offset + k] = match[k]; } /* KBH: we need this to make sure we keep looking in a word */ /* for patterns even if the current character is not known in state 0 */ /* since patterns for hyphenation may occur anywhere in the word */ try_next_letter: ; } #ifdef VERBOSE for (i = 0; i < j; i++) putchar (hyphens[i]); putchar ('\n'); #endif for (i = 0; i < j - 4; i++) #if 0 if (hyphens[i + 1] & 1) hyphens[i] = '-'; #else hyphens[i] = hyphens[i + 1]; #endif hyphens[0] = '0'; for (; i < word_size; i++) hyphens[i] = '0'; hyphens[word_size] = '\0'; if (prep_word != prep_word_buf) hnj_free (prep_word); return 0; } /* Unicode ligature length */ int hnj_ligature(unsigned char c) { switch (c) { case 0x80: /* ff */ case 0x81: /* fi */ case 0x82: return LIG_xx; /* fl */ case 0x83: /* ffi */ case 0x84: return LIG_xxx; /* ffl */ case 0x85: /* long st */ case 0x86: return LIG_xx; /* st */ } return 0; } /* character length of the first n byte of the input word */ int hnj_hyphen_strnlen(const char * word, int n, int utf8) { int i = 0; int j = 0; while (j < n && word[j] != '\0') { i++; // Unicode ligature support if (utf8 && ((unsigned char) word[j] == 0xEF) && ((unsigned char) word[j + 1] == 0xAC)) { i += hnj_ligature(word[j + 2]); } for (j++; utf8 && (word[j] & 0xc0) == 0x80; j++); } return i; } int hnj_hyphen_lhmin(int utf8, const char *word, int word_size, char * hyphens, char *** rep, int ** pos, int ** cut, int lhmin) { int i = 1, j; // Unicode ligature support if (utf8 && ((unsigned char) word[0] == 0xEF) && ((unsigned char) word[1] == 0xAC)) { i += hnj_ligature(word[2]); } for (j = 0; i < lhmin && word[j] != '\0'; i++) do { // check length of the non-standard part if (*rep && *pos && *cut && (*rep)[j]) { char * rh = strchr((*rep)[j], '='); if (rh && (hnj_hyphen_strnlen(word, j - (*pos)[j] + 1, utf8) + hnj_hyphen_strnlen((*rep)[j], rh - (*rep)[j], utf8)) < lhmin) { free((*rep)[j]); (*rep)[j] = NULL; hyphens[j] = '0'; } } else { hyphens[j] = '0'; } j++; // Unicode ligature support if (utf8 && ((unsigned char) word[j] == 0xEF) && ((unsigned char) word[j + 1] == 0xAC)) { i += hnj_ligature(word[j + 2]); } } while (utf8 && (word[j] & 0xc0) == 0x80); return 0; } int hnj_hyphen_rhmin(int utf8, const char *word, int word_size, char * hyphens, char *** rep, int ** pos, int ** cut, int rhmin) { int i; int j = word_size - 2; for (i = 1; i < rhmin && j > 0; j--) { // check length of the non-standard part if (*rep && *pos && *cut && (*rep)[j]) { char * rh = strchr((*rep)[j], '='); if (rh && (hnj_hyphen_strnlen(word + j - (*pos)[j] + (*cut)[j] + 1, 100, utf8) + hnj_hyphen_strnlen(rh + 1, strlen(rh + 1), utf8)) < rhmin) { free((*rep)[j]); (*rep)[j] = NULL; hyphens[j] = '0'; } } else { hyphens[j] = '0'; } if (!utf8 || (word[j] & 0xc0) != 0xc0) i++; } return 0; } // recursive function for compound level hyphenation int hnj_hyphen_hyph_(HyphenDict *dict, const char *word, int word_size, char * hyphens, char *** rep, int ** pos, int ** cut, int clhmin, int crhmin, int lend, int rend) { char prep_word_buf[MAX_WORD]; char *prep_word; int i, j, k; int state; char ch; HyphenState *hstate; char *match; char *repl; signed char replindex; signed char replcut; int offset; int matchlen_buf[MAX_CHARS]; int matchindex_buf[MAX_CHARS]; char * matchrepl_buf[MAX_CHARS]; int * matchlen; int * matchindex; char ** matchrepl; int isrepl = 0; int nHyphCount; if (word_size + 3 < MAX_CHARS) { prep_word = prep_word_buf; matchlen = matchlen_buf; matchindex = matchindex_buf; matchrepl = matchrepl_buf; } else { prep_word = hnj_malloc (word_size + 3); matchlen = hnj_malloc ((word_size + 3) * sizeof(int)); matchindex = hnj_malloc ((word_size + 3) * sizeof(int)); matchrepl = hnj_malloc ((word_size + 3) * sizeof(char *)); } j = 0; prep_word[j++] = '.'; for (i = 0; i < word_size; i++) prep_word[j++] = word[i]; prep_word[j++] = '.'; prep_word[j] = '\0'; for (i = 0; i < j; i++) hyphens[i] = '0'; #ifdef VERBOSE printf ("prep_word = %s\n", prep_word); #endif /* now, run the finite state machine */ state = 0; for (i = 0; i < j; i++) { ch = prep_word[i]; for (;;) { if (state == -1) { /* return 1; */ /* KBH: FIXME shouldn't this be as follows? */ state = 0; goto try_next_letter; } #ifdef VERBOSE char *state_str; state_str = get_state_str (state); for (k = 0; k < i - strlen (state_str); k++) putchar (' '); printf ("%s", state_str); #endif hstate = &dict->states[state]; for (k = 0; k < hstate->num_trans; k++) if (hstate->trans[k].ch == ch) { state = hstate->trans[k].new_state; goto found_state; } state = hstate->fallback_state; #ifdef VERBOSE printf (" falling back, fallback_state %d\n", state); #endif } found_state: #ifdef VERBOSE printf ("found state %d\n",state); #endif /* Additional optimization is possible here - especially, elimination of trailing zeroes from the match. Leading zeroes have already been optimized. */ match = dict->states[state].match; repl = dict->states[state].repl; replindex = dict->states[state].replindex; replcut = dict->states[state].replcut; /* replacing rules not handled by hyphen_hyphenate() */ if (match) { offset = i + 1 - strlen (match); #ifdef VERBOSE for (k = 0; k < offset; k++) putchar (' '); printf ("%s (%s)\n", match, repl); #endif if (repl) { if (!isrepl) for(; isrepl < word_size; isrepl++) { matchrepl[isrepl] = NULL; matchindex[isrepl] = -1; } matchlen[offset + replindex] = replcut; } /* This is a linear search because I tried a binary search and found it to be just a teeny bit slower. */ for (k = 0; match[k]; k++) { if ((hyphens[offset + k] < match[k])) { hyphens[offset + k] = match[k]; if (match[k]&1) { matchrepl[offset + k] = repl; if (repl && (k >= replindex) && (k <= replindex + replcut)) { matchindex[offset + replindex] = offset + k; } } } } } /* KBH: we need this to make sure we keep looking in a word */ /* for patterns even if the current character is not known in state 0 */ /* since patterns for hyphenation may occur anywhere in the word */ try_next_letter: ; } #ifdef VERBOSE for (i = 0; i < j; i++) putchar (hyphens[i]); putchar ('\n'); #endif for (i = 0; i < j - 3; i++) #if 0 if (hyphens[i + 1] & 1) hyphens[i] = '-'; #else hyphens[i] = hyphens[i + 1]; #endif for (; i < word_size; i++) hyphens[i] = '0'; hyphens[word_size] = '\0'; /* now create a new char string showing hyphenation positions */ /* count the hyphens and allocate space for the new hyphenated string */ nHyphCount = 0; for (i = 0; i < word_size; i++) if (hyphens[i]&1) nHyphCount++; j = 0; for (i = 0; i < word_size; i++) { if (isrepl && (matchindex[i] >= 0) && matchrepl[matchindex[i]]) { if (rep && pos && cut) { if (!*rep && !*pos && !*cut) { int k; *rep = (char **) malloc(sizeof(char *) * word_size); *pos = (int *) malloc(sizeof(int) * word_size); *cut = (int *) malloc(sizeof(int) * word_size); for (k = 0; k < word_size; k++) { (*rep)[k] = NULL; (*pos)[k] = 0; (*cut)[k] = 0; } } (*rep)[matchindex[i] - 1] = hnj_strdup(matchrepl[matchindex[i]]); (*pos)[matchindex[i] - 1] = matchindex[i] - i; (*cut)[matchindex[i] - 1] = matchlen[i]; } j += strlen(matchrepl[matchindex[i]]); i += matchlen[i] - 1; } } if (matchrepl != matchrepl_buf) { hnj_free (matchrepl); hnj_free (matchlen); hnj_free (matchindex); } // recursive hyphenation of the first (compound) level segments if (dict->nextlevel) { char * rep2_buf[MAX_WORD]; int pos2_buf[MAX_WORD]; int cut2_buf[MAX_WORD]; char hyphens2_buf[MAX_WORD]; char ** rep2; int * pos2; int * cut2; char * hyphens2; int begin = 0; if (word_size < MAX_CHARS) { rep2 = rep2_buf; pos2 = pos2_buf; cut2 = cut2_buf; hyphens2 = hyphens2_buf; } else { rep2 = hnj_malloc (word_size * sizeof(char *)); pos2 = hnj_malloc (word_size * sizeof(int)); cut2 = hnj_malloc (word_size * sizeof(int)); hyphens2 = hnj_malloc (word_size); } for (i = 0; i < word_size; i++) rep2[i] = NULL; for (i = 0; i < word_size; i++) if (hyphens[i]&1 || (begin > 0 && i + 1 == word_size)) { if (i - begin > 1) { int hyph = 0; prep_word[i + 2] = '\0'; /* non-standard hyphenation at compound boundary (Schiffahrt) */ if (*rep && *pos && *cut && (*rep)[i]) { char * l = strchr((*rep)[i], '='); strcpy(prep_word + 2 + i - (*pos)[i], (*rep)[i]); if (l) { hyph = (l - (*rep)[i]) - (*pos)[i]; prep_word[2 + i + hyph] = '\0'; } } hnj_hyphen_hyph_(dict, prep_word + begin + 1, i - begin + 1 + hyph, hyphens2, &rep2, &pos2, &cut2, clhmin, crhmin, (begin > 0 ? 0 : lend), (hyphens[i]&1 ? 0 : rend)); for (j = 0; j < i - begin - 1; j++) { hyphens[begin + j] = hyphens2[j]; if (rep2[j] && rep && pos && cut) { if (!*rep && !*pos && !*cut) { int k; *rep = (char **) malloc(sizeof(char *) * word_size); *pos = (int *) malloc(sizeof(int) * word_size); *cut = (int *) malloc(sizeof(int) * word_size); for (k = 0; k < word_size; k++) { (*rep)[k] = NULL; (*pos)[k] = 0; (*cut)[k] = 0; } } (*rep)[begin + j] = rep2[j]; (*pos)[begin + j] = pos2[j]; (*cut)[begin + j] = cut2[j]; } } prep_word[i + 2] = word[i + 1]; if (*rep && *pos && *cut && (*rep)[i]) { strcpy(prep_word + 1, word); } } begin = i + 1; for (j = 0; j < word_size; j++) rep2[j] = NULL; } // non-compound if (begin == 0) { hnj_hyphen_hyph_(dict->nextlevel, word, word_size, hyphens, rep, pos, cut, clhmin, crhmin, lend, rend); if (!lend) hnj_hyphen_lhmin(dict->utf8, word, word_size, hyphens, rep, pos, cut, clhmin); if (!rend) hnj_hyphen_rhmin(dict->utf8, word, word_size, hyphens, rep, pos, cut, crhmin); } if (rep2 != rep2_buf) { free(rep2); free(cut2); free(pos2); free(hyphens2); } } if (prep_word != prep_word_buf) hnj_free (prep_word); return 0; } /* UTF-8 normalization of hyphen and non-standard positions */ int hnj_hyphen_norm(const char *word, int word_size, char * hyphens, char *** rep, int ** pos, int ** cut) { int i, j, k; if ((((unsigned char) word[0]) >> 6) == 2) { fprintf(stderr, "error - bad, non UTF-8 input: %s\n", word); return 1; } /* calculate UTF-8 character positions */ for (i = 0, j = -1; i < word_size; i++) { /* beginning of an UTF-8 character (not '10' start bits) */ if ((((unsigned char) word[i]) >> 6) != 2) j++; hyphens[j] = hyphens[i]; if (rep && pos && cut && *rep && *pos && *cut) { int l = (*pos)[i]; (*pos)[j] = 0; for (k = 0; k < l; k++) { if ((((unsigned char) word[i - k]) >> 6) != 2) (*pos)[j]++; } k = i - l + 1; l = k + (*cut)[i]; (*cut)[j] = 0; for (; k < l; k++) { if ((((unsigned char) word[k]) >> 6) != 2) (*cut)[j]++; } (*rep)[j] = (*rep)[i]; if (j < i) { (*rep)[i] = NULL; (*pos)[i] = 0; (*cut)[i] = 0; } } } hyphens[j + 1] = '\0'; return 0; } /* get the word with all possible hyphenations (output: hyphword) */ void hnj_hyphen_hyphword(const char * word, int l, const char * hyphens, char * hyphword, char *** rep, int ** pos, int ** cut) { int i, j; for (i = 0, j = 0; i < l; i++, j++) { if (hyphens[i]&1) { hyphword[j] = word[i]; if (*rep && *pos && *cut && (*rep)[i]) { strcpy(hyphword + j - (*pos)[i] + 1, (*rep)[i]); j += strlen((*rep)[i]) - (*pos)[i]; i += (*cut)[i] - (*pos)[i]; } else hyphword[++j] = '='; } else hyphword[j] = word[i]; } hyphword[j] = '\0'; } /* main api function with default hyphenmin parameters */ int hnj_hyphen_hyphenate2 (HyphenDict *dict, const char *word, int word_size, char * hyphens, char *hyphword, char *** rep, int ** pos, int ** cut) { hnj_hyphen_hyph_(dict, word, word_size, hyphens, rep, pos, cut, dict->clhmin, dict->crhmin, 1, 1); hnj_hyphen_lhmin(dict->utf8, word, word_size, hyphens, rep, pos, cut, (dict->lhmin > 0 ? dict->lhmin : 2)); hnj_hyphen_rhmin(dict->utf8, word, word_size, hyphens, rep, pos, cut, (dict->rhmin > 0 ? dict->rhmin : 2)); /* nohyphen */ if (dict->nohyphen) { char * nh = dict->nohyphen; int nhi; for (nhi = 0; nhi <= dict->nohyphenl; nhi++) { char * nhy = (char *) strstr(word, nh); while (nhy) { hyphens[nhy - word + strlen(nh) - 1] = 0; hyphens[nhy - word - 1] = 0; nhy = (char *) strstr(nhy + 1, nh); } nh = nh + strlen(nh) + 1; } } if (hyphword) hnj_hyphen_hyphword(word, word_size, hyphens, hyphword, rep, pos, cut); if (dict->utf8) return hnj_hyphen_norm(word, word_size, hyphens, rep, pos, cut); return 0; } /* previous main api function with hyphenmin parameters */ int hnj_hyphen_hyphenate3 (HyphenDict *dict, const char *word, int word_size, char * hyphens, char *hyphword, char *** rep, int ** pos, int ** cut, int lhmin, int rhmin, int clhmin, int crhmin) { lhmin = (lhmin > 0 ? lhmin : dict->lhmin); rhmin = (rhmin > 0 ? rhmin : dict->rhmin); hnj_hyphen_hyph_(dict, word, word_size, hyphens, rep, pos, cut, clhmin, crhmin, 1, 1); hnj_hyphen_lhmin(dict->utf8, word, word_size, hyphens, rep, pos, cut, (lhmin > 0 ? lhmin : 2)); hnj_hyphen_rhmin(dict->utf8, word, word_size, hyphens, rep, pos, cut, (rhmin > 0 ? rhmin : 2)); if (hyphword) hnj_hyphen_hyphword(word, word_size, hyphens, hyphword, rep, pos, cut); /* nohyphen */ if (dict->nohyphen) { char * nh = dict->nohyphen; int nhi; for (nhi = 0; nhi <= dict->nohyphenl; nhi++) { char * nhy = (char *) strstr(word, nh); while (nhy) { hyphens[nhy - word + strlen(nh) - 1] = 0; hyphens[nhy - word - 1] = 0; nhy = (char *) strstr(nhy + 1, nh); } nh = nh + strlen(nh) + 1; } } if (dict->utf8) return hnj_hyphen_norm(word, word_size, hyphens, rep, pos, cut); return 0; } ./PyHyphen-1.0beta1/src/hnjalloc.c0000666000175000017500000000341110763742660016225 0ustar takakitakaki/* LibHnj is dual licensed under LGPL and MPL. Boilerplate for both * licenses follows. */ /* LibHnj - a library for high quality hyphenation and justification * Copyright (C) 1998 Raph Levien, (C) 2001 ALTLinux, Moscow * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Library General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Library General Public License for more details. * * You should have received a copy of the GNU Library General Public * License along with this library; if not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * Boston, MA 02111-1307 USA. */ /* * The contents of this file are subject to the Mozilla Public License * Version 1.0 (the "MPL"); you may not use this file except in * compliance with the MPL. You may obtain a copy of the MPL at * http://www.mozilla.org/MPL/ * * Software distributed under the MPL is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the MPL * for the specific language governing rights and limitations under the * MPL. * */ /* wrappers for malloc */ #include "Python.h" void * hnj_malloc (int size) { void *p; p = PyMem_Malloc (size); if (p == NULL) PyErr_NoMemory(); return p; } void * hnj_realloc (void *p, int size) { void* p2; p2 = PyMem_Realloc (p, size); if (p2 == NULL) PyErr_NoMemory(); return p2; } void hnj_free (void *p) { PyMem_Free(p); } ./PyHyphen-1.0beta1/setup.py0000666000175000017500000001224011546021004015170 0ustar takakitakaki import sys, os, shutil, codecs, locale from string import Template from distutils.core import setup, Extension # URL of the default repository. It goes into config.py. # Change this if you want to download dictionaries from somewhere else by default. # Note that you can also specify the repository individualy # when calling hyphen.dictools.install. default_repo = 'http://ftp.services.openoffice.org/pub/OpenOffice.org/contrib/dictionaries/' # Copy version-specific files files = {'__init__.py' : 'hyphen/', 'dictools.py' : 'hyphen/', 'config.py' : 'hyphen/', 'hnjmodule.c' : 'src/', 'textwrap2.py' : './'} # create package directory: if not os.path.exists('hyphen'): os.mkdir('hyphen') #copy version-specific files ver = sys.version[0] py3k = (ver == '3') for file_name, dest in files.items(): shutil.copy(ver + '.x/' + file_name, dest + file_name) longdescr = open('README.txt').read() arg_dict = dict( name = "PyHyphen", version = "1.0beta1", author = "Dr. Leo", author_email = "fhaxbox66@googlemail.com", url = "http://pyhyphen.googlecode.com", description = "The hyphenation library of OpenOffice and FireFox wrapped for Python", long_description = longdescr, classifiers = [ 'Intended Audience :: Developers', 'Development Status :: 4 - Beta', 'License :: OSI Approved', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Programming Language :: C', 'Topic :: Text Processing', 'Topic :: Text Processing :: Linguistic' ], packages = ['hyphen'], ext_modules = [ Extension('hyphen.hnj', ['src/hnjmodule.c', 'src/hyphen.c', 'src/hnjalloc.c' ], include_dirs = ['include'])], py_modules = ['textwrap2'], provides = ['hyphen', 'textwrap2'] ) # Check for a binary shipping with this distribution and use it instead of compiling # the C sources, unless --force_build_ext is given. if len(set(('install', 'bdist_wininst', 'bdist')) - set(sys.argv)) < 3: if '--force_build_ext' in sys.argv: sys.argv.remove('--force_build_ext') else: bin_file = ''.join(('bin/hnj', '.', sys.platform, '-', sys.version[:3], '.pyd')) if os.path.exists(bin_file): shutil.copy(bin_file, './hyphen/hnj.pyd') arg_dict['package_data'] = {'hyphen' : ['hnj.pyd']} arg_dict.pop('ext_modules') sys.stdout.write("Found a suitable binary version of the C extension module. This binary will be installed rather than building it from source.\n\ However, if you prefer compiling, reenter 'python setup.py --force_build_ext'.") setup(**arg_dict) # clean up shutil.rmtree('hyphen') # it would disturb the following import of hyphen os.remove('textwrap2.py') os.remove('src/hnjmodule.c') # Configure the path for dictionaries in config.py if 'install' in sys.argv: sys.stdout.write("Adjusting /.../hyphen/config.py... ") # We catch ImportErrors to handle situations where the # hyphen package has been # installed in a directory that is not listed in # sys.path. This occurs, e.g., # when creating a Debian package. try: import hyphen mod_path = hyphen.__path__[0] + '/config.py' content = codecs.open(mod_path, 'r', 'utf8').read() new_content = Template(content).substitute(path = hyphen.__path__[0], repo = default_repo) # Remove config.pyc to make sure the modified .py file is byte-compiled # when re-importing. Otherwise the new config.py might have # the same time stamp as the old one os.remove(mod_path + 'c') # Write the new config.py codecs.open(mod_path, 'w', 'utf8').write(new_content) sys.stdout.write("Done.\n") # Install dictionaries if '--no_dictionaries' not in sys.argv: # install dict_info and dictionaries if py3k: from imp import reload reload(hyphen.config) reload(hyphen) from hyphen.dictools import install, install_dict_info sys.stdout.write('Installing dictionary info...') hyphen.dict_info = install_dict_info() sys.stdout.write(' Done.\n') sys.stdout.write('Installing dictionaries... en_US ') install('en_US') # Install dict for local language if needed locale.setlocale(locale.LC_ALL, '') local_lang = locale.getlocale()[0] if local_lang != 'en_US': if local_lang in hyphen.dict_info: sys.stdout.write(local_lang + ' ') install(local_lang) sys.stdout.write('Done.\n') else: sys.stdout.write('(No dictionary for local language found)\n') except ImportError: sys.stderr.write("""Warning: Could not import hyphen package. You may wish to adjust config.py manually or run setup.py with different options. No dictionary has been installed.\n""") ./PyHyphen-1.0beta1/MANIFEST0000666000175000017500000000060611546030414014617 0ustar takakitakakiLICENSE.txt MANIFEST README.txt setup.py 2.x\__init__.py 2.x\config.py 2.x\dictools.py 2.x\hnjmodule.c 2.x\textwrap2.py 3.x\__init__.py 3.x\config.py 3.x\dictools.py 3.x\hnjmodule.c 3.x\textwrap2.py bin\hnj.win32-2.6.pyd bin\hnj.win32-2.7.pyd bin\hnj.win32-3.1.pyd bin\hnj.win32-3.2.pyd include\hnjalloc.h include\hyphen.h src\hnjalloc.c src\hnjmodule.c src\hyphen.c ./PyHyphen-1.0beta1/README.txt0000666000175000017500000002667311546030224015177 0ustar takakitakaki================================= PyHyphen - hyphenation for Python ================================= (c) 2008-2011 Dr. Leo Contact: fhaxbox66@googlemail.com Project home: http://pyhyphen.googlecode.com Mailing list: http://groups.google.com/group/pyhyphen .. contents:: Change log ====================== New in version 1.0 * Upgraded the C library libhyphen to v2.7 which brings significant improvements, most notably correct treatment of * already hyphenated words such as 'Python-powered' * use a CSV file from the oo website with meta information on dictionaries for installation of dictionaries and instantiation of hyphenators. Apps can access the metadata on all downloadable dicts through the new module-level attribute hyphen.dict_info or for each hyphenator through the 'info' attribute, * Hyphenator objects have a 'info' attribute which is a Python dictionary with meta information on the hyphenation dictionary. The 'language' attribute is deprecated. *Note:* These new features add complexity to the installation process as the metadata and dictionary files are downloaded at install time. These features have to be tested in various environments before declaring the package stable. * Streamlined the installation process * The en_US hyphenation dictionary has been removed from the package. Instead, the dictionaries for en_US and the local language are automatically downloaded at install time. * restructured the package and merged 2.x and 3.x setup files * switch from svn to hg * added win32 binary of the C extension module for Python32, currently no binaries for Python 2.4 and 2.5 New in version 0.10 * added win32 binary for Python 2.7 * renamed 'hyphenator' class to to more conventional 'Hyphenator'. 'hyphenator' is deprecated. New in version 0.9.3: * added win32 binary of the C extension for Python 3.1 * added 'syllables' method to the hyphenator (can yield inconsistent results in languages with non-standard hyphenation) New in version 0.9.2 * make it compile with Python 3.0.1 * add win32 binary of the C extension for Python 3.0 New in version 0.9.1 * full support for Python 3.0 * merged 3.0 sources with the 2.x distribution. New in Version 0.9: * removed the 'inserted' method from the hyphenator class as it is not used in practice the word to be hyphenated must now be unicode (utf-8 encoded strings raise TypeError). The restriction to unicode is safer and more 3.0-compliant. * fixed important bug in 'pairs' method that could cause a unicode error if 'word' was not encodable to the dictionary's encoding. In the latter case, the new version returns an empty list (consistent with other cases where the word is not hyphenable). * the configuration script has been simplified and improved: it does not raise ImportError even if the package cannot be imported. This tolerance is needed to create a Debian package. New in Version 0.8 - supports Python 2.x and 3.0 (in 2 separate distributions)) - contains the new C library hyphen-2.4 which implements an extended algorithm supporting: - compound words (dictionaries are under development in the OpenOffice community)) - parameters to fix the minimal number of characters to be cut off by hyphenation (lmin, rmin, compound_lmin and compound_rmin). ) This may require code changes in existing apps. - new en_US dictionary. - many minor improvements under the hood 1. Overview ================ The gole of the PyHyphen project is to provide Python with a high quality hyphenation facility. PyHyphen consists of the package 'hyphen' and the module 'textwrap2'. The source distribution supports Python 2.4 or higher, including Python 3.2. 1.1 Content of the hyphen package ------------------------------------------ The 'hyphen' module defines the following: - at top level the definition of the class 'Hyphenator' each instance of which can hyphenate and wrap words using a dictionary compatible with the hyphenation feature of OpenOffice and Mozilla. - the module dictools contains useful functions such as downloading and installing dictionaries from a configurable repository. After installation of PyHyphen, the OpenOffice repository is used by default. 'dictools.install_dict-info' downloads metadata on all available hyphenation dictionaries from the OpenOffice website and stores it in a pickled file. - hyphen.dict_info: a dict object with metadata on all hyphenation dictionaries downloadable from the OpenOffice website. - config is a configuration file initialized at install time with default values for the directory where dictionaries are searched, and the repository for downloads of dictionaries. Initial values are the package root and the OpenOffice repository for dictionaries. - hnj' is the C extension module that does all the ground work. It contains the C library libhyphen. It supports non-standard hyphenation with replacements as well as compound word hyphenation. Note that hyphenation dictionaries are invisible to the Python programmer. But each hyphenator object has an attribute 'info' which is a dict object containing metadata on the hyphenation dictionary of this Hyphenator instance. The former 'language' attribute, a string of the form 'll_CC' is deprecated as from v1.0. 1.2 The module 'textwrap2' ------------------------------ This module is an enhanced though backwards compatible version of the module 'textwrap' from the Python standard library. Not very surprisingly, it adds hyphenation functionality to 'textwrap'. To this end, a new key word parameter 'use_hyphenator' has been added to the __init__ method of the TextWrapper class which defaults to None. It can be initialized with any hyphenator object. Note that until version 0.7 this keyword parameter was named 'use_hyphens'. So older code may need to be changed.' 1.3 hyphen_test ------------------------------- (no longer part of the distribution as of version 0.9.1; please clone the hg repository to get it) This Python script is a framework for running large tests of the hyphen package. A test is a list of 3 elements: a text file (typically a word list), its encoding and a list of strings specifying a dictionary to be applied to the word list. Adding a test is as easy as writing a function call. All results are logged. 2. Code example ====================== :: >>>from hyphen import Hyphenator from hyphen.dictools import * # Download and install some dictionaries in the default directory using the default # repository, usually the OpenOffice website for lang in ['de_DE', 'fr_FR', 'en_UK', 'ru_RU']: if not is_installed(lang): install(lang) # Create some hyphenators h_de = Hyphenator('de_DE') h_en = Hyphenator('en_US') # Now hyphenate some words # Note: the following examples are written in Python 3.x syntax. # If you use Python 2.x, you must add the 'u' prefixes as Hyphenator methods expect unicode objects. h_en.pairs('beautiful' [['beau', 'tiful'], [u'beauti', 'ful']] h_en.wrap('beautiful', 6) ['beau-', 'tiful'] h_en.wrap('beautiful', 7) ['beauti-', 'ful'] h_en.syllables('beautiful') ['beau', 'ti', 'ful'] h_en.info {'file_name': 'hyph_en_US.zip', 'country_code': 'US', 'name': 'hyph_en_US', 'long_descr': 'English (United States)', 'language_code': 'en'} from textwrap2 import fill print fill('very long text...', width = 40, use_hyphens = h_en) 3. Compiling and installing ================================ 3.1 General requirements --------------------------- PyHyphen works with Python 2.4 or higher, including 3.2. There are pre-compiled binaries of the hnj module for win32 and Python 2.6 to 3.2. On other platforms you will need a build environment such as gcc, make 3.2 Compiling and installing from source ---------------------------------------------- Choose and download the source distribution from http://cheeseshop.python.org/pypi/PyHyphen and unpack it in a temporary directory. Then cd to this directory. You can compile and install the hyphen package as well as the module textwrap2 by entering at the command line somethin like: $python setup.py install The setup script will first check the Python version and copy the required version-specific files. Second, setup.py searches in ./bin for a pre-compiled binary of hnj for your platform. If there is a binary that looks ok, this version is installed. Otherwise, hnj is compiled from source. On Windows you will need MSVC 2003 (Python 2.4 and 2.5) or MSVC 2008 (for Python2.6 or higher), mingw or whatever fits to your Python distribution. If the distribution comes with a binary of 'hnj' that fits to your platform and python version, you can still force a compilation from source by entering $python setup.py install --force_build_ext Under Linux you may need root privileges, so you may want to enter something like $sudo python setup.py install After compiling and installing the hyphen package, config.py is adjusted as follows: - the package directory becomes the local default path for hyphenation dictionaries - the OpenOffice website becomes the default repository from which dictionaries are downloaded. Thereafter, the setup script tries to re-import the hyphen package to install a default set of dictionaries, unless the command line contains the 'no_dictionaries' command after 'install'. The script then tries to install the metadata file by calling hyphen.dictools.install_dict_info. Then, the hyphenation dictionaries for en_US (commonly used) and the local language, if different, are installed. 4. How to get dictionaries? ================================= Information on all hyphenation dictionaries available on the OpenOffice website is stored in hyphen.dict_info. You can also visit http://wiki.services.openoffice.org/wiki/Dictionaries for a complete list. Then use the dictools.install function to download and install the dictionary locally. 5. What's under the hood? ============================== the C extension module 'hnj' used by the hyphenator class defined in __init__.py contains the C library libhyphen which is used by OpenOffice.org, Mozilla and alike. The C sources have not been changed, let alone hnjmalloc.c which has been slightly modify to use pythonic memory management and error handling. For further information on the hyphenation library and available dictionaries visit http://wiki.services.openoffice.org/wiki/Dictionaries. 6. Testing ============== This requires cloning the hg repository, as the test.py module is no longer part of the source distribution. Please see the instructions in Demo/hyphen_test.py. All you need is a text file, and its encoding. Copy the text file into the Demo/input directory, add a new function call to hyphen_test.py, run it and read the .log file and the files created in the output directory. There you will see the results for each word. You can specify a list of dictionaries to be used. Then, hyphen_test will create an output file for each dictionary used with a given word list. 7. Contributing and reporting bugs ===================================== Contributions, comments, bug reports, criticism and praise can be sent to the author. The sources of PyHyphen are found in a Mercurial repository at http://pyhyphen.googlecode.com This is also where you can submit bug reports. ./PyHyphen-1.0beta1/2.x/0000775000175000017500000000000011546766220014104 5ustar takakitakaki./PyHyphen-1.0beta1/2.x/hnjmodule.c0000666000175000017500000003323211132636054016232 0ustar takakitakaki#include "Python.h" #include "structmember.h" #include "hyphen.h" #include "string.h" /* String constants for calls of Py_Unicode_FromEncodedObject etc.*/ static const char unicode_errors[] = "strict"; /* is raised if hnj_hyphen returns an error while trying to hyphenate a word*/ static PyObject *ErrorObject; /* ----------------------------------------------------- */ /* Declarations for objects of type hyphenator_ */ /* type object to store the hyphenation dictionary. Its only method is 'apply' which calls the core function 'hnj_hyphenate2'' from the wrapped library 'hnj_hyphen-2.3' */ typedef struct { PyObject_HEAD HyphenDict *dict; int lmin, rmin, compound_lmin, compound_rmin; } HyDictobject; static PyTypeObject HyDict_type; /* ---------------------------------------------------------------- */ static char HyDict_apply__doc__[] = "SUMMARY:\n\ apply(word: unicode object, mode: int) -> hyphenated word (return type depends on value of mode)\n\n\ Note: 'hnj' should normally be called only from the convenience interface provided by\ the hyphen.hyphenator class.\n\n\ word: must be lower-cased to be hyphenated correctly. Through the flags in mode,\n\ the caller can provide information on whether the word was originally capitalized, \n\ lower-cased or upper-cased. Capital letters are restored \n\ according to the value of 'mode'. The encoded representation of 'word'\n\ may have at most 100 bytes including the terminating '\0'.\n\ mode: the 3 least significant bits are interpreted as flags with the following meaning:\n\ - mode & 1 = 0: return a string with '=' inserted at the hyphenation points\n\ - mode & 1 = 1: return a list of lists of the form [before_hyphen, after_hyphen]\n\ - mode & 2 = 1: return a capitalized word\n\ - mode & 4 = 1: return an upper-cased word\n"; /* get a pointer to the nth 8-bit or UTF-8 character of the word */ /* This is required because some operations are done at utf8 string level. */ static char * hindex(char * word, int n, int utf8) { int j = 0; while (j < n) { j++; word++; while (utf8 && ((((unsigned char) *word) >> 6) == 2)) word++; } return word; } /* Depending on the value of 'mode', convert a utf8 C string to PyUnicode or PyString (utf8), handle also capitalization and upper case words. */ static PyObject * prepare_result(char *word, char *encoding, int mode) { Py_UNICODE * ch_u; PyObject *result; int len_s, i; /* first convert the C string to unicode. */ if (!(result = PyUnicode_Decode(word, strlen(word), encoding, unicode_errors))) return NULL; if (mode & 4) { /* capitalize entire word */ ch_u = PyUnicode_AS_UNICODE(result); len_s = PyUnicode_GetSize(result); for (i=0; i <= len_s; i++) { *ch_u = Py_UNICODE_TOUPPER(*ch_u); ch_u++; } } else { if (mode & 2) { /* capitalize first letter */ ch_u = PyUnicode_AS_UNICODE(result); *ch_u = Py_UNICODE_TOUPPER(*ch_u); } } /* return a unicode object */ return result; } /* core function of the hyphenator_ object type */ static PyObject * HyDict_apply(HyDictobject *self, PyObject *args) { const char separator[] = "="; char *hyphenated_word, *hyphens, *word_str; char ** rep = NULL; char r; int * pos = NULL; int * cut = NULL; unsigned int wd_size, hyph_count, i, j, k, mode; PyObject *result, *s1, *s2, *separator_u = NULL; /* mode: bit0 === 1: return a tuple, otherwise a word with '=' inserted at the positions of possible hyphenations. bit1 == 1: word must be capitalized before returning bit2 == 1: entire word must be uppered before returning */ /* parse and check arguments */ if (!PyArg_ParseTuple(args, "esi", &self->dict->cset, &word_str, &mode)) return NULL; wd_size = strlen(word_str); if (wd_size >= MAX_CHARS) { PyErr_SetString(PyExc_ValueError, "Word to be hyphenated may have at most 100 characters."); PyMem_Free(word_str); return NULL; } /* allocate memory for the return values of the core function hnj_hyphenate2*/ hyphens = (char *) PyMem_Malloc(wd_size + 5); hyphenated_word = (char *) PyMem_Malloc(wd_size * 3); /* now actually try the hyphenation*/ if (hnj_hyphen_hyphenate3(self->dict, word_str, wd_size, hyphens, hyphenated_word, &rep, &pos, &cut, self->lmin, self->rmin, self->compound_lmin, self->compound_rmin)) { PyMem_Free(hyphens); PyMem_Free(hyphenated_word); PyMem_Free(word_str); PyErr_SetString(ErrorObject, "Cannot hyphenate word."); return NULL; } /* Count possible hyphenations. This is done by checking bit 0 of each */ /* char of 'hyphens' which is 0 if and only if the word can be hyphened */ /* at that position. Then proceed to */ /* the real work, i.d. returning a unicode object with inserted '=' at each */ /* possible hyphenation, or return a list of lists of two unicode objects */ /* representing a possible hyphenation each. Note that the string */ /* is useful only in languages without non-standard hyphenation, as */ /* the string could contain more than one replacement, whereas */ /* we are only interested in one replacement at the hyphenation position */ /* we choose. */ /* If no hyphenations were found, a string with 0 inserted '=', i.e. the original word, */ /* or an empty list (with 0 pairs) is returned. */ hyph_count = 0; for (i=0; (i+1) < strlen(hyphens); i++) { if (hyphens[i] & 1) hyph_count++; } /* Do we need to return a string with inserted '=', or a list of pairs? */ if (!(mode & 1)) { /* Prepare for returning a unicode obj of the form 'before_hyphen=after_hyphen. */ if (!(result = prepare_result(hyphenated_word, self->dict->cset, mode))) { PyMem_Free(hyphenated_word); PyMem_Free(word_str); PyMem_Free(hyphens); return NULL; } PyMem_Free(hyphenated_word); } else { PyMem_Free(hyphenated_word); /* construct a list of lists of two unicode objects. Each inner list */ /* represents a possible hyphenation. */ /* First create the outer list. Each element will be a list of two strings or unicode objects. */ if (!(result = PyList_New(hyph_count))) { PyMem_Free(hyphens); PyMem_Free(word_str); return NULL; } /* now fill the resulting list from left to right with the pairs */ j=0; hyph_count = 0; /* The following is needed to split the word (in which an '=' indicates the */ /* hyphen position) */ separator_u = PyUnicode_Decode(separator, 1, self->dict->cset, unicode_errors); for (i = 0; (i + 1) < strlen(word_str); i++) { /* j-th character utf8? Then just increment j */ if (self->dict->utf8 && ((((unsigned char) word_str[i]) >> 6) == 2)) continue; /* Is here a hyphen? */ if ((hyphens[j] & 1)) { /* Build the hyphenated word at C string level. */ /* first, handle non-standard hyphenation with replacement. */ if (rep && rep[j]) { /* determine the position within word_str where to insert rep[j] */ /* do the replacement by appending the three substrings: */ hyphenated_word = (char *) PyMem_Malloc(strlen(word_str) + strlen(rep[j])+1); k = hindex(word_str, j - pos[j] + 1, self->dict->utf8) - word_str; r = word_str[k]; word_str[k] = 0; strcpy(hyphenated_word, word_str); strcat(hyphenated_word, rep[j]); word_str[k] = r; strcat(hyphenated_word, hindex(word_str + k, cut[j], self->dict->utf8)); } else { /* build the word in case of standard hyphenation. */ /* An '=' will be inserted so that the */ /* resulting string has the same format as in the non-standard case. */ hyphenated_word = (char *) PyMem_Malloc(strlen(word_str) + 2); k = hindex(word_str, j + 1, self->dict->utf8) - word_str; r = word_str[k]; word_str[k] = 0; strcpy(hyphenated_word, word_str); strcat(hyphenated_word, separator); word_str[k] = r; strcat(hyphenated_word, word_str + k); } /* Now prepare the resulting unicode object according to the value of mode */ if (!(s1 = prepare_result(hyphenated_word, self->dict->cset, mode))) { PyMem_Free(hyphenated_word); PyMem_Free(hyphens); PyMem_Free(word_str); return NULL; } PyMem_Free(hyphenated_word); /* split it into two parts at the position of the '=' */ /* and write the resulting list into the tuple */ if (!((s2 = PyUnicode_Split(s1, separator_u, 1)) && (!PyList_SetItem(result, hyph_count++, s2)))) { Py_XDECREF(s2); Py_DECREF(s1); PyMem_Free(hyphens); PyMem_Free(word_str); return NULL; } Py_DECREF(s1); } /* finished with current hyphen */ j++; } /* for loop*/ Py_DECREF(separator_u); } /* end of else construct a list */ PyMem_Free(hyphens); PyMem_Free(word_str); return result; } static struct PyMethodDef HyDict_methods[] = { {"apply", (PyCFunction)HyDict_apply, METH_VARARGS, HyDict_apply__doc__}, {NULL, NULL} /* sentinel */ }; /* ---------- */ static void HyDict_dealloc(HyDictobject *self) { if (self->dict) hnj_hyphen_free(self->dict); self->ob_type->tp_free((PyObject*) self); } static int HyDict_init(HyDictobject *self, PyObject *args) { char* fn; if (!PyArg_ParseTuple(args, "siiii", &fn, &self->lmin, &self->rmin, &self->compound_lmin, &self->compound_rmin)) return -1; if (!(self->dict = hnj_hyphen_load(fn))) { if (!PyErr_Occurred()) PyErr_SetString(PyExc_IOError, "Cannot load hyphen dictionary."); return -1; } return 0; } static char HyDict_type__doc__[] = "Wrapper class for the hnj_hyphen library contained in this module.\n\n\ Usage: hyphenator_(dict_file_name: string, lmin, rmin, compound_lmin, compound_rmin: integer)\n\ The init method will try to load a hyphenation dictionary with the filename passed.\n\ If an error occurs when trying to load the dictionary, IOError is raised.\n\ Dictionary files compatible with hnj can be downloaded at the OpenOffice website.\n\n\ This class should normally be instantiated only by the convenience interface provided by\n\ the hyphen.hyphenator class.\n" ; static PyTypeObject HyDict_type = { PyObject_HEAD_INIT(NULL) 0, /*ob_size*/ "hyphenator_", /*tp_name*/ sizeof(HyDictobject), /*tp_basicsize*/ 0, /*tp_itemsize*/ /* methods */ (destructor)HyDict_dealloc, /*tp_dealloc*/ (printfunc)0, /*tp_print*/ 0, /*tp_getattr*/ (setattrfunc)0, /*tp_setattr*/ (cmpfunc)0, /*tp_compare*/ (reprfunc)0, /*tp_repr*/ 0, /*tp_as_number*/ 0, /*tp_as_sequence*/ 0, /*tp_as_mapping*/ (hashfunc)0, /*tp_hash*/ (ternaryfunc)0, /*tp_call*/ (reprfunc)0, /*tp_str*/ 0, /*tp_getattro*/ 0, /*tp_setattro*/ 0, /*tp_as_buffer*/ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /*tp_flags*/ HyDict_type__doc__, /* Documentation string */ 0, /* tp_traverse */ 0, /* tp_clear */ 0, /* tp_richcompare */ 0, /* tp_weaklistoffset */ 0, /* tp_iter */ 0, /* tp_iternext */ HyDict_methods, /* tp_methods */ 0, /* tp_members */ 0, /* tp_getset */ 0, /* tp_base */ 0, /* tp_dict */ 0, /* tp_descr_get */ 0, /* tp_descr_set */ 0, /* tp_dictoffset */ (initproc)HyDict_init, /* tp_init */ 0, /* tp_alloc */ 0, /* tp_new */ }; /* End of code for hyphenator_ objects */ /* -------------------------------------------------------- */ /* List of methods defined in the module */ static struct PyMethodDef hnj_methods[] = { {NULL, (PyCFunction)NULL, 0, NULL} /* sentinel */ }; static char hnj_module_documentation[] = "This C extension module is a wrapper around the hyphenation library 'hyphen-2.4' (2008-05).\n\ It should normally be imported and invoked only by the convenience interface provided\n\ by the hyphen.hyphenator class.\n" ; PyMODINIT_FUNC inithnj(void) { PyObject *m, *d; HyDict_type.tp_new = PyType_GenericNew; if (PyType_Ready(&HyDict_type) < 0) return; /* Create the module and add the functions */ m = Py_InitModule3("hnj", hnj_methods, hnj_module_documentation); if (m == NULL) return; /* Add some symbolic constants to the module */ d = PyModule_GetDict(m); ErrorObject = PyString_FromString("hnj.error"); PyDict_SetItemString(d, "error", ErrorObject); Py_INCREF(&HyDict_type); PyModule_AddObject(m, "hyphenator_", (PyObject *)&HyDict_type); /* Check for errors */ if (PyErr_Occurred()) Py_FatalError("cannot initialize module hnj."); } ./PyHyphen-1.0beta1/2.x/textwrap2.py0000666000175000017500000003622411132636054016417 0ustar takakitakaki"""Text wrapping and filling with optional hyphenation. """ # Copyright (C) 1999-2001 Gregory P. Ward. # Copyright (C) 2002, 2003 Python Software Foundation. # Written by Greg Ward # Optional hyphenation added by Dr. Leo __revision__ = "$Id: textwrap.py 46863 2006-06-11 19:42:51Z tim.peters $" import string, re # Do the right thing with boolean values for all known Python versions # (so this module can be copied to projects that don't depend on Python # 2.3, e.g. Optik and Docutils). try: True, False except NameError: (True, False) = (1, 0) __all__ = ['TextWrapper', 'wrap', 'fill'] # Hardcode the recognized whitespace characters to the US-ASCII # whitespace characters. The main reason for doing this is that in # ISO-8859-1, 0xa0 is non-breaking whitespace, so in certain locales # that character winds up in string.whitespace. Respecting # string.whitespace in those cases would 1) make textwrap treat 0xa0 the # same as any other whitespace char, which is clearly wrong (it's a # *non-breaking* space), 2) possibly cause problems with Unicode, # since 0xa0 is not in range(128). _whitespace = '\t\n\x0b\x0c\r ' class TextWrapper: """ Object for wrapping/filling text. The public interface consists of the wrap() and fill() methods; the other methods are just there for subclasses to override in order to tweak the default behaviour. If you want to completely replace the main wrapping algorithm, you'll probably have to override _wrap_chunks(). Several instance attributes control various aspects of wrapping: width (default: 70) the maximum width of wrapped lines (unless break_long_words is false) initial_indent (default: "") string that will be prepended to the first line of wrapped output. Counts towards the line's width. subsequent_indent (default: "") string that will be prepended to all lines save the first of wrapped output; also counts towards each line's width. expand_tabs (default: true) Expand tabs in input text to spaces before further processing. Each tab will become 1 .. 8 spaces, depending on its position in its line. If false, each tab is treated as a single character. replace_whitespace (default: true) Replace all whitespace characters in the input text by spaces after tab expansion. Note that if expand_tabs is false and replace_whitespace is true, every tab will be converted to a single space! fix_sentence_endings (default: false) Ensure that sentence-ending punctuation is always followed by two spaces. Off by default because the algorithm is (unavoidably) imperfect. break_long_words (default: true) Break words longer than 'width'. If false, those words will not be broken, and some lines might be longer than 'width'. use_hyphenator (default: None) must be a hyphenator object from the package 'hyphen'. """ whitespace_trans = string.maketrans(_whitespace, ' ' * len(_whitespace)) unicode_whitespace_trans = {} uspace = ord(u' ') for x in map(ord, _whitespace): unicode_whitespace_trans[x] = uspace # This funky little regex is just the trick for splitting # text up into word-wrappable chunks. E.g. # "Hello there -- you goof-ball, use the -b option!" # splits into # Hello/ /there/ /--/ /you/ /goof-/ball,/ /use/ /the/ /-b/ /option! # (after stripping out empty strings). wordsep_re = re.compile( r'(\s+|' # any whitespace r'[^\s\w]*\w+[a-zA-Z]-(?=\w+[a-zA-Z])|' # hyphenated words r'(?<=[\w\!\"\'\&\.\,\?])-{2,}(?=\w))') # em-dash # XXX this is not locale- or charset-aware -- string.lowercase # is US-ASCII only (and therefore English-only) sentence_end_re = re.compile(r'[%s]' # lowercase letter r'[\.\!\?]' # sentence-ending punct. r'[\"\']?' # optional end-of-quote % string.lowercase) def __init__(self, width=70, initial_indent="", subsequent_indent="", expand_tabs=True, replace_whitespace=True, fix_sentence_endings=False, break_long_words=True, use_hyphenator = None): self.width = width self.initial_indent = initial_indent self.subsequent_indent = subsequent_indent self.expand_tabs = expand_tabs self.replace_whitespace = replace_whitespace self.fix_sentence_endings = fix_sentence_endings self.break_long_words = break_long_words self.use_hyphenator = use_hyphenator # -- Private methods ----------------------------------------------- # (possibly useful for subclasses to override) def _munge_whitespace(self, text): """_munge_whitespace(text : string) -> string Munge whitespace in text: expand tabs and convert all other whitespace characters to spaces. Eg. " foo\tbar\n\nbaz" becomes " foo bar baz". """ if self.expand_tabs: text = text.expandtabs() if self.replace_whitespace: if isinstance(text, str): text = text.translate(self.whitespace_trans) elif isinstance(text, unicode): text = text.translate(self.unicode_whitespace_trans) return text def _split(self, text): """_split(text : string) -> [string] Split the text to wrap into indivisible chunks. Chunks are not quite the same as words; see wrap_chunks() for full details. As an example, the text Look, goof-ball -- use the -b option! breaks into the following chunks: 'Look,', ' ', 'goof-', 'ball', ' ', '--', ' ', 'use', ' ', 'the', ' ', '-b', ' ', 'option!' """ chunks = self.wordsep_re.split(text) chunks = filter(None, chunks) return chunks def _fix_sentence_endings(self, chunks): """_fix_sentence_endings(chunks : [string]) Correct for sentence endings buried in 'chunks'. Eg. when the original text contains "... foo.\nBar ...", munge_whitespace() and split() will convert that to [..., "foo.", " ", "Bar", ...] which has one too few spaces; this method simply changes the one space to two. """ i = 0 pat = self.sentence_end_re while i < len(chunks)-1: if chunks[i+1] == " " and pat.search(chunks[i]): chunks[i+1] = " " i += 2 else: i += 1 def _handle_long_word(self, reversed_chunks, cur_line, cur_len, width): """_handle_long_word(chunks : [string], cur_line : [string], cur_len : int, width : int) Handle a chunk of text (most likely a word, not whitespace) that is too long to fit in any line. """ space_left = max(width - cur_len, 1) # If we're allowed to break long words, then do so: put as much # of the next chunk onto the current line as will fit. if self.break_long_words: cur_line.append(reversed_chunks[-1][:space_left]) reversed_chunks[-1] = reversed_chunks[-1][space_left:] # Otherwise, we have to preserve the long word intact. Only add # it to the current line if there's nothing already there -- # that minimizes how much we violate the width constraint. elif not cur_line: cur_line.append(reversed_chunks.pop()) # If we're not allowed to break long words, and there's already # text on the current line, do nothing. Next time through the # main loop of _wrap_chunks(), we'll wind up here again, but # cur_len will be zero, so the next line will be entirely # devoted to the long word that we can't handle right now. def _wrap_chunks(self, chunks): """_wrap_chunks(chunks : [string]) -> [string] Wrap a sequence of text chunks and return a list of lines of length 'self.width' or less. (If 'break_long_words' is false, some lines may be longer than this.) Chunks correspond roughly to words and the whitespace between them: each chunk is indivisible (modulo 'break_long_words'), but a line break can come between any two chunks. Chunks should not have internal whitespace; ie. a chunk is either all whitespace or a "word". Whitespace chunks will be removed from the beginning and end of lines, but apart from that whitespace is preserved. """ lines = [] if self.width <= 0: raise ValueError("invalid width %r (must be > 0)" % self.width) # Arrange in reverse order so items can be efficiently popped # from a stack of chucks. chunks.reverse() while chunks: # Start the list of chunks that will make up the current line. # cur_len is just the length of all the chunks in cur_line. cur_line = [] cur_len = 0 # Figure out which static string will prefix this line. if lines: indent = self.subsequent_indent else: indent = self.initial_indent # Maximum width for this line. width = self.width - len(indent) # First chunk on line is whitespace -- drop it, unless this # is the very beginning of the text (ie. no lines started yet). if chunks[-1].strip() == '' and lines: del chunks[-1] while chunks: l = len(chunks[-1]) # Can at least squeeze this chunk onto the current line. if cur_len + l <= width: cur_line.append(chunks.pop()) cur_len += l # Nope, this line is full. But try hyphenation. else: if self.use_hyphenator and (width - cur_len >= 2): hyphenated_chunk = self.use_hyphenator.wrap(chunks[-1], width - cur_len) if hyphenated_chunk: cur_line.append(hyphenated_chunk[0]) chunks[-1] = hyphenated_chunk[1] break # The current line is full, and the next chunk is too big to # fit on *any* line (not just this one). if chunks and len(chunks[-1]) > width: self._handle_long_word(chunks, cur_line, cur_len, width) # If the last chunk on this line is all whitespace, drop it. if cur_line and cur_line[-1].strip() == '': del cur_line[-1] # Convert current line back to a string and store it in list # of all lines (return value). if cur_line: lines.append(indent + ''.join(cur_line)) return lines # -- Public interface ---------------------------------------------- def wrap(self, text): """wrap(text : string) -> [string] Reformat the single paragraph in 'text' so it fits in lines of no more than 'self.width' columns, and return a list of wrapped lines. Tabs in 'text' are expanded with string.expandtabs(), and all other whitespace characters (including newline) are converted to space. """ text = self._munge_whitespace(text) chunks = self._split(text) if self.fix_sentence_endings: self._fix_sentence_endings(chunks) return self._wrap_chunks(chunks) def fill(self, text): """fill(text : string) -> string Reformat the single paragraph in 'text' to fit in lines of no more than 'self.width' columns, and return a new string containing the entire wrapped paragraph. """ return "\n".join(self.wrap(text)) # -- Convenience interface --------------------------------------------- def wrap(text, width=70, **kwargs): """Wrap a single paragraph of text, returning a list of wrapped lines. Reformat the single paragraph in 'text' so it fits in lines of no more than 'width' columns, and return a list of wrapped lines. By default, tabs in 'text' are expanded with string.expandtabs(), and all other whitespace characters (including newline) are converted to space. See TextWrapper class for available keyword args to customize wrapping behaviour. """ w = TextWrapper(width=width, **kwargs) return w.wrap(text) def fill(text, width=70, **kwargs): """Fill a single paragraph of text, returning a new string. Reformat the single paragraph in 'text' to fit in lines of no more than 'width' columns, and return a new string containing the entire wrapped paragraph. As with wrap(), tabs are expanded and other whitespace characters converted to space. See TextWrapper class for available keyword args to customize wrapping behaviour. """ w = TextWrapper(width=width, **kwargs) return w.fill(text) # -- Loosely related functionality ------------------------------------- _whitespace_only_re = re.compile('^[ \t]+$', re.MULTILINE) _leading_whitespace_re = re.compile('(^[ \t]*)(?:[^ \t\n])', re.MULTILINE) def dedent(text): """Remove any common leading whitespace from every line in `text`. This can be used to make triple-quoted strings line up with the left edge of the display, while still presenting them in the source code in indented form. Note that tabs and spaces are both treated as whitespace, but they are not equal: the lines " hello" and "\thello" are considered to have no common leading whitespace. (This behaviour is new in Python 2.5; older versions of this module incorrectly expanded tabs before searching for common leading whitespace.) """ # Look for the longest leading string of spaces and tabs common to # all lines. margin = None text = _whitespace_only_re.sub('', text) indents = _leading_whitespace_re.findall(text) for indent in indents: if margin is None: margin = indent # Current line more deeply indented than previous winner: # no change (previous winner is still on top). elif indent.startswith(margin): pass # Current line consistent with and no deeper than previous winner: # it's the new winner. elif margin.startswith(indent): margin = indent # Current line and previous winner have no common whitespace: # there is no margin. else: margin = "" break # sanity check (testing/debugging only) if 0 and margin: for line in text.split("\n"): assert not line or line.startswith(margin), \ "line = %r, margin = %r" % (line, margin) if margin: text = re.sub(r'(?m)^' + margin, '', text) return text if __name__ == "__main__": #print dedent("\tfoo\n\tbar") #print dedent(" \thello there\n \t how are you?") print dedent("Hello there.\n This is indented.") ./PyHyphen-1.0beta1/2.x/config.py0000666000175000017500000000007211502153064015710 0ustar takakitakakidefault_dict_path = u'$path' default_repository = u'$repo'./PyHyphen-1.0beta1/2.x/dictools.py0000666000175000017500000000702611546012624016275 0ustar takakitakaki# PyHyphen - hyphenation for Python # module: dictools ''' This module contains convenience functions to handle hyphenation dictionaries. ''' import os, urllib2, csv, pickle, config, hyphen from StringIO import StringIO from zipfile import ZipFile __all__ = ['install', 'is_installed', 'uninstall', 'list_installed', 'install_dict_info'] def list_installed(directory = config.default_dict_path): '''Return a list of strings containing language and country codes of the dictionaries installed in 'directory' (default as declared in config.py). Example: file name = 'hyph_en_US.dic'. Return value: ['en_US']''' return [d[5:-4] for d in os.listdir(directory) if (d.startswith('hyph_') and d.endswith('.dic'))] def is_installed(language, directory = config.default_dict_path): '''return True if 'directory' (default as declared in config.py) contains a dictionary file for 'language', False otherwise. By convention, 'language' should have the form 'll_CC'. Example: 'en_US' for US English. ''' return (language in list_installed(directory)) def install(language, directory = config.default_dict_path, repos = config.default_repository): ''' Download and install a dictionary file. language: a string of the form 'll_CC'. Example: 'en_US' for English, USA directory: the installation directory. Defaults to the value given in config.py. After installation this is the package root of 'hyphen' repos: the url of the dictionary repository. (Default: as declared in config.py; after installation this is the OpenOffice repository for dictionaries.). ''' if hyphen.dict_info and language in hyphen.dict_info: fn = hyphen.dict_info[language]['file_name'] else: fn = 'hyph_' + language + '.dic' url = ''.join((repos, fn)) s = urllib2.urlopen(url).read() z = ZipFile(StringIO(s)) if z.testzip(): raise IOError('The ZIP archive containing the dictionary is corrupt.') dic_filename = ''.join((hyphen.dict_info[language]['name'], '.dic')) dic_str = z.read(dic_filename) dest = open('/'.join((directory, dic_filename)), 'w') dest.write(dic_str) dest.close() def uninstall(language, directory = config.default_dict_path): ''' Uninstall the dictionary of the specified language. 'language': is by convention a string of the form 'll_CC' whereby ll is the language code and CC the country code. 'directory' (default: config.default_dict_path'. After installation of PyHyphen this is the package root of 'hyphen'. ''' if hyphen.dict_info: file_path = ''.join((directory, '/', hyphen.dict_info[language]['name'], '.dic')) else: file_path = ''.join((directory, '/', 'hyph_', language, '.dic')) os.remove(file_path) def install_dict_info(save = True, directory = config.default_dict_path): '''download metadata on available dictionaries from the oo website and stores it locally.''' l = urllib2.urlopen('http://ftp.osuosl.org/pub/openoffice/contrib/dictionaries/hyphavail.lst').readlines() stream = StringIO('\n'.join(l)) d = csv.DictReader(stream, fieldnames = ['language_code', 'country_code', 'name', 'long_descr', 'file_name']) avail_dict = {} for i in d: key = '_'.join((i['language_code'], i['country_code'])) avail_dict[key] = i if save: file_path = directory + '/dict_info.pickle' f = open(file_path, 'w') pickle.dump(avail_dict, f) f.close() return avail_dict ./PyHyphen-1.0beta1/2.x/__init__.py0000666000175000017500000002112011546027462016211 0ustar takakitakaki# -*- coding: utf-8 -*- # Without prejudice to the license governing the use of # the Python standard module textwrap on which textwrap2 is based, # PyHyphen is licensed under the same terms as the underlying C library hyphen-2.3.1. # The essential parts of the license terms of libhyphen are quoted hereunder. # # # # # Extract from the license information of hyphen-2.4 library # ============================================================ # # # # GPL 2.0/LGPL 2.1/MPL 1.1 tri-license # # Software distributed under these licenses is distributed on an "AS IS" basis, # WITHOUT WARRANTY OF ANY KIND, either express or implied. See the licences # for the specific language governing rights and limitations under the licenses. # # The contents of this software may be used under the terms of # the GNU General Public License Version 2 or later (the "GPL"), or # the GNU Lesser General Public License Version 2.1 or later (the "LGPL", ''' hyphen - hyphenation for Python This package adds a hyphenation functionality to the Python programming language. You may also wish to have a look at the module 'textwrap2' distributed jointly with this package. Contents 1. Overview 2. Code examples 1. Overview PyHyphen consists of the package 'hyphen' and the module 'textwrap2'. 1.1 The hyphen package contains: - at top level the definition of the class 'Hyphenator' each instance of which can hyphenate words using a dictionary compatible with the hyphenation feature of OpenOffice and Mozilla. The former class 'hyphenator' is deprecated as of version 0.10 as class names conventially begin with a capital letter. - the module dictools contains useful functions such as automatic downloading and installing dictionaries from a configurable repository. By default, the OpenOffice repository is used. - config is a configuration file initialized at install time with default values for the directory where dictionaries are searched, and the repository for future downloads of dictionaries. - hyph_en_US.dic is the hyphenation dictionary for US English as found on the OpenOffice.org repository. - 'hnj' is the C extension module that does all the ground work. It contains the C library libhyphen used in OpenOffice and Mozilla products. It supports non-standard hyphenation and - as of version 2.4 - compound words. Moreover, the minimum number of characters cut off by the hyphen can be set both for the entire word and compound parts thereof. Note that hyphenation dictionaries are invisible to the Python programmer. But each Hyphenator object has a member 'info' of type dict which contains meta information on the hyphenation dictionary. The module-level attribute is a dictionary with meta information on all dictionaries available for download at the specified location. It relies on the successful install of a meta data file from the oo website. If you use other repository locations, this feature will not work. 1.2 The module 'textwrap2' This module is an enhanced though backwards compatible version of the module 'textwrap' known from the Python standard library. Not very surprisingly, it adds hyphenation functionality to 'textwrap'. 2. Code examples (see README.txt) ''' import hnj, config, pickle, os __all__ = ['dictools', 'Hyphenator'] # Try to load meta information on downloadable dictionaries: if os.path.exists(config.default_dict_path + '/dict_info.pickle'): dict_info = pickle.load(open(config.default_dict_path + '/dict_info.pickle')) else: dict_info = None class Hyphenator: """ Wrapper class around the class 'hnj.hyphenator_'. It provides convenient access to the C library hyphen-2.4'. """ def __init__(self, language = 'en_US', lmin = 2, rmin = 2, compound_lmin = 2, compound_rmin = 2, directory = config.default_dict_path): ''' Return a hyphenator object initialized with a dictionary for the specified language. 'language' should by convention be a string of length 5 of the form "ll_CC" where ll is the language code and CC the country code. This is inspired by the file names of OpenOffice's hyphenation dictionaries. Example: 'en_NZ' for English / New Zealand Each class instance has an attribute 'info' of type dict containing metadata on its dictionary. If the module-level attribute dict_info is None, or does not contain an entry for this dictionary, the info attribute of the Hyphenator instance is None. There is also a 'language' attribute of type str which is deprecated since v1.0. lmin, rmin, compound_lmin and compound_rmin: set minimum number of chars to be cut off by hyphenation in single or compound words ''' if dict_info and language in dict_info: file_name = dict_info[language]['name'] + u'.dic' else: file_name = language file_path = directory + u'/' + file_name self.__hyphenate__ = hnj.hyphenator_(file_path, lmin, rmin, compound_lmin, compound_rmin) self.language = language if dict_info: self.info = dict_info[language] else: self.info = None def pairs(self, word): ''' Hyphenate a unicode string and return a list of lists of the form [[u'hy', u'phenation'], [u'hyphen', u'ation']]. Return [], if len(word) < 4 or if word could not be hyphenated because * it is not encodable to the dictionary's encoding, or ** the hyphenator could not find any hyphenation point ''' if not isinstance(word, unicode): raise TypeError('Unicode object expected.') mode = 1 if (len(word) < 4) or ('=' in word): return [] if not word.islower(): if (word.isupper()): mode += 4 word = word.lower() else: if (word[1:].islower()): mode += 2 word = word.lower() else: return [] # Now call the hyphenator catching the case that 'word' is not encodable # to the dictionary's encoding.' try: return self.__hyphenate__.apply(word, mode) except UnicodeError: return [] def syllables(self, word): ''' Hyphenate a unicode string and return list of syllables. Return [], if len(word) < 4 or if word could not be hyphenated because * it is not encodable to the dictionary's encoding, or ** the hyphenator could not find any hyphenation point Results are not consistent in case of non-standard hyphenation as a join of the syllables would not yield the original word. ''' if not isinstance(word, unicode): raise TypeError('Unicode object expected.') mode = 0 if (len(word) < 4) or ('=' in word): return [] if not word.islower(): if (word.isupper()): mode += 4 word = word.lower() else: if (word[1:].islower()): mode += 2 word = word.lower() else: return [] # Now call the hyphenator catching the case that 'word' is not encodable # to the dictionary's encoding.' try: return self.__hyphenate__.apply(word, mode).split('=') except UnicodeError: return [] def wrap(self, word, width, hyphen = '-'): ''' Hyphenate 'word' and determine the best hyphenation fitting into 'width' characters. Return a list of the form [u'hypen-', u'ation'] The '-' in the above example is the default value of 'hyphen'. It is added automatically and must fit into 'width' as well. If no hyphenation was found such that the shortest prefix (plus 'hyphen') fits into 'width', [] is returned. ''' p = self.pairs(word) max_chars = width - len(hyphen) while p: if p[-1][0].endswith(hyphen): cur_max_chars = max_chars + 1 else: cur_max_chars = max_chars if len(p[-1][0]) > cur_max_chars: p.pop() else: break if p: # Need to append a hyphen? if cur_max_chars == max_chars: p[-1][0] += hyphen return p[-1] else: return [] # The following ensures backward compatibility with version 0.9.3 class hyphenator(Hyphenator): '''This class is deprecated. Use 'Hyphenator' instead.''' ./PyHyphen-1.0beta1/3.x/0000775000175000017500000000000011546766220014105 5ustar takakitakaki./PyHyphen-1.0beta1/3.x/hnjmodule.c0000666000175000017500000004067211514603372016242 0ustar takakitakaki#include "Python.h" #include "structmember.h" #include "hyphen.h" #include "string.h" /* String constants for calls of Py_Unicode_FromEncodedObject etc.*/ static const char unicode_errors[] = "strict"; /* is raised if hnj_hyphen returns an error while trying to hyphenate a word*/ static PyObject *ErrorObject; /* ----------------------------------------------------- */ /* Declarations for objects of type hyphenator_ */ /* type object to store the hyphenation dictionary. Its only method is 'apply' which calls the core function 'hnj_hyphenate2'' from the wrapped library 'hnj_hyphen-2.3' */ typedef struct { PyObject_HEAD HyphenDict *dict; int lmin, rmin, compound_lmin, compound_rmin; } HyDictobject; static PyTypeObject HyDict_type; /* ---------------------------------------------------------------- */ static char HyDict_apply__doc__[] = "SUMMARY:\n\ apply(word: unicode object, mode: int) -> hyphenated word (return type depends on value of mode)\n\n\ Note: 'hnjmodule' should normally be called only from the convenience interface provided by\ the hyphen.hyphenator class.\n\n\ word: must be lower-cased to be hyphenated correctly. Capital letters are restored\n\ according to the value of 'mode'. The encoded representation of 'word' may have at most\n\ 100 bytes including the terminating '\0'.\n\ mode: the 3 least significant bits are interpreted as flags with the following meaning:\n\ - mode & 1 = 0: return a string with '=' inserted at the hyphenation points\n\ - mode & 1 = 1: return a list of lists of the form [before_hyphen, after_hyphen]\n\ - mode & 2 = 1: return a capitalized word\n\ - mode & 4 = 1: return an upper-cased word\n"; /* get a pointer to the nth 8-bit or UTF-8 character of the word */ /* This is required because some operations are done at utf8 string level. */ static char * hindex(char * word, int n, int utf8) { int j = 0; while (j < n) { j++; word++; while (utf8 && ((((unsigned char) *word) >> 6) == 2)) word++; } return word; } /* Depending on the value of 'mode', convert a utf8 C string to PyUnicode or PyString (utf8), handle also capitalization and upper case words. */ static PyObject * prepare_result(char *word, char *encoding, int mode) { Py_UNICODE * ch_u; PyObject *result; int len_s, i; /* first convert the C string to unicode. */ if (!(result = PyUnicode_Decode(word, strlen(word), encoding, unicode_errors))) return NULL; if (mode & 4) { /* capitalize entire word */ ch_u = PyUnicode_AS_UNICODE(result); len_s = PyUnicode_GetSize(result); for (i=0; i <= len_s; i++) { *ch_u = Py_UNICODE_TOUPPER(*ch_u); ch_u++; } } else { if (mode & 2) { /* capitalize first letter */ ch_u = PyUnicode_AS_UNICODE(result); *ch_u = Py_UNICODE_TOUPPER(*ch_u); } } /* return a unicode object */ return result; } /* core function of the hyphenator_ object type */ static PyObject * HyDict_apply(HyDictobject *self, PyObject *args) { const char separator[] = "="; char *hyphenated_word, *hyphens, *word_str; char ** rep = NULL; char r; int * pos = NULL; int * cut = NULL; unsigned int wd_size, hyph_count, i, j, k, mode; PyObject *result, *s1, *s2, *separator_u = NULL; /* mode: bit0 === 1: return a tuple, otherwise a word with '=' inserted at the positions of possible hyphenations. bit1 == 1: word must be capitalized before returning bit2 == 1: entire word must be uppered before returning */ /* parse and check arguments */ if (!PyArg_ParseTuple(args, "esi", &self->dict->cset, &word_str, &mode)) return NULL; wd_size = strlen(word_str); if (wd_size >= MAX_CHARS) { PyErr_SetString(PyExc_ValueError, "Word to be hyphenated may have at most 100 characters."); PyMem_Free(word_str); return NULL; } /* allocate memory for the return values of the core function hnj_hyphenate3*/ hyphens = (char *) PyMem_Malloc(wd_size + 5); hyphenated_word = (char *) PyMem_Malloc(wd_size * 3); /* now actually try the hyphenation*/ if (hnj_hyphen_hyphenate3(self->dict, word_str, wd_size, hyphens, hyphenated_word, &rep, &pos, &cut, self->lmin, self->rmin, self->compound_lmin, self->compound_rmin)) { PyMem_Free(hyphens); PyMem_Free(hyphenated_word); PyMem_Free(word_str); PyErr_SetString(ErrorObject, "Cannot hyphenate word."); return NULL; } /* Count possible hyphenations. This is done by checking bit 0 of each */ /* char of 'hyphens' which is 0 if and only if the word can be hyphened */ /* at that position. Then proceed to */ /* the real work, i.d. returning a unicode object with inserted '=' at each */ /* possible hyphenation, or return a list of lists of two unicode objects */ /* representing a possible hyphenation each. Note that the string */ /* is useful only in languages without non-standard hyphenation, as */ /* the string could contain more than one replacement, whereas */ /* we are only interested in one replacement at the hyphenation position */ /* we choose. */ /* If no hyphenations were found, a string with 0 inserted '=', i.e. the original word, */ /* or an empty list (with 0 pairs) is returned. */ hyph_count = 0; for (i=0; (i+1) < strlen(hyphens); i++) { if (hyphens[i] & 1) hyph_count++; } /* Do we need to return a string with inserted '=', or a list of pairs? */ if (!(mode & 1)) { /* Prepare for returning a unicode obj of the form 'before_hyphen=after_hyphen. */ if (!(result = prepare_result(hyphenated_word, self->dict->cset, mode))) { PyMem_Free(hyphenated_word); PyMem_Free(word_str); PyMem_Free(hyphens); return NULL; } PyMem_Free(hyphenated_word); } else { PyMem_Free(hyphenated_word); /* construct a list of lists of two unicode objects. Each inner list */ /* represents a possible hyphenation. */ /* First create the outer list. Each element will be a list of two strings or unicode objects. */ if (!(result = PyList_New(hyph_count))) { PyMem_Free(hyphens); PyMem_Free(word_str); return NULL; } /* now fill the resulting list from left to right with the pairs */ j=0; hyph_count = 0; /* The following is needed to split the word (in which an '=' indicates the */ /* hyphen position) */ separator_u = PyUnicode_Decode(separator, 1, self->dict->cset, unicode_errors); for (i = 0; (i + 1) < strlen(word_str); i++) { /* j-th character utf8? Then just increment j */ if (self->dict->utf8 && ((((unsigned char) word_str[i]) >> 6) == 2)) continue; /* Is here a hyphen? */ if ((hyphens[j] & 1)) { /* Build the hyphenated word at C string level. */ /* first, handle non-standard hyphenation with replacement. */ if (rep && rep[j]) { /* determine the position within word_str where to insert rep[j] */ /* do the replacement by appending the three substrings: */ hyphenated_word = (char *) PyMem_Malloc(strlen(word_str) + strlen(rep[j])+1); k = hindex(word_str, j - pos[j] + 1, self->dict->utf8) - word_str; r = word_str[k]; word_str[k] = 0; strcpy(hyphenated_word, word_str); strcat(hyphenated_word, rep[j]); word_str[k] = r; strcat(hyphenated_word, hindex(word_str + k, cut[j], self->dict->utf8)); } else { /* build the word in case of standard hyphenation. */ /* An '=' will be inserted so that the */ /* resulting string has the same format as in the non-standard case. */ hyphenated_word = (char *) PyMem_Malloc(strlen(word_str) + 2); k = hindex(word_str, j + 1, self->dict->utf8) - word_str; r = word_str[k]; word_str[k] = 0; strcpy(hyphenated_word, word_str); strcat(hyphenated_word, separator); word_str[k] = r; strcat(hyphenated_word, word_str + k); } /* Now prepare the resulting unicode object according to the value of mode */ if (!(s1 = prepare_result(hyphenated_word, self->dict->cset, mode))) { PyMem_Free(hyphenated_word); PyMem_Free(hyphens); PyMem_Free(word_str); return NULL; } PyMem_Free(hyphenated_word); /* split it into two parts at the position of the '=' */ /* and write the resulting list into the tuple */ if (!((s2 = PyUnicode_Split(s1, separator_u, 1)) && (!PyList_SetItem(result, hyph_count++, s2)))) { Py_XDECREF(s2); Py_DECREF(s1); PyMem_Free(hyphens); PyMem_Free(word_str); return NULL; } Py_DECREF(s1); } /* finished with current hyphen */ j++; } /* for loop*/ Py_DECREF(separator_u); } /* end of else construct a list */ PyMem_Free(hyphens); PyMem_Free(word_str); return result; } static struct PyMethodDef HyDict_methods[] = { {"apply", (PyCFunction)HyDict_apply, METH_VARARGS, HyDict_apply__doc__}, {NULL, NULL} /* sentinel */ }; /* ---------- */ static void HyDict_dealloc(HyDictobject *self) { if (self->dict) hnj_hyphen_free(self->dict); PyObject_Del(self); } static int HyDict_init(HyDictobject *self, PyObject *args) { char* fn; if (!PyArg_ParseTuple(args, "siiii", &fn, &self->lmin, &self->rmin, &self->compound_lmin, &self->compound_rmin)) return -1; if (!(self->dict = hnj_hyphen_load(fn))) { if (!PyErr_Occurred()) PyErr_SetString(PyExc_IOError, "Cannot load hyphen dictionary."); return -1; } return 0; } static char HyDict_type__doc__[] = "Wrapper class for the hnj_hyphen library contained in this module.\n\n\ Usage: hyphenator_(dict_file_name: string)\n\ The init method will try to load a hyphenation dictionary with the filename passed.\n\ If an error occurs when trying to load the dictionary, IOError is raised.\n\ Dictionary files compatible with hnjmodule can be downloaded at the OpenOffice website.\n\n\ This class should normally be instantiated only by the convenience interface provided by\n\ the hyphen.hyphenator class.\n" ; static PyTypeObject HyDict_type = { PyObject_HEAD_INIT(NULL) "hnjmodule.hyphenator_", /*tp_name*/ sizeof(HyDictobject), /*tp_basicsize*/ 0, /*tp_itemsize*/ /* methods */ (destructor)HyDict_dealloc, /*tp_dealloc*/ (printfunc)0, /*tp_print*/ 0, /*tp_getattr*/ (setattrfunc)0, /*tp_setattr*/ 0, /*tp_reserved*/ (reprfunc)0, /*tp_repr*/ 0, /*tp_as_number*/ 0, /*tp_as_sequence*/ 0, /*tp_as_mapping*/ (hashfunc)0, /*tp_hash*/ (ternaryfunc)0, /*tp_call*/ (reprfunc)0, /*tp_str*/ 0, /*tp_getattro*/ 0, /*tp_setattro*/ 0, /*tp_as_buffer*/ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /*tp_flags*/ HyDict_type__doc__, /* Documentation string */ 0, /* tp_traverse */ 0, /* tp_clear */ 0, /* tp_richcompare */ 0, /* tp_weaklistoffset */ 0, /* tp_iter */ 0, /* tp_iternext */ HyDict_methods, /* tp_methods */ 0, /* tp_members */ 0, /* tp_getset */ 0, /* tp_base */ 0, /* tp_dict */ 0, /* tp_descr_get */ 0, /* tp_descr_set */ 0, /* tp_dictoffset */ (initproc)HyDict_init, /* tp_init */ 0, /* tp_alloc */ 0, /* tp_new */ }; static PyTypeObject Str_Type = { /* The ob_type field must be initialized in the module init function * to be portable to Windows without using C++. */ PyVarObject_HEAD_INIT(NULL, 0) "hnjmodule.Str", /*tp_name*/ 0, /*tp_basicsize*/ 0, /*tp_itemsize*/ /* methods */ 0, /*tp_dealloc*/ 0, /*tp_print*/ 0, /*tp_getattr*/ 0, /*tp_setattr*/ 0, /*tp_compare*/ 0, /*tp_repr*/ 0, /*tp_as_number*/ 0, /*tp_as_sequence*/ 0, /*tp_as_mapping*/ 0, /*tp_hash*/ 0, /*tp_call*/ 0, /*tp_str*/ 0, /*tp_getattro*/ 0, /*tp_setattro*/ 0, /*tp_as_buffer*/ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /*tp_flags*/ 0, /*tp_doc*/ 0, /*tp_traverse*/ 0, /*tp_clear*/ 0, /*tp_richcompare*/ 0, /*tp_weaklistoffset*/ 0, /*tp_iter*/ 0, /*tp_iternext*/ 0, /*tp_methods*/ 0, /*tp_members*/ 0, /*tp_getset*/ 0, /* see PyInit_xx */ /*tp_base*/ 0, /*tp_dict*/ 0, /*tp_descr_get*/ 0, /*tp_descr_set*/ 0, /*tp_dictoffset*/ 0, /*tp_init*/ 0, /*tp_alloc*/ 0, /*tp_new*/ 0, /*tp_free*/ 0, /*tp_is_gc*/ }; /* ---------- */ static PyObject * null_richcompare(PyObject *self, PyObject *other, int op) { Py_INCREF(Py_NotImplemented); return Py_NotImplemented; } static PyTypeObject Null_Type = { /* The ob_type field must be initialized in the module init function * to be portable to Windows without using C++. */ PyVarObject_HEAD_INIT(NULL, 0) "hnjmodule.Null", /*tp_name*/ 0, /*tp_basicsize*/ 0, /*tp_itemsize*/ /* methods */ 0, /*tp_dealloc*/ 0, /*tp_print*/ 0, /*tp_getattr*/ 0, /*tp_setattr*/ 0, /*tp_compare*/ 0, /*tp_repr*/ 0, /*tp_as_number*/ 0, /*tp_as_sequence*/ 0, /*tp_as_mapping*/ 0, /*tp_hash*/ 0, /*tp_call*/ 0, /*tp_str*/ 0, /*tp_getattro*/ 0, /*tp_setattro*/ 0, /*tp_as_buffer*/ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /*tp_flags*/ 0, /*tp_doc*/ 0, /*tp_traverse*/ 0, /*tp_clear*/ null_richcompare, /*tp_richcompare*/ 0, /*tp_weaklistoffset*/ 0, /*tp_iter*/ 0, /*tp_iternext*/ 0, /*tp_methods*/ 0, /*tp_members*/ 0, /*tp_getset*/ 0, /* see PyInit_xx */ /*tp_base*/ 0, /*tp_dict*/ 0, /*tp_descr_get*/ 0, /*tp_descr_set*/ 0, /*tp_dictoffset*/ 0, /*tp_init*/ 0, /*tp_alloc*/ 0, /* see PyInit_xx */ /*tp_new*/ 0, /*tp_free*/ 0, /*tp_is_gc*/ }; /* ---------- */ /* End of code for hyphenator_ objects */ /* -------------------------------------------------------- */ /* List of methods defined in the module */ static struct PyMethodDef hnj_methods[] = { {NULL, (PyCFunction)NULL, 0, NULL} /* sentinel */ }; static char module_doc[] = "This C extension module is a wrapper around the hyphenation library 'hyphen-2.3.1' (2008-02-19).\n\ It should normally be imported and invoked only by the convenience interface provided\n\ by the hyphen.hyphenator class.\n" ; static struct PyModuleDef hnjmodule = { PyModuleDef_HEAD_INIT, "hnj", module_doc, -1, hnj_methods, NULL, NULL, NULL, NULL }; PyMODINIT_FUNC PyInit_hnj(void) { PyObject *m = NULL; /* Due to cross platform compiler issues the slots must be filled * here. It's required for portability to Windows without requiring * C++. */ Null_Type.tp_base = &PyBaseObject_Type; Null_Type.tp_new = PyType_GenericNew; Str_Type.tp_base = &PyUnicode_Type; HyDict_type.tp_new = PyType_GenericNew; /* Create the module and add the functions */ m = PyModule_Create(&hnjmodule); if (m == NULL) goto fail; /* Add some symbolic constants to the module */ if (ErrorObject == NULL) { ErrorObject = PyErr_NewException("hnj.error", NULL, NULL); if (ErrorObject == NULL) goto fail; } Py_INCREF(ErrorObject); PyModule_AddObject(m, "error", ErrorObject); /* Add Str */ if (PyType_Ready(&Str_Type) < 0) goto fail; PyModule_AddObject(m, "Str", (PyObject *)&Str_Type); /* Add Null */ if (PyType_Ready(&Null_Type) < 0) goto fail; PyModule_AddObject(m, "Null", (PyObject *)&Null_Type); /* Add HiDict_type */ if (PyType_Ready(&HyDict_type) < 0) goto fail; PyModule_AddObject(m, "hyphenator_", (PyObject *)&HyDict_type); return m; fail: Py_XDECREF(m); return NULL; } ./PyHyphen-1.0beta1/3.x/textwrap2.py0000666000175000017500000003740011132636054016415 0ustar takakitakaki"""Text wrapping and filling. """ # Copyright (C) 1999-2001 Gregory P. Ward. # Copyright (C) 2002, 2003 Python Software Foundation. # Written by Greg Ward __revision__ = "$Id: textwrap.py 63335 2008-05-16 00:03:33Z alexandre.vassalotti $" import string, re __all__ = ['TextWrapper', 'wrap', 'fill'] # Hardcode the recognized whitespace characters to the US-ASCII # whitespace characters. The main reason for doing this is that in # ISO-8859-1, 0xa0 is non-breaking whitespace, so in certain locales # that character winds up in string.whitespace. Respecting # string.whitespace in those cases would 1) make textwrap treat 0xa0 the # same as any other whitespace char, which is clearly wrong (it's a # *non-breaking* space), 2) possibly cause problems with Unicode, # since 0xa0 is not in range(128). _whitespace = '\t\n\x0b\x0c\r ' class TextWrapper: """ Object for wrapping/filling text. The public interface consists of the wrap() and fill() methods; the other methods are just there for subclasses to override in order to tweak the default behaviour. If you want to completely replace the main wrapping algorithm, you'll probably have to override _wrap_chunks(). Several instance attributes control various aspects of wrapping: width (default: 70) the maximum width of wrapped lines (unless break_long_words is false) initial_indent (default: "") string that will be prepended to the first line of wrapped output. Counts towards the line's width. subsequent_indent (default: "") string that will be prepended to all lines save the first of wrapped output; also counts towards each line's width. expand_tabs (default: true) Expand tabs in input text to spaces before further processing. Each tab will become 1 .. 8 spaces, depending on its position in its line. If false, each tab is treated as a single character. replace_whitespace (default: true) Replace all whitespace characters in the input text by spaces after tab expansion. Note that if expand_tabs is false and replace_whitespace is true, every tab will be converted to a single space! fix_sentence_endings (default: false) Ensure that sentence-ending punctuation is always followed by two spaces. Off by default because the algorithm is (unavoidably) imperfect. break_long_words (default: true) Break words longer than 'width'. If false, those words will not be broken, and some lines might be longer than 'width'. break_on_hyphens (default: true) Allow breaking hyphenated words. If true, wrapping will occur preferably on whitespaces and right after hyphens part of compound words. drop_whitespace (default: true) Drop leading and trailing whitespace from lines. """ unicode_whitespace_trans = {} uspace = ord(' ') for x in _whitespace: unicode_whitespace_trans[ord(x)] = uspace # This funky little regex is just the trick for splitting # text up into word-wrappable chunks. E.g. # "Hello there -- you goof-ball, use the -b option!" # splits into # Hello/ /there/ /--/ /you/ /goof-/ball,/ /use/ /the/ /-b/ /option! # (after stripping out empty strings). wordsep_re = re.compile( r'(\s+|' # any whitespace r'[^\s\w]*\w+[a-zA-Z]-(?=\w+[a-zA-Z])|' # hyphenated words r'(?<=[\w\!\"\'\&\.\,\?])-{2,}(?=\w))') # em-dash # This less funky little regex just split on recognized spaces. E.g. # "Hello there -- you goof-ball, use the -b option!" # splits into # Hello/ /there/ /--/ /you/ /goof-ball,/ /use/ /the/ /-b/ /option!/ wordsep_simple_re = re.compile(r'(\s+)') # XXX this is not locale- or charset-aware -- string.lowercase # is US-ASCII only (and therefore English-only) sentence_end_re = re.compile(r'[a-z]' # lowercase letter r'[\.\!\?]' # sentence-ending punct. r'[\"\']?' # optional end-of-quote r'\Z') # end of chunk def __init__(self, width=70, initial_indent="", subsequent_indent="", expand_tabs=True, replace_whitespace=True, fix_sentence_endings=False, break_long_words=True, drop_whitespace=True, break_on_hyphens=True, use_hyphenator=None): self.width = width self.initial_indent = initial_indent self.subsequent_indent = subsequent_indent self.expand_tabs = expand_tabs self.replace_whitespace = replace_whitespace self.fix_sentence_endings = fix_sentence_endings self.break_long_words = break_long_words self.drop_whitespace = drop_whitespace self.break_on_hyphens = break_on_hyphens # -- Private methods ----------------------------------------------- # (possibly useful for subclasses to override) def _munge_whitespace(self, text): """_munge_whitespace(text : string) -> string Munge whitespace in text: expand tabs and convert all other whitespace characters to spaces. Eg. " foo\tbar\n\nbaz" becomes " foo bar baz". """ if self.expand_tabs: text = text.expandtabs() if self.replace_whitespace: text = text.translate(self.unicode_whitespace_trans) return text def _split(self, text): """_split(text : string) -> [string] Split the text to wrap into indivisible chunks. Chunks are not quite the same as words; see wrap_chunks() for full details. As an example, the text Look, goof-ball -- use the -b option! breaks into the following chunks: 'Look,', ' ', 'goof-', 'ball', ' ', '--', ' ', 'use', ' ', 'the', ' ', '-b', ' ', 'option!' if break_on_hyphens is True, or in: 'Look,', ' ', 'goof-ball', ' ', '--', ' ', 'use', ' ', 'the', ' ', '-b', ' ', option!' otherwise. """ if self.break_on_hyphens is True: chunks = self.wordsep_re.split(text) else: chunks = self.wordsep_simple_re.split(text) chunks = [c for c in chunks if c] return chunks def _fix_sentence_endings(self, chunks): """_fix_sentence_endings(chunks : [string]) Correct for sentence endings buried in 'chunks'. Eg. when the original text contains "... foo.\nBar ...", munge_whitespace() and split() will convert that to [..., "foo.", " ", "Bar", ...] which has one too few spaces; this method simply changes the one space to two. """ i = 0 pat = self.sentence_end_re while i < len(chunks)-1: if chunks[i+1] == " " and pat.search(chunks[i]): chunks[i+1] = " " i += 2 else: i += 1 def _handle_long_word(self, reversed_chunks, cur_line, cur_len, width): """_handle_long_word(chunks : [string], cur_line : [string], cur_len : int, width : int) Handle a chunk of text (most likely a word, not whitespace) that is too long to fit in any line. """ # Figure out when indent is larger than the specified width, and make # sure at least one character is stripped off on every pass if width < 1: space_left = 1 else: space_left = width - cur_len # If we're allowed to break long words, then do so: put as much # of the next chunk onto the current line as will fit. if self.break_long_words: cur_line.append(reversed_chunks[-1][:space_left]) reversed_chunks[-1] = reversed_chunks[-1][space_left:] # Otherwise, we have to preserve the long word intact. Only add # it to the current line if there's nothing already there -- # that minimizes how much we violate the width constraint. elif not cur_line: cur_line.append(reversed_chunks.pop()) # If we're not allowed to break long words, and there's already # text on the current line, do nothing. Next time through the # main loop of _wrap_chunks(), we'll wind up here again, but # cur_len will be zero, so the next line will be entirely # devoted to the long word that we can't handle right now. def _wrap_chunks(self, chunks): """_wrap_chunks(chunks : [string]) -> [string] Wrap a sequence of text chunks and return a list of lines of length 'self.width' or less. (If 'break_long_words' is false, some lines may be longer than this.) Chunks correspond roughly to words and the whitespace between them: each chunk is indivisible (modulo 'break_long_words'), but a line break can come between any two chunks. Chunks should not have internal whitespace; ie. a chunk is either all whitespace or a "word". Whitespace chunks will be removed from the beginning and end of lines, but apart from that whitespace is preserved. """ lines = [] if self.width <= 0: raise ValueError("invalid width %r (must be > 0)" % self.width) # Arrange in reverse order so items can be efficiently popped # from a stack of chucks. chunks.reverse() while chunks: # Start the list of chunks that will make up the current line. # cur_len is just the length of all the chunks in cur_line. cur_line = [] cur_len = 0 # Figure out which static string will prefix this line. if lines: indent = self.subsequent_indent else: indent = self.initial_indent # Maximum width for this line. width = self.width - len(indent) # First chunk on line is whitespace -- drop it, unless this # is the very beginning of the text (ie. no lines started yet). if self.drop_whitespace and chunks[-1].strip() == '' and lines: del chunks[-1] while chunks: l = len(chunks[-1]) # Can at least squeeze this chunk onto the current line. if cur_len + l <= width: cur_line.append(chunks.pop()) cur_len += l # Nope, this line is full. But try hyphenation, if hyphenator was passed. else: if self.use_hyphenator and (width - cur_len >= 2): hyphenated_chunk = self.use_hyphenator.wrap(chunks[-1], width - cur_len) if hyphenated_chunk: cur_line.append(hyphenated_chunk[0]) chunks[-1] = hyphenated_chunk[1] break # The current line is full, and the next chunk is too big to # fit on *any* line (not just this one). if chunks and len(chunks[-1]) > width: self._handle_long_word(chunks, cur_line, cur_len, width) # If the last chunk on this line is all whitespace, drop it. if self.drop_whitespace and cur_line and cur_line[-1].strip() == '': del cur_line[-1] # Convert current line back to a string and store it in list # of all lines (return value). if cur_line: lines.append(indent + ''.join(cur_line)) return lines # -- Public interface ---------------------------------------------- def wrap(self, text): """wrap(text : string) -> [string] Reformat the single paragraph in 'text' so it fits in lines of no more than 'self.width' columns, and return a list of wrapped lines. Tabs in 'text' are expanded with string.expandtabs(), and all other whitespace characters (including newline) are converted to space. """ text = self._munge_whitespace(text) chunks = self._split(text) if self.fix_sentence_endings: self._fix_sentence_endings(chunks) return self._wrap_chunks(chunks) def fill(self, text): """fill(text : string) -> string Reformat the single paragraph in 'text' to fit in lines of no more than 'self.width' columns, and return a new string containing the entire wrapped paragraph. """ return "\n".join(self.wrap(text)) # -- Convenience interface --------------------------------------------- def wrap(text, width=70, **kwargs): """Wrap a single paragraph of text, returning a list of wrapped lines. Reformat the single paragraph in 'text' so it fits in lines of no more than 'width' columns, and return a list of wrapped lines. By default, tabs in 'text' are expanded with string.expandtabs(), and all other whitespace characters (including newline) are converted to space. See TextWrapper class for available keyword args to customize wrapping behaviour. """ w = TextWrapper(width=width, **kwargs) return w.wrap(text) def fill(text, width=70, **kwargs): """Fill a single paragraph of text, returning a new string. Reformat the single paragraph in 'text' to fit in lines of no more than 'width' columns, and return a new string containing the entire wrapped paragraph. As with wrap(), tabs are expanded and other whitespace characters converted to space. See TextWrapper class for available keyword args to customize wrapping behaviour. """ w = TextWrapper(width=width, **kwargs) return w.fill(text) # -- Loosely related functionality ------------------------------------- _whitespace_only_re = re.compile('^[ \t]+$', re.MULTILINE) _leading_whitespace_re = re.compile('(^[ \t]*)(?:[^ \t\n])', re.MULTILINE) def dedent(text): """Remove any common leading whitespace from every line in `text`. This can be used to make triple-quoted strings line up with the left edge of the display, while still presenting them in the source code in indented form. Note that tabs and spaces are both treated as whitespace, but they are not equal: the lines " hello" and "\thello" are considered to have no common leading whitespace. (This behaviour is new in Python 2.5; older versions of this module incorrectly expanded tabs before searching for common leading whitespace.) """ # Look for the longest leading string of spaces and tabs common to # all lines. margin = None text = _whitespace_only_re.sub('', text) indents = _leading_whitespace_re.findall(text) for indent in indents: if margin is None: margin = indent # Current line more deeply indented than previous winner: # no change (previous winner is still on top). elif indent.startswith(margin): pass # Current line consistent with and no deeper than previous winner: # it's the new winner. elif margin.startswith(indent): margin = indent # Current line and previous winner have no common whitespace: # there is no margin. else: margin = "" break # sanity check (testing/debugging only) if 0 and margin: for line in text.split("\n"): assert not line or line.startswith(margin), \ "line = %r, margin = %r" % (line, margin) if margin: text = re.sub(r'(?m)^' + margin, '', text) return text if __name__ == "__main__": #print dedent("\tfoo\n\tbar") #print dedent(" \thello there\n \t how are you?") print(dedent("Hello there.\n This is indented.")) ./PyHyphen-1.0beta1/3.x/config.py0000666000175000017500000000007011502153146015710 0ustar takakitakakidefault_dict_path = '$path' default_repository = '$repo'./PyHyphen-1.0beta1/3.x/dictools.py0000666000175000017500000000713711546012506016300 0ustar takakitakaki# PyHyphen - hyphenation for Python # module: dictools ''' This module contains convenience functions to handle hyphenation dictionaries. ''' import hyphen, os, urllib.request, pickle, csv from io import BytesIO, StringIO from zipfile import ZipFile from . import config __all__ = ['install', 'uninstall', 'is_installed', 'list_installed', 'install_dict_info'] def list_installed(directory = config.default_dict_path): '''Return a list of strings containing language and country codes of the dictionaries installed in 'directory' (default as declared in config.py). Example: file name = 'hyph_en_US.dic'. Return value: ['en_US']''' return [d[5:-4] for d in os.listdir(directory) if (d.startswith('hyph_') and d.endswith('.dic'))] def is_installed(language, directory = config.default_dict_path): '''return True if 'directory' (default as declared in config.py) contains a dictionary file for 'language', False otherwise. By convention, 'language' should have the form 'll_CC'. Example: 'en_US' for US English. ''' return (language in list_installed(directory)) def install(language, directory = config.default_dict_path, repos = config.default_repository): ''' Download and install a dictionary file. language: a string of the form 'll_CC'. Example: 'en_US' for English, USA directory: the installation directory. Defaults to the value given in config.py. After installation this is the package root of 'hyphen' repos: the url of the dictionary repository. (Default: as declared in config.py; after installation this is the OpenOffice repository for dictionaries.). ''' if hyphen.dict_info and language in hyphen.dict_info: fn = hyphen.dict_info[language]['file_name'] else: fn = 'hyph_' + language + '.dic' url = ''.join((repos, fn)) s = urllib.request.urlopen(url).read() z = ZipFile(BytesIO(s)) if z.testzip(): raise IOError('The ZIP archive containing the dictionary is corrupt.') dic_filename = ''.join(('hyph_', language, '.dic')) dic_str = z.read(dic_filename) with open('/'.join((directory, dic_filename)), 'wb') as dest: dest.write(dic_str) def uninstall(language, directory = config.default_dict_path): ''' Uninstall the dictionary of the specified language. 'language': is by convention a string of the form 'll_CC' whereby ll is the language code and CC the country code. 'directory' (default: config.default_dict_path'. After installation of PyHyphen this is the package root of 'hyphen'.''' if hyphen.dict_info and language in hyphen.dict_info: file_path = ''.join((directory, '/', hyphen.dict_info[language]['name'], '.dic')) else: file_path = ''.join((directory, '/', 'hyph_', language, '.dic')) os.remove(file_path) def install_dict_info(save = True, directory = config.default_dict_path): '''Load the list of available dictionaries and store it locally.''' raw_bytes = urllib.request.urlopen('http://ftp.osuosl.org/pub/openoffice/contrib/dictionaries/hyphavail.lst').read() stream = StringIO(raw_bytes.decode()) # This looks clumpsy to me. But csd.dictreader does not accept bytes. d = csv.DictReader(stream, fieldnames = ['language_code', 'country_code', 'name', 'long_descr', 'file_name']) avail_dict = {} for i in d: key = '_'.join((i['language_code'], i['country_code'])) avail_dict[key] = i if save: file_path = directory + '/dict_info.pickle' with open(file_path, 'wb') as f: pickle.dump(avail_dict, f) return avail_dict ./PyHyphen-1.0beta1/3.x/__init__.py0000666000175000017500000002047111546025614016217 0ustar takakitakaki# Without prejudice to the license governing the use of # the Python standard module textwrap on which textwrap2 is based, # PyHyphen is licensed under the same terms as the underlying C library hyphen-2.3.1. # The essential parts of the license terms of libhyphen are quoted hereunder. # # # # # Extract from the license information of hyphen-2.3.1 library # ============================================================ # # # # GPL 2.0/LGPL 2.1/MPL 1.1 tri-license # # Software distributed under these licenses is distributed on an "AS IS" basis, # WITHOUT WARRANTY OF ANY KIND, either express or implied. See the licences # for the specific language governing rights and limitations under the licenses. # # The contents of this software may be used under the terms of # the GNU General Public License Version 2 or later (the "GPL"), or # the GNU Lesser General Public License Version 2.1 or later (the "LGPL", ''' hyphen - hyphenation for Python This package adds hyphenation functionality to the Python programming language. You may also wish to have a look at the module 'textwrap2' distributed jointly with this package. Contents 1. Overview 2. Code examples 1. Overview The gole of the PyHyphen project is to add hyphenation functionality to the Python programming language. PyHyphen consists of the package 'hyphen' and the module 'textwrap2' 1.1 The hyphen package contains: - at top level the definition of the class 'Hyphenator' each instance of which can hyphenate words using a dictionary compatible with the hyphenation feature of OpenOffice and Mozilla. The former class 'hyphenator' is deprecated as of version 0.10 as class names conventially begin with a capital letter. - the module dictools contains useful functions such as automatic downloading and - the module dictools contains useful functions automatically downloading and installing dictionaries from a configurable repository. By default, the OpenOffice repository is used. - config is a configuration file initialized at install time with default values for the directory where dictionaries are searched, and the repository for future downloads of dictionaries. - hyph_en_US.dic is the hyphenation dictionary for US English as found on the OpenOffice.org repository. - 'hnjmodule' is the C extension module that does all the ground work. It contains the C library hyphen-2.4. I cannot think of a reason to access the wrapper class exported by 'hnjmodule' directly rather than through the top level wrapper class hyphen.hyphenator. So 'hnjmodule' is disregarded by 'from hyphen import *'. Note that hyphenation dictionaries are invisible to the Python programmer. But each hyphenator object has a member 'language' which is a string showing the language of the dictionary in use. 1.2 The module 'textwrap2' This module is an enhanced though backwards compatible version of the module 'textwrap' known from the Python standard library. Not very surprisingly, it adds hyphenation functionality to 'textwrap'. 2. Code examples (see README.txt) ''' from . import hnj, config import pickle, os __all__ = ['dictools', 'Hyphenator'] # Try to load meta information on downloadable dictionaries: if os.path.exists(config.default_dict_path + '/dict_info.pickle'): dict_info = pickle.load(open(config.default_dict_path + '/dict_info.pickle', 'rb')) else: dict_info = None class Hyphenator: ''' Wrapper class around the class 'hnjmodule.hyphenator_'. It provides convenient access to the C library 'libhyphen'. ''' def __init__(self, language = 'en_US', lmin = 2, rmin = 2, compound_lmin = 2, compound_rmin = 2, directory = config.default_dict_path): ''' Return a hyphenator object initialized with a dictionary for the specified language. 'language' should by convention be a string of length 5 of the form "ll_CC" where ll is the language code and CC the country code. This is inspired by the file names of OpenOffice's hyphenation dictionaries. Example: 'en_NZ' for English / New Zealand Each class instance has an attribute 'info' of type dict containing metadata on its dictionary. If the module-level attribute dict_info is None or does not contain an entry for this dictionary, the info attribute of the Hyphenator instance will be None. There is also a 'language' attribute of type str which is deprecated since v1.0. lmin, rmin, compound_lmin and compound_rmin: set minimum number of chars to be cut off by hyphenation in single or compound words ''' if dict_info and language in dict_info: file_name = dict_info[language]['name'] + '.dic' else: file_name = language file_path = ''.join((directory, '/hyph_', language, '.dic')) self.__hyphenate__ = hnj.hyphenator_(file_path, lmin, rmin, compound_lmin, compound_rmin) self.language = language if dict_info: self.info = dict_info[language] else: self.info = None def pairs(self, word): ''' Hyphenate 'word' and return a list of lists of the form [['hy', 'phenation'], ['hyphen', 'ation']]. Return [], if len(word) < 4 or if word could not be hyphenated because * it is not encodable to the dictionary's encoding * * the hyphenator could not find a hyphenation point .''' mode = 1 if (len(word) < 4) or ('=' in word): return [] if not word.islower(): if (word.isupper()): mode += 4 word = word.lower() else: if (word[1:].islower()): mode += 2 word = word.lower() else: return [] # Now call the hyphenator catching the case that 'word' is not encodable # to the dictionary's encoding.'' try: return self.__hyphenate__.apply(word, mode) except UnicodeError: return [] def syllables(self, word): ''' Hyphenate 'word' and return a list of syllables. Return [], if len(word) < 4 or if word could not be hyphenated because * it is not encodable to the dictionary's encoding * the hyphenator could not find a hyphenation point . Results are inconsistent in case of non-standard hyphenation as a join of syllables would not yield the original word. ''' mode = 0 if (len(word) < 4) or ('=' in word): return [] if not word.islower(): if (word.isupper()): mode += 4 word = word.lower() else: if (word[1:].islower()): mode += 2 word = word.lower() else: return [] # Now call the hyphenator catching the case that 'word' is not encodable # to the dictionary's encoding.'' try: return self.__hyphenate__.apply(word, mode).split('=') except UnicodeError: return [] def wrap(self, word, width, hyphen = '-'): ''' Hyphenate 'word' and determine the best hyphenation fitting into 'width' characters. Return a list of the form ['hypen-', 'ation'] The '-' in the above example is the default value of 'hyphen'. It is added automatically and must fit into 'width' as well. If no hyphenation was found such that the shortest prefix (plus 'hyphen') fits into 'width', [] is returned. If the left part ends with a hyphen such as in 'Python-powered', no hyphen is appended. ''' p = self.pairs(word) max_chars = width - len(hyphen) while p: if p[-1][0].endswith(hyphen): cur_max_chars = max_chars + 1 else: cur_max_chars = max_chars if len(p[-1][0]) > cur_max_chars: p.pop() else: break if p: # Need to append a hyphen? if cur_max_chars == max_chars: p[-1][0] += hyphen return p[-1] else: return [] # The following ensures backwards compatibility with version 0.9.3 class hyphenator(Hyphenator): '''This class is deprecated. Use 'Hyphenator' instead.''' ./PyHyphen-1.0beta1/include/0000775000175000017500000000000011546766220015120 5ustar takakitakaki./PyHyphen-1.0beta1/include/hyphen.h0000666000175000017500000001265511474442376016602 0ustar takakitakaki/* Hyphen - hyphenation library using converted TeX hyphenation patterns * * (C) 1998 Raph Levien * (C) 2001 ALTLinux, Moscow * (C) 2006, 2007, 2008 László Németh * * This was part of libHnj library by Raph Levien. * * Peter Novodvorsky from ALTLinux cut hyphenation part from libHnj * to use it in OpenOffice.org. * * Non-standard and compound word hyphenation support by László Németh. * * License is the original LibHnj license: * * LibHnj is dual licensed under LGPL and MPL. Boilerplate for both * licenses follows. */ /* LibHnj - a library for high quality hyphenation and justification * Copyright (C) 1998 Raph Levien * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Library General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Library General Public License for more details. * * You should have received a copy of the GNU Library General Public * License along with this library; if not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * Boston, MA 02111-1307 USA. */ /* * The contents of this file are subject to the Mozilla Public License * Version 1.0 (the "MPL"); you may not use this file except in * compliance with the MPL. You may obtain a copy of the MPL at * http://www.mozilla.org/MPL/ * * Software distributed under the MPL is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the MPL * for the specific language governing rights and limitations under the * MPL. * */ #ifndef __HYPHEN_H__ #define __HYPHEN_H__ #ifdef __cplusplus extern "C" { #endif /* __cplusplus */ typedef struct _HyphenDict HyphenDict; typedef struct _HyphenState HyphenState; typedef struct _HyphenTrans HyphenTrans; #define MAX_CHARS 100 #define MAX_NAME 20 struct _HyphenDict { /* user options */ char lhmin; /* lefthyphenmin: min. hyph. distance from the left side */ char rhmin; /* righthyphenmin: min. hyph. distance from the right side */ char clhmin; /* min. hyph. distance from the left compound boundary */ char crhmin; /* min. hyph. distance from the right compound boundary */ char * nohyphen; /* comma separated list of characters or character sequences with forbidden hyphenation */ int nohyphenl; /* count of elements in nohyphen */ /* system variables */ int num_states; char cset[MAX_NAME]; int utf8; HyphenState *states; HyphenDict *nextlevel; }; struct _HyphenState { char *match; char *repl; signed char replindex; signed char replcut; int fallback_state; int num_trans; HyphenTrans *trans; }; struct _HyphenTrans { char ch; int new_state; }; HyphenDict *hnj_hyphen_load (const char *fn); void hnj_hyphen_free (HyphenDict *dict); /* obsolete, use hnj_hyphen_hyphenate2() or *hyphenate3() functions) */ int hnj_hyphen_hyphenate (HyphenDict *dict, const char *word, int word_size, char *hyphens); /* int hnj_hyphen_hyphenate2(): non-standard hyphenation. (It supports Catalan, Dutch, German, Hungarian, Norwegian, Swedish etc. orthography, see documentation.) input data: word: input word word_size: byte length of the input word hyphens: allocated character buffer (size = word_size + 5) hyphenated_word: allocated character buffer (size ~ word_size * 2) or NULL rep, pos, cut: pointers (point to the allocated and _zeroed_ buffers (size=word_size) or with NULL value) or NULL output data: hyphens: hyphenation vector (hyphenation points signed with odd numbers) hyphenated_word: hyphenated input word (hyphens signed with `='), optional (NULL input) rep: NULL (only standard hyph.), or replacements (hyphenation points signed with `=' in replacements); pos: NULL, or difference of the actual position and the beginning positions of the change in input words; cut: NULL, or counts of the removed characters of the original words at hyphenation, Note: rep, pos, cut are complementary arrays to the hyphens, indexed with the character positions of the input word. For example: Schiffahrt -> Schiff=fahrt, pattern: f1f/ff=f,1,2 output: rep[5]="ff=f", pos[5] = 1, cut[5] = 2 Note: hnj_hyphen_hyphenate2() can allocate rep, pos, cut (word_size length arrays): char ** rep = NULL; int * pos = NULL; int * cut = NULL; char hyphens[MAXWORDLEN]; hnj_hyphen_hyphenate2(dict, "example", 7, hyphens, NULL, &rep, &pos, &cut); See example in the source distribution. */ int hnj_hyphen_hyphenate2 (HyphenDict *dict, const char *word, int word_size, char * hyphens, char *hyphenated_word, char *** rep, int ** pos, int ** cut); /* like hnj_hyphen_hyphenate2, but with hyphenmin parameters */ /* lhmin: lefthyphenmin * rhmin: righthyphenmin * clhmin: compoundlefthyphemin * crhmin: compoundrighthyphenmin * (see documentation) */ int hnj_hyphen_hyphenate3 (HyphenDict *dict, const char *word, int word_size, char * hyphens, char *hyphword, char *** rep, int ** pos, int ** cut, int lhmin, int rhmin, int clhmin, int crhmin); #ifdef __cplusplus } #endif /* __cplusplus */ #endif /* __HYPHEN_H__ */ ./PyHyphen-1.0beta1/include/hnjalloc.h0000666000175000017500000000300710763742660017067 0ustar takakitakaki/* LibHnj is dual licensed under LGPL and MPL. Boilerplate for both * licenses follows. */ /* LibHnj - a library for high quality hyphenation and justification * Copyright (C) 1998 Raph Levien * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Library General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Library General Public License for more details. * * You should have received a copy of the GNU Library General Public * License along with this library; if not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * Boston, MA 02111-1307 USA. */ /* * The contents of this file are subject to the Mozilla Public License * Version 1.0 (the "MPL"); you may not use this file except in * compliance with the MPL. You may obtain a copy of the MPL at * http://www.mozilla.org/MPL/ * * Software distributed under the MPL is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the MPL * for the specific language governing rights and limitations under the * MPL. * */ /* wrappers for malloc */ void * hnj_malloc (int size); void * hnj_realloc (void *p, int size); void hnj_free (void *p);