commit c1202888810e29a0b9645c0ab1f504e8f9c62dde Author: Wolf Vollprecht Date: Sun Jul 6 22:35:24 2014 +0200 initial commit sidebar diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..8511393 --- /dev/null +++ b/.gitignore @@ -0,0 +1,6 @@ +build/lib.linux-x86_64-2.7 +build/scripts-2.7 +build/share +debian/uberwriter/DEBIAN +debian/uberwriter/opt +debian/uberwriter/usr diff --git a/.quickly b/.quickly new file mode 100644 index 0000000..40dacb3 --- /dev/null +++ b/.quickly @@ -0,0 +1,5 @@ +project = uberwriter +version = 12.08.1 +template = ubuntu-application +bzrbranch = lp:~w-vollprecht/uberwriter/quickly_trunk +lp_id = uberwriter diff --git a/ATTENTION b/ATTENTION new file mode 100644 index 0000000..e69de29 diff --git a/AUTHORS b/AUTHORS new file mode 100644 index 0000000..7c025dc --- /dev/null +++ b/AUTHORS @@ -0,0 +1,2 @@ +Copyright (C) 2012, Wolf Vollprecht +Copyright (C) 2012, Vova Kolobok diff --git a/COPYING b/COPYING new file mode 100644 index 0000000..94a9ed0 --- /dev/null +++ b/COPYING @@ -0,0 +1,674 @@ + GNU GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU General Public License is a free, copyleft license for +software and other kinds of works. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +the GNU General Public License is intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. We, the Free Software Foundation, use the +GNU General Public License for most of our software; it applies also to +any other work released this way by its authors. You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + To protect your rights, we need to prevent others from denying you +these rights or asking you to surrender the rights. Therefore, you have +certain responsibilities if you distribute copies of the software, or if +you modify it: responsibilities to respect the freedom of others. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must pass on to the recipients the same +freedoms that you received. You must make sure that they, too, receive +or can get the source code. And you must show them these terms so they +know their rights. + + Developers that use the GNU GPL protect your rights with two steps: +(1) assert copyright on the software, and (2) offer you this License +giving you legal permission to copy, distribute and/or modify it. + + For the developers' and authors' protection, the GPL clearly explains +that there is no warranty for this free software. For both users' and +authors' sake, the GPL requires that modified versions be marked as +changed, so that their problems will not be attributed erroneously to +authors of previous versions. + + Some devices are designed to deny users access to install or run +modified versions of the software inside them, although the manufacturer +can do so. This is fundamentally incompatible with the aim of +protecting users' freedom to change the software. The systematic +pattern of such abuse occurs in the area of products for individuals to +use, which is precisely where it is most unacceptable. Therefore, we +have designed this version of the GPL to prohibit the practice for those +products. If such problems arise substantially in other domains, we +stand ready to extend this provision to those domains in future versions +of the GPL, as needed to protect the freedom of users. + + Finally, every program is threatened constantly by software patents. +States should not allow patents to restrict development and use of +software on general-purpose computers, but in those that do, we wish to +avoid the special danger that patents applied to a free program could +make it effectively proprietary. To prevent this, the GPL assures that +patents cannot be used to render the program non-free. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Use with the GNU Affero General Public License. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU Affero General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the special requirements of the GNU Affero General Public License, +section 13, concerning interaction through a network will apply to the +combination as such. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . + +Also add information on how to contact you by electronic and paper mail. + + If the program does terminal interaction, make it output a short +notice like this when it starts in an interactive mode: + + Copyright (C) + This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, your program's commands +might be different; for a GUI interface, you would use an "about box". + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU GPL, see +. + + The GNU General Public License does not permit incorporating your program +into proprietary programs. If your program is a subroutine library, you +may consider it more useful to permit linking proprietary applications with +the library. If this is what you want to do, use the GNU Lesser General +Public License instead of this License. But first, please read +. diff --git a/bin/uberwriter b/bin/uberwriter new file mode 100755 index 0000000..949f723 --- /dev/null +++ b/bin/uberwriter @@ -0,0 +1,47 @@ +#!/usr/bin/python3 +# -*- Mode: Python; coding: utf-8; indent-tabs-mode: nil; tab-width: 4 -*- +### BEGIN LICENSE +# Copyright (C) 2012, Wolf Vollprecht +# This program is free software: you can redistribute it and/or modify it +# under the terms of the GNU General Public License version 3, as published +# by the Free Software Foundation. +# +# This program is distributed in the hope that it will be useful, but +# WITHOUT ANY WARRANTY; without even the implied warranties of +# MERCHANTABILITY, SATISFACTORY QUALITY, or FITNESS FOR A PARTICULAR +# PURPOSE. See the GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License along +# with this program. If not, see . +### END LICENSE + +### DO NOT EDIT THIS FILE ### + +import sys +import os + +import locale +locale.textdomain('uberwriter') + +# Add project root directory (enable symlink and trunk execution) +PROJECT_ROOT_DIRECTORY = os.path.abspath( + os.path.dirname(os.path.dirname(os.path.realpath(sys.argv[0])))) + +python_path = [] +if os.path.abspath(__file__).startswith('/opt'): + locale.bindtextdomain('uberwriter', '/opt/extras.ubuntu.com/uberwriter/share/locale') + syspath = sys.path[:] # copy to avoid infinite loop in pending objects + for path in syspath: + opt_path = path.replace('/usr', '/opt/extras.ubuntu.com/uberwriter') + python_path.insert(0, opt_path) + sys.path.insert(0, opt_path) + os.putenv("XDG_DATA_DIRS", "%s:%s" % ("/opt/extras.ubuntu.com/uberwriter/share/", os.getenv("XDG_DATA_DIRS", "/usr/local/share/:/usr/share/"))) +if (os.path.exists(os.path.join(PROJECT_ROOT_DIRECTORY, 'uberwriter')) + and PROJECT_ROOT_DIRECTORY not in sys.path): + python_path.insert(0, PROJECT_ROOT_DIRECTORY) + sys.path.insert(0, PROJECT_ROOT_DIRECTORY) +if python_path: + os.putenv('PYTHONPATH', "%s:%s" % (os.getenv('PYTHONPATH', ''), ':'.join(python_path))) # for subprocesses + +import uberwriter +uberwriter.main() diff --git a/bin/uberwriterc b/bin/uberwriterc new file mode 100644 index 0000000..8fc0996 Binary files /dev/null and b/bin/uberwriterc differ diff --git a/build/lib/uberwriter/AboutUberwriterDialog.py b/build/lib/uberwriter/AboutUberwriterDialog.py new file mode 100644 index 0000000..d576e53 --- /dev/null +++ b/build/lib/uberwriter/AboutUberwriterDialog.py @@ -0,0 +1,35 @@ +# -*- Mode: Python; coding: utf-8; indent-tabs-mode: nil; tab-width: 4 -*- +### BEGIN LICENSE +# Copyright (C) 2012, Wolf Vollprecht +# This program is free software: you can redistribute it and/or modify it +# under the terms of the GNU General Public License version 3, as published +# by the Free Software Foundation. +# +# This program is distributed in the hope that it will be useful, but +# WITHOUT ANY WARRANTY; without even the implied warranties of +# MERCHANTABILITY, SATISFACTORY QUALITY, or FITNESS FOR A PARTICULAR +# PURPOSE. See the GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License along +# with this program. If not, see . +### END LICENSE + +import locale +from locale import gettext as _ +locale.textdomain('uberwriter') + +import logging +logger = logging.getLogger('uberwriter') + +from uberwriter_lib.AboutDialog import AboutDialog + +# See uberwriter_lib.AboutDialog.py for more details about how this class works. +class AboutUberwriterDialog(AboutDialog): + __gtype_name__ = "AboutUberwriterDialog" + + def finish_initializing(self, builder): # pylint: disable=E1002 + """Set up the about dialog""" + super(AboutUberwriterDialog, self).finish_initializing(builder) + + # Code for other initialization actions should be added here. + diff --git a/build/lib/uberwriter/FixTable.py b/build/lib/uberwriter/FixTable.py new file mode 100644 index 0000000..7b64121 --- /dev/null +++ b/build/lib/uberwriter/FixTable.py @@ -0,0 +1,209 @@ +import re +from gi.repository import Gtk + +import logging +logger = logging.getLogger('uberwriter') +logger.critical("RASDAOD JKJD ASJD SJ") + +class FixTable(): + + def __init__(self, TextBuffer): + self.TextBuffer = TextBuffer + + @staticmethod + def create_seperator(widths, char): + """ + Generate a line of + and - as sepeartor + + Example: + >>> create_separarator([2, 4], '-') + '+----+------+' + """ + line = [] + + for w in widths: + line.append("+" + char * (w + 2)) + + line.append("+") + return ''.join(line) + + @staticmethod + def create_line(columns, widths): + """ + Crea una fila de la tabla separando los campos con un '|'. + + El argumento `columns` es una lista con las celdas que se + quieren imprimir y el argumento `widths` tiene el ancho + de cada columna. Si la columna es mas ancha que el texto + a imprimir se agregan espacios vacíos. + + Example + >>> create_line(['nombre', 'apellido'], [7, 10]) + '| nombre | apellido |' + """ + + line = zip(columns, widths) + result = [] + + for text, width in line: + spaces = " " * (width - len(text)) + text = "| " + text + spaces + " " + result.append(text) + + result.append("|") + return ''.join(result) + + @staticmethod + def create_table(content): + """Imprime una tabla en formato restructuredText. + + El argumento `content` tiene que ser una lista + de celdas. + + Example: + + >>> print create_table([['software', 'vesion'], ['python', '3.2'], + ['vim', '7.3']]) ++----------+--------+ +| software | vesion | ++==========+========+ +| python | 3.2 | ++----------+--------+ +| vim | 7.3 | ++----------+--------+ + """ + + # obtiene las columnas de toda la tabla. + columns = zip(*content) + # calcula el tamano maximo que debe tener cada columna. + # replace with len() + widths = [max([len(x) for x in i]) for i in columns] + + result = [] + + result.append(FixTable.create_seperator(widths, '-')) + print(content, widths) + result.append(FixTable.create_line(content[0], widths)) + result.append(FixTable.create_seperator(widths, '=')) + + for line in content[1:]: + result.append(FixTable.create_line(line, widths)) + result.append(FixTable.create_seperator(widths, '-')) + + return '\n'.join(result) + + @staticmethod + def are_in_a_table(current_line): + "Line in a table?" + return "|" in current_line or "+" in current_line + + @staticmethod + def are_in_a_paragraph(current_line): + "Line in a paragraph?" + return len(current_line.strip()) >= 1 + + def get_table_bounds(self, are_in_callback): + """ + Gets the row number where the table begins and ends. + are_in_callback argument must be a function +         indicating whether a particular line belongs or not +        to the table to be measured (or create). +        Returns two values ​​as a tuple + """ + top = 0 + + buf = self.TextBuffer + start_iter = buf.get_start_iter() + end_iter = buf.get_end_iter() + + text = self.TextBuffer.get_text(start_iter, end_iter, False).split('\n') + logger.debug(text) + length = len(text) + bottom = length - 1 + + insert_mark = self.TextBuffer.get_insert() + insert_iter = self.TextBuffer.get_iter_at_mark(insert_mark) + current_row_index = insert_iter.get_line() + + for a in range(current_row_index, top, -1): + if not are_in_callback(text[a]): + top = a + 1 + break + + for b in range(current_row_index, length): + if not are_in_callback(text[b]): + bottom = b - 1 + break + + return top, bottom + + @staticmethod + def remove_spaces(string): + """Remove unnecessary spaces""" + return re.sub("\s\s+", " ", string) + + @staticmethod + def create_separators_removing_spaces(string): + return re.sub("\s\s+", "|", string) + + @staticmethod + def extract_cells_as_list(string): + "Extrae el texto de una fila de tabla y lo retorna como una lista." + string = FixTable.remove_spaces(string) + return [item.strip() for item in string.split('|') if item] + + @staticmethod + def extract_table(text, top, bottom): + full_table_text = text[top:bottom] + # selecciona solamente las lineas que tienen celdas con texto. + only_text_lines = [x for x in full_table_text if '|' in x] + # extrae las celdas y descarta los separadores innecesarios. + return [FixTable.extract_cells_as_list(x) for x in only_text_lines] + + @staticmethod + def extract_words_as_lists(text, top, bottom): + "Genera una lista de palabras para crear una lista." + + lines = text[top:bottom + 1] + return [FixTable.create_separators_removing_spaces(line).split('|') for line in lines] + + def fix_table(self): + """ + Fix Table, so all columns have the same width (again) + + `initial_row` is a int idicationg the current row index + """ + + cursor_mark = self.TextBuffer.get_insert() + cursor_iter = self.TextBuffer.get_iter_at_mark(cursor_mark) + cursor_iter.set_line(cursor_iter.get_line()) + + end_line = cursor_iter.copy() + end_line.forward_to_line_end() + + + line_text = self.TextBuffer.get_text(cursor_iter, end_line, False) + if FixTable.are_in_a_table(line_text): + + # obtiene el indice donde comienza y termina la tabla. + r1, r2 = self.get_table_bounds(FixTable.are_in_a_table) + + logger.debug('asdasd ') + + # extrae de la tabla solo las celdas de texto + buf = self.TextBuffer + start_iter = buf.get_start_iter() + end_iter = buf.get_end_iter() + + text = self.TextBuffer.get_text(start_iter, end_iter, False).split('\n') + + table_as_list = FixTable.extract_table(text, r1, r2) + logger.debug(table_as_list) + # genera una nueva tabla tipo restructured text y la dibuja en el buffer. + table_content = FixTable.create_table(table_as_list) + logger.debug(table_content) + # Insert table back into Buffer ... + self.TextBuffer.insert(start_iter, table_content, -1) + else: + logger.debug("Not in a table") + print("Not in table") diff --git a/build/lib/uberwriter/FormatShortcuts.py b/build/lib/uberwriter/FormatShortcuts.py new file mode 100644 index 0000000..7a1f242 --- /dev/null +++ b/build/lib/uberwriter/FormatShortcuts.py @@ -0,0 +1,217 @@ +# -*- Mode: Python; coding: utf-8; indent-tabs-mode: nil; tab-width: 4 -*- +### BEGIN LICENSE +# Copyright (C) 2012, Wolf Vollprecht +# This program is free software: you can redistribute it and/or modify it +# under the terms of the GNU General Public License version 3, as published +# by the Free Software Foundation. +# +# This program is distributed in the hope that it will be useful, but +# WITHOUT ANY WARRANTY; without even the implied warranties of +# MERCHANTABILITY, SATISFACTORY QUALITY, or FITNESS FOR A PARTICULAR +# PURPOSE. See the GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License along +# with this program. If not, see . +### END LICENSE + + +import locale + +import re +from gi.repository import Gtk, Gdk # pylint: disable=E0611 +from gi.repository import Pango # pylint: disable=E0611 + +from locale import gettext as _ +locale.textdomain('uberwriter') + +from . MarkupBuffer import MarkupBuffer + +class FormatShortcuts(): + + def __init__(self, textbuffer, texteditor): + self.TextBuffer = textbuffer + self.TextEditor = texteditor + + def rule(self): + self.TextBuffer.insert_at_cursor("\n\n-------\n") + self.TextEditor.scroll_mark_onscreen(self.TextBuffer.get_insert()) + self.regex = MarkupBuffer.regex + + def bold(self): + self.apply_format("**") + + def italic(self): + self.apply_format("*") + + def apply_format(self, wrap = "*"): + if self.TextBuffer.get_has_selection(): + ## Find current highlighting + + (start, end) = self.TextBuffer.get_selection_bounds() + moved = False + if ( + start.get_offset() >= len(wrap) and + end.get_offset() <= self.TextBuffer.get_char_count() - len(wrap) + ): + moved = True + ext_start = start.copy() + ext_start.backward_chars(len(wrap)) + ext_end = end.copy() + ext_end.forward_chars(len(wrap)) + text = self.TextBuffer.get_text(ext_start, ext_end, True) + else: + text = self.TextBuffer.get_text(start, end, True) + + if moved and text.startswith(wrap) and text.endswith(wrap): + text = text[len(wrap):-len(wrap)] + new_text = text + self.TextBuffer.delete(ext_start, ext_end) + move_back = 0 + else: + if moved: + text = text[len(wrap):-len(wrap)] + new_text = text.lstrip().rstrip() + text = text.replace(new_text, wrap + new_text + wrap) + + self.TextBuffer.delete(start, end) + move_back = len(wrap) + + self.TextBuffer.insert_at_cursor(text) + text_length = len(new_text) + + else: + helptext = "" + if wrap == "*": + helptext = _("emphasized text") + elif wrap == "**": + helptext = _("strong text") + + self.TextBuffer.insert_at_cursor(wrap + helptext + wrap) + text_length = len(helptext) + move_back = len(wrap) + + cursor_mark = self.TextBuffer.get_insert() + cursor_iter = self.TextBuffer.get_iter_at_mark(cursor_mark) + cursor_iter.backward_chars(move_back) + self.TextBuffer.move_mark_by_name('selection_bound', cursor_iter) + cursor_iter.backward_chars(text_length) + self.TextBuffer.move_mark_by_name('insert', cursor_iter) + + def unordered_list_item(self): + helptext = _("List item") + text_length = len(helptext) + move_back = 0 + if self.TextBuffer.get_has_selection(): + (start, end) = self.TextBuffer.get_selection_bounds() + if start.starts_line(): + text = self.TextBuffer.get_text(start, end, False) + if text.startswith(("- ", "* ", "+ ")): + delete_end = start.forward_chars(2) + self.TextBuffer.delete(start, delete_end) + else: + self.TextBuffer.insert(start, "- ") + else: + move_back = 0 + cursor_mark = self.TextBuffer.get_insert() + cursor_iter = self.TextBuffer.get_iter_at_mark(cursor_mark) + + start_ext = cursor_iter.copy() + start_ext.backward_lines(3) + text = self.TextBuffer.get_text(cursor_iter, start_ext, False) + lines = text.splitlines() + + for line in reversed(lines): + if len(line) and line.startswith(("- ", "* ", "+ ")): + if cursor_iter.starts_line(): + self.TextBuffer.insert_at_cursor(line[:2] + helptext) + else: + self.TextBuffer.insert_at_cursor("\n" + line[:2] + helptext) + break + else: + if len(lines[-1]) == 0 and len(lines[-2]) == 0: + self.TextBuffer.insert_at_cursor("- " + helptext) + elif len(lines[-1]) == 0: + if cursor_iter.starts_line(): + self.TextBuffer.insert_at_cursor("- " + helptext) + else: + self.TextBuffer.insert_at_cursor("\n- " + helptext) + else: + self.TextBuffer.insert_at_cursor("\n\n- " + helptext) + break + + self.select_edit(move_back, text_length) + + def ordered_list_item(self): + pass + + def select_edit(self, move_back, text_length): + cursor_mark = self.TextBuffer.get_insert() + cursor_iter = self.TextBuffer.get_iter_at_mark(cursor_mark) + cursor_iter.backward_chars(move_back) + self.TextBuffer.move_mark_by_name('selection_bound', cursor_iter) + cursor_iter.backward_chars(text_length) + self.TextBuffer.move_mark_by_name('insert', cursor_iter) + self.TextEditor.scroll_mark_onscreen(self.TextBuffer.get_insert()) + + def above(self, linestart = ""): + if not cursor_iter.starts_line(): + return "" + else: + cursor_mark = self.TextBuffer.get_insert() + cursor_iter = self.TextBuffer.get_iter_at_mark(cursor_mark) + + start_ext = cursor_iter.copy() + start_ext.backward_lines(2) + text = self.TextBuffer.get_text(cursor_iter, start_ext, False) + lines = text.splitlines() + + #if line[-1].startswith + + def get_lines(self, cursor_iter): + + start_ext = cursor_iter.copy() + start_ext.backward_lines(2) + text = self.TextBuffer.get_text(cursor_iter, start_ext, False) + lines = text.splitlines() + + abs_line = cursor_iter.get_line() + + return reversed(lines) + + def heading(self, level = 0): + helptext = _("Heading") + before = "" + if self.TextBuffer.get_has_selection(): + (start, end) = self.TextBuffer.get_selection_bounds() + text = self.TextBuffer.get_text(start, end, False) + self.TextBuffer.delete(start, end) + else: + text = helptext + + cursor_mark = self.TextBuffer.get_insert() + cursor_iter = self.TextBuffer.get_iter_at_mark(cursor_mark) + + #lines = self.get_lines(cursor_iter) + + #if cursor_iter.starts_line(): + # if lines[1] != '': + # before = before + "\n" + #else: + # match = re.match(r'([\#]+ )(.+)', lines[0]) + # if match: + # if match.group(1): + # + # print match.group(0) + # if len(match.group(0)) < 6: + # before = before + "#" * (len(match.group(0)) + 1) + # else: + # before = before + "#" + # else: + # before = before + "\n\n" + # + # + # check_text = self.TextBuffer.get_text(start, cursor_iter, False).decode("utf-8") + # print check_text + + self.TextBuffer.insert_at_cursor("#" + " " + text) + self.select_edit(0, len(text)) diff --git a/build/lib/uberwriter/MarkupBuffer.py b/build/lib/uberwriter/MarkupBuffer.py new file mode 100644 index 0000000..f83c2a4 --- /dev/null +++ b/build/lib/uberwriter/MarkupBuffer.py @@ -0,0 +1,316 @@ +# -*- Mode: Python; coding: utf-8; indent-tabs-mode: nil; tab-width: 4 -*- +### BEGIN LICENSE +# Copyright (C) 2012, Wolf Vollprecht +# This program is free software: you can redistribute it and/or modify it +# under the terms of the GNU General Public License version 3, as published +# by the Free Software Foundation. +# +# This program is distributed in the hope that it will be useful, but +# WITHOUT ANY WARRANTY; without even the implied warranties of +# MERCHANTABILITY, SATISFACTORY QUALITY, or FITNESS FOR A PARTICULAR +# PURPOSE. See the GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License along +# with this program. If not, see . +### END LICENSE + +import re +from gi.repository import Gtk # pylint: disable=E0611 +from gi.repository import Pango # pylint: disable=E0611 + + +class MarkupBuffer(): + + def __init__(self, Parent, TextBuffer, base_leftmargin): + self.multiplier = 10 + self.parent = Parent + self.TextBuffer = TextBuffer + + # Styles + self.italic = self.TextBuffer.create_tag("italic", + style=Pango.Style.ITALIC) + + self.emph = self.TextBuffer.create_tag("emph", + weight=Pango.Weight.BOLD, + style=Pango.Style.NORMAL) + + self.bolditalic = self.TextBuffer.create_tag("bolditalic", + weight=Pango.Weight.BOLD, + style=Pango.Style.ITALIC) + + self.headline_two = self.TextBuffer.create_tag("headline_two", + weight=Pango.Weight.BOLD, + style=Pango.Style.NORMAL) + + self.normal_indent = self.TextBuffer.create_tag('normal_indent', indent=100) + + self.green_text = self.TextBuffer.create_tag( + "greentext", + foreground="#00364C" + ) + + self.grayfont = self.TextBuffer.create_tag('graytag', + foreground="gray") + + self.blackfont = self.TextBuffer.create_tag('blacktag', + foreground="#222") + + self.underline = self.TextBuffer.create_tag( + "underline", + underline=Pango.Underline.SINGLE + ) + + self.underline.set_property('weight', Pango.Weight.BOLD) + + self.strikethrough = self.TextBuffer.create_tag( + "strikethrough", + strikethrough=True + ) + + self.centertext = self.TextBuffer.create_tag( + "centertext", + justification=Gtk.Justification.CENTER + ) + + self.TextBuffer.apply_tag( + self.normal_indent, + self.TextBuffer.get_start_iter(), + self.TextBuffer.get_end_iter() + ) + + self.rev_leftmargin = [] + for i in range(0, 6): + name = "rev_marg_indent_left" + str(i) + self.rev_leftmargin.append(self.TextBuffer.create_tag(name)) + self.rev_leftmargin[i].set_property("left-margin", 90 - 10 * (i + 1)) + self.rev_leftmargin[i].set_property("indent", - 10 * (i + 1) - 10) + #self.leftmargin[i].set_property("background", "gray") + + self.leftmargin = [] + + for i in range(0, 6): + name = "marg_indent_left" + str(i) + self.leftmargin.append(self.TextBuffer.create_tag(name)) + self.leftmargin[i].set_property("left-margin", base_leftmargin + 10 + 10 * (i + 1)) + self.leftmargin[i].set_property("indent", - 10 * (i + 1) - 10) + + self.leftindent = [] + + for i in range(0, 15): + name = "indent_left" + str(i) + self.leftindent.append(self.TextBuffer.create_tag(name)) + self.leftindent[i].set_property("indent", - 10 * (i + 1) - 20) + + self.table_env = self.TextBuffer.create_tag('table_env') + self.table_env.set_property('wrap-mode', Gtk.WrapMode.NONE) + # self.table_env.set_property('font', 'Ubuntu Mono 13px') + self.table_env.set_property('pixels-above-lines', 0) + self.table_env.set_property('pixels-below-lines', 0) + regex = { + "ITALIC": re.compile(r"\*\w(.+?)\*| _\w(.+?)_ ", re.UNICODE), # *asdasd* // _asdasd asd asd_ + "STRONG": re.compile(r"\*{2}\w(.+?)\*{2}| [_]{2}\w(.+?)[_]{2} ", re.UNICODE), # **as das** // __asdasdasd asd ad a__ + "STRONGITALIC": re.compile(r"\*{3}\w(.+?)\*{3}| [_]{3}\w(.+?)[_]{3} "), + "BLOCKQUOTE": re.compile(r"^([\>]+ )", re.MULTILINE), + "STRIKETHROUGH": re.compile(r"~~[^ `~\n].+?~~"), + "LIST": re.compile(r"^[\-\*\+] ", re.MULTILINE), + "NUMERICLIST": re.compile(r"^((\d|[a-z]|\#)+[\.\)]) ", re.MULTILINE), + "INDENTEDLIST": re.compile(r"^(\t{1,6})((\d|[a-z]|\#)+[\.\)]|[\-\*\+]) ", re.MULTILINE), + "HEADINDICATOR": re.compile(r"^(#{1,6}) ", re.MULTILINE), + "HEADLINE": re.compile(r"^(#{1,6} [^\n]+)", re.MULTILINE), + "HEADLINE_TWO": re.compile(r"^\w.+\n[\=\-]{3,}", re.MULTILINE), + "MATH": re.compile(r"[\$]{1,2}([^` ].+?[^`\\ ])[\$]{1,2}"), + "HORIZONTALRULE": re.compile(r"(\n\n[\*\-]{3,}\n)"), + "TABLE": re.compile(r"^[\-\+]{5,}\n(.+?)\n[\-\+]{5,}\n", re.DOTALL), + "LINK": re.compile(r"\(http(.+?)\)") + } + + def markup_buffer(self, mode=0): + buf = self.TextBuffer + + # Modes: + # 0 -> start to end + # 1 -> around the cursor + # 2 -> n.d. + + if mode == 0: + context_start = buf.get_start_iter() + context_end = buf.get_end_iter() + context_offset = 0 + elif mode == 1: + cursor_mark = buf.get_insert() + context_start = buf.get_iter_at_mark(cursor_mark) + context_start.backward_lines(3) + context_end = buf.get_iter_at_mark(cursor_mark) + context_end.forward_lines(2) + context_offset = context_start.get_offset() + + text = buf.get_slice(context_start, context_end, False) + + self.TextBuffer.remove_tag(self.italic, context_start, context_end) + + matches = re.finditer(self.regex["ITALIC"], text) + for match in matches: + startIter = buf.get_iter_at_offset(context_offset + match.start()) + endIter = buf.get_iter_at_offset(context_offset + match.end()) + self.TextBuffer.apply_tag(self.italic, startIter, endIter) + + self.TextBuffer.remove_tag(self.emph, context_start, context_end) + + matches = re.finditer(self.regex["STRONG"], text) + for match in matches: + startIter = buf.get_iter_at_offset(context_offset + match.start()) + endIter = buf.get_iter_at_offset(context_offset + match.end()) + self.TextBuffer.apply_tag(self.emph, startIter, endIter) + + matches = re.finditer(self.regex["STRONGITALIC"], text) + for match in matches: + startIter = buf.get_iter_at_offset(context_offset + match.start()) + endIter = buf.get_iter_at_offset(context_offset + match.end()) + self.TextBuffer.apply_tag(self.bolditalic, startIter, endIter) + + self.TextBuffer.remove_tag(self.strikethrough, context_start, context_end) + + matches = re.finditer(self.regex["STRIKETHROUGH"], text) + for match in matches: + startIter = buf.get_iter_at_offset(context_offset + match.start()) + endIter = buf.get_iter_at_offset(context_offset + match.end()) + self.TextBuffer.apply_tag(self.strikethrough, startIter, endIter) + + self.TextBuffer.remove_tag(self.green_text, context_start, context_end) + + matches = re.finditer(self.regex["MATH"], text) + for match in matches: + startIter = buf.get_iter_at_offset(context_offset + match.start()) + endIter = buf.get_iter_at_offset(context_offset + match.end()) + self.TextBuffer.apply_tag(self.green_text, startIter, endIter) + + for margin in self.rev_leftmargin: + self.TextBuffer.remove_tag(margin, context_start, context_end) + + matches = re.finditer(self.regex["LIST"], text) + for match in matches: + startIter = buf.get_iter_at_offset(context_offset + match.start()) + endIter = buf.get_iter_at_offset(context_offset + match.end()) + self.TextBuffer.apply_tag(self.rev_leftmargin[0], startIter, endIter) + + matches = re.finditer(self.regex["NUMERICLIST"], text) + for match in matches: + startIter = buf.get_iter_at_offset(context_offset + match.start()) + endIter = buf.get_iter_at_offset(context_offset + match.end()) + index = len(match.group(1)) - 1 + if index < len(self.rev_leftmargin): + margin = self.rev_leftmargin[index] + self.TextBuffer.apply_tag(margin, startIter, endIter) + + matches = re.finditer(self.regex["BLOCKQUOTE"], text) + for match in matches: + startIter = buf.get_iter_at_offset(context_offset + match.start()) + endIter = buf.get_iter_at_offset(context_offset + match.end()) + index = len(match.group(1)) - 2 + if index < len(self.leftmargin): + self.TextBuffer.apply_tag(self.leftmargin[index], startIter, endIter) + + for leftindent in self.leftindent: + self.TextBuffer.remove_tag(leftindent, context_start, context_end) + + matches = re.finditer(self.regex["INDENTEDLIST"], text) + for match in matches: + startIter = buf.get_iter_at_offset(context_offset + match.start()) + endIter = buf.get_iter_at_offset(context_offset + match.end()) + index = (len(match.group(1)) - 1) * 2 + len(match.group(2)) + if index < len(self.leftindent): + self.TextBuffer.apply_tag(self.leftindent[index], startIter, endIter) + + matches = re.finditer(self.regex["HEADINDICATOR"], text) + for match in matches: + startIter = buf.get_iter_at_offset(context_offset + match.start()) + endIter = buf.get_iter_at_offset(context_offset + match.end()) + index = len(match.group(1)) - 1 + if index < len(self.rev_leftmargin): + margin = self.rev_leftmargin[index] + self.TextBuffer.apply_tag(margin, startIter, endIter) + + matches = re.finditer(self.regex["HORIZONTALRULE"], text) + rulecontext = context_start.copy() + rulecontext.forward_lines(3) + self.TextBuffer.remove_tag(self.centertext, rulecontext, context_end) + + for match in matches: + startIter = buf.get_iter_at_offset(context_offset + match.start()) + startIter.forward_chars(2) + endIter = buf.get_iter_at_offset(context_offset + match.end()) + self.TextBuffer.apply_tag(self.centertext, startIter, endIter) + + matches = re.finditer(self.regex["HEADLINE"], text) + for match in matches: + startIter = buf.get_iter_at_offset(context_offset + match.start()) + endIter = buf.get_iter_at_offset(context_offset + match.end()) + self.TextBuffer.apply_tag(self.emph, startIter, endIter) + + matches = re.finditer(self.regex["HEADLINE_TWO"], text) + self.TextBuffer.remove_tag(self.headline_two, rulecontext, context_end) + for match in matches: + startIter = buf.get_iter_at_offset(context_offset + match.start()) + endIter = buf.get_iter_at_offset(context_offset + match.end()) + self.TextBuffer.apply_tag(self.headline_two, startIter, endIter) + + matches = re.finditer(self.regex["TABLE"], text) + for match in matches: + startIter = buf.get_iter_at_offset(context_offset + match.start()) + endIter = buf.get_iter_at_offset(context_offset + match.end()) + self.TextBuffer.apply_tag(self.table_env, startIter, endIter) + + if self.parent.focusmode: + self.focusmode_highlight() + + def focusmode_highlight(self): + self.TextBuffer.apply_tag(self.grayfont, + self.TextBuffer.get_start_iter(), + self.TextBuffer.get_end_iter()) + + self.TextBuffer.remove_tag(self.blackfont, + self.TextBuffer.get_start_iter(), + self.TextBuffer.get_end_iter()) + + cursor = self.TextBuffer.get_mark("insert") + cursor_iter = self.TextBuffer.get_iter_at_mark(cursor) + + end_sentence = cursor_iter.copy() + end_sentence.forward_sentence_end() + + end_line = cursor_iter.copy() + end_line.forward_to_line_end() + + comp = end_line.compare(end_sentence) + # if comp < 0, end_line is BEFORE end_sentence + if comp <= 0: + end_sentence = end_line + + start_sentence = cursor_iter.copy() + start_sentence.backward_sentence_start() + + self.TextBuffer.apply_tag(self.blackfont, + start_sentence, end_sentence) + + def set_multiplier(self, multiplier): + self.multiplier = multiplier + + def recalculate(self, lm): + multiplier = self.multiplier + for i in range(0, 6): + self.rev_leftmargin[i].set_property("left-margin", (lm - multiplier) - multiplier * (i + 1)) + self.rev_leftmargin[i].set_property("indent", - multiplier * (i + 1) - multiplier) + + for i in range(0, 6): + self.leftmargin[i].set_property("left-margin", (lm - multiplier) + multiplier + multiplier * (i + 1)) + self.leftmargin[i].set_property("indent", - (multiplier - 1) * (i + 1) - multiplier) + + def dark_mode(self, active=False): + if active: + self.green_text.set_property("foreground", "#FA5B0F") + self.grayfont.set_property("foreground", "#666") + self.blackfont.set_property("foreground", "#CCC") + else: + self.green_text.set_property("foreground", "#00364C") + self.grayfont.set_property("foreground", "gray") + self.blackfont.set_property("foreground", "#222") diff --git a/build/lib/uberwriter/UberwriterAdvancedExportDialog.py b/build/lib/uberwriter/UberwriterAdvancedExportDialog.py new file mode 100644 index 0000000..bc36e20 --- /dev/null +++ b/build/lib/uberwriter/UberwriterAdvancedExportDialog.py @@ -0,0 +1,255 @@ +# -*- Mode: Python; coding: utf-8; indent-tabs-mode: nil; tab-width: 4 -*- +### BEGIN LICENSE +# Copyright (C) 2012, Wolf Vollprecht +# This program is free software: you can redistribute it and/or modify it +# under the terms of the GNU General Public License version 3, as published +# by the Free Software Foundation. +# +# This program is distributed in the hope that it will be useful, but +# WITHOUT ANY WARRANTY; without even the implied warranties of +# MERCHANTABILITY, SATISFACTORY QUALITY, or FITNESS FOR A PARTICULAR +# PURPOSE. See the GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License along +# with this program. If not, see . +### END LICENSE + +from gi.repository import Gtk +import os +import subprocess +import locale +from locale import gettext as _ +locale.textdomain('uberwriter') + +import logging +logger = logging.getLogger('uberwriter') + +from uberwriter_lib.AdvancedExportDialog import AdvancedExportDialog + +# See uberwriter_lib.AboutDialog.py for more details about how this class works. +class UberwriterAdvancedExportDialog(AdvancedExportDialog): + __gtype_name__ = "UberwriterAdvancedExportDialog" + + def finish_initializing(self, builder): # pylint: disable=E1002 + """Set up the about dialog""" + super(UberwriterAdvancedExportDialog, self).finish_initializing(builder) + + # Code for other initialization actions should be added here. + + self.builder.get_object("highlight_style").set_active(0) + + format_store = Gtk.ListStore(int, str) + for fmt_id in self.formats_dict: + format_store.append([fmt_id, self.formats_dict[fmt_id]["name"]]) + self.format_field = builder.get_object('choose_format') + self.format_field.set_model(format_store) + + format_renderer = Gtk.CellRendererText() + self.format_field.pack_start(format_renderer, True) + self.format_field.add_attribute(format_renderer, "text", 1) + self.format_field.set_active(0) + self.show_all() + + formats_dict = { + 1: { + "name": "LaTeX Source", + "ext": "tex", + "to": "latex" + }, + 2: { + "name": "LaTeX PDF", + "ext": "pdf", + "to": "pdf" + }, + 3: { + "name": "LaTeX beamer slide show Source .tex", + "ext": "tex", + "to": "beamer" + }, + 4: { + "name": "LaTeX beamer slide show PDF", + "ext": "pdf", + "to": "beamer" + }, + 5: { + "name": "HTML", + "ext": "html", + "to": "html" + }, + 6: { + "name": "Textile", + "ext": "txt", + "to": "textile" + }, + 7: { + "name": "OpenOffice text document", + "ext": "odt", + "to": "odt" + }, + 8: { + "name": "Word docx", + "ext": "docx", + "to": "docx" + }, + 9: { + "name": "reStructuredText txt", + "ext": "txt", + "to": "rst" + }, + 10: { + "name": "ConTeXt tex", + "ext": "tex", + "to": "context" + }, + 11: { + "name": "groff man", + "ext": "man", + "to": "man" + }, + 12: { + "name": "MediaWiki markup", + "ext": "txt", + "to": "mediawiki" + }, + 13: { + "name": "OpenDocument XML", + "ext": "xml", + "to": "opendocument" + }, + 14: { + "name": "OpenDocument XML", + "ext": "texi", + "to": "texinfo" + }, + 15: { + "name": "Slidy HTML and javascript slide show", + "ext": "html", + "to": "slidy" + }, + 16: { + "name": "Slideous HTML and javascript slide show", + "ext": "html", + "to": "slideous" + }, + 17: { + "name": "HTML5 + javascript slide show", + "ext": "html", + "to": "dzslides" + }, + 18: { + "name": "S5 HTML and javascript slide show", + "ext": "html", + "to": "s5" + }, + 19: { + "name": "EPub electronic publication", + "ext": "epub", + "to": "epub" + }, + 20: { + "name": "RTF Rich Text Format", + "ext": "rtf", + "to": "rtf" + } + + } + + def advanced_export(self, text = ""): + tree_iter = self.format_field.get_active_iter() + if tree_iter != None: + model = self.format_field.get_model() + row_id, name = model[tree_iter][:2] + + fmt = self.formats_dict[row_id] + logger.info(fmt) + filechooser = Gtk.FileChooserDialog( + "Export as %s" % fmt["name"], + self, + Gtk.FileChooserAction.SAVE, + (Gtk.STOCK_CANCEL, Gtk.ResponseType.CANCEL, + Gtk.STOCK_SAVE, Gtk.ResponseType.OK) + ) + + filechooser.set_do_overwrite_confirmation(True) + + response = filechooser.run() + if response == Gtk.ResponseType.OK: + filename = filechooser.get_filename() + filechooser.destroy() + else: + filechooser.destroy() + return + + output_dir = os.path.abspath(os.path.join(filename, os.path.pardir)) + + basename = os.path.basename(filename) + + args = ['pandoc', '--from=markdown'] + + to = "--to=%s" % fmt["to"] + + if basename.endswith("." + fmt["ext"]): + output_file = "--output=%s" % basename + else: + output_file = "--output=%s.%s" % (basename, fmt["ext"]) + + if self.builder.get_object("toc").get_active(): + args.append('--toc') + if self.builder.get_object("normalize").get_active(): + args.append('--normalize') + if self.builder.get_object("smart").get_active(): + args.append('--smart') + + if self.builder.get_object("highlight").get_active == False: + args.append('--no-highlight') + else: + hs = self.builder.get_object("highlight_style").get_active_text() + args.append("--highlight-style=%s" % hs) + + if self.builder.get_object("standalone").get_active(): + args.append("--standalone") + + if self.builder.get_object("number_sections").get_active(): + args.append("--number-sections") + + if self.builder.get_object("strict").get_active(): + args.append("--strict") + + if self.builder.get_object("incremental").get_active(): + args.append("--incremental") + + if self.builder.get_object("self_contained").get_active(): + args.append("--self-contained") + + if self.builder.get_object("html5").get_active(): + if fmt["to"] == "html": + to = "--to=%s" % "html5" + + # Pandoc can't handle verbose -t pdf (#571) + + if fmt["to"] != "pdf": + args.append(to) + + css_uri = self.builder.get_object("css_filechooser").get_uri() + if css_uri: + if css_uri.startswith("file://"): + css_uri = css_uri[7:] + args.append("--css=%s" % css_uri) + + bib_uri = self.builder.get_object("bib_filechooser").get_uri() + if bib_uri: + if bib_uri.startswith("file://"): + bib_uri = bib_uri[7:] + args.append("--bibliography=%s" % bib_uri) + + + args.append(output_file) + + logger.info(args) + + p = subprocess.Popen(args, stdin=subprocess.PIPE, + stdout=subprocess.PIPE, cwd=output_dir) + + output = p.communicate(text)[0] + + return filename \ No newline at end of file diff --git a/build/lib/uberwriter/UberwriterInlinePreview.py b/build/lib/uberwriter/UberwriterInlinePreview.py new file mode 100644 index 0000000..d32584e --- /dev/null +++ b/build/lib/uberwriter/UberwriterInlinePreview.py @@ -0,0 +1,288 @@ +# -*- Mode: Python; coding: utf-8; indent-tabs-mode: nil; tab-width: 4 -*- +### BEGIN LICENSE +# Copyright (C) 2012, Wolf Vollprecht +# This program is free software: you can redistribute it and/or modify it +# under the terms of the GNU General Public License version 3, as published +# by the Free Software Foundation. +# +# This program is distributed in the hope that it will be useful, but +# WITHOUT ANY WARRANTY; without even the implied warranties of +# MERCHANTABILITY, SATISFACTORY QUALITY, or FITNESS FOR A PARTICULAR +# PURPOSE. See the GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License along +# with this program. If not, see . +### END LICENSE + +import re +import http.client +import urllib +from urllib.error import URLError, HTTPError +import webbrowser +import locale +import subprocess +import tempfile + +import threading + +from gi.repository import Gtk, Gdk, GdkPixbuf, GObject +from uberwriter_lib import LatexToPNG + +from .FixTable import FixTable + +from .MarkupBuffer import MarkupBuffer + +from locale import gettext as _ +locale.textdomain('uberwriter') + +import logging +logger = logging.getLogger('uberwriter') + +GObject.threads_init() # Still needed? + +# TODO: +# - Don't insert a span with id, it breaks the text to often +# Would be better to search for the nearest title and generate +# A jumping URL from that (for preview) +# Also, after going to preview, set cursor back to where it was + +def check_url(url, item, spinner): + logger.debug("thread started, checking url") + error = False + try: + response = urllib.request.urlopen(url) + except URLError as e: + error = True + text = "Error! Reason: %s" % e.reason + + if not error: + if (response.code / 100) >= 4: + logger.debug("Website not available") + text = _("Website is not available") + else: + text = _("Website is available") + logger.debug("Response: %s" % text) + spinner.destroy() + item.set_label(text) + + +def get_web_thumbnail(url, item, spinner): + logger.debug("thread started, generating thumb") + + # error = False + + filename = tempfile.mktemp(suffix='.png') + thumb_size = '256' # size can only be 32, 64, 96, 128 or 256! + args = ['gnome-web-photo', '--mode=thumbnail', '-s', thumb_size, url, filename] + p = subprocess.Popen(args, stdin=subprocess.PIPE, stdout=subprocess.PIPE) + output = p.communicate()[0] + + image = Gtk.Image.new_from_file(filename) + image.show() + + # if not error: + # if (response.code / 100) >= 4: + # logger.debug("Website not available") + # text = _("Website is not available") + # else: + # text = _("Website is available") + + spinner.destroy() + item.add(image) + item.show() + + +class UberwriterInlinePreview(): + + def __init__(self, view, text_buffer): + self.TextView = view + self.TextBuffer = text_buffer + self.LatexConverter = LatexToPNG.LatexToPNG() + cursor_mark = self.TextBuffer.get_insert() + cursor_iter = self.TextBuffer.get_iter_at_mark(cursor_mark) + self.ClickMark = self.TextBuffer.create_mark('click', cursor_iter) + # Events for popup menu + self.TextView.connect_after('populate-popup', self.populate_popup) + self.TextView.connect_after('popup-menu', self.move_popup) + self.TextView.connect('button-press-event', self.click_move_button) + + def click_move_button(self, widget, event): + if event.button == 3: + x, y = self.TextView.window_to_buffer_coords(2, + int(event.x), + int(event.y)) + self.TextBuffer.move_mark(self.ClickMark, + self.TextView.get_iter_at_location(x, y)) + + def fix_table(self, widget, data=None): + logger.debug('fixing that table') + f = FixTable(self.TextBuffer) + f.fix_table() + + def populate_popup(self, editor, menu, data=None): + + item = Gtk.MenuItem.new() + item.set_name("PreviewMenuItem") + separator = Gtk.SeparatorMenuItem.new() + + table_item = Gtk.MenuItem.new() + table_item.set_label('Fix that table') + + table_item.connect('activate', self.fix_table) + table_item.show() + menu.prepend(table_item) + menu.show() + + start_iter = self.TextBuffer.get_iter_at_mark(self.ClickMark) + # Line offset of click mark + line_offset = start_iter.get_line_offset() + end_iter = start_iter.copy() + start_iter.set_line_offset(0) + end_iter.forward_to_line_end() + + text = self.TextBuffer.get_text(start_iter, end_iter, False) + + math = MarkupBuffer.regex["MATH"] + link = MarkupBuffer.regex["LINK"] + + footnote = re.compile('\[\^([^\s]+?)\]') + image = re.compile("!\[(.+?)\]\((.+?)\)") + + buf = self.TextBuffer + context_offset = 0 + + matchlist = [] + + found_match = False + + matches = re.finditer(math, text) + for match in matches: + logger.debug(match.group(1)) + if match.start() < line_offset and match.end() > line_offset: + success, result = self.LatexConverter.generatepng(match.group(1)) + if success: + image = Gtk.Image.new_from_file(result) + image.show() + item.add(image) + item.set_property('width-request', 50) + else: + label = Gtk.Label() + msg = 'Formula looks incorrect:\n' + result + label.set_alignment(0.0, 0.5) + label.set_text(msg) + label.show() + item.add(label) + item.show() + menu.prepend(separator) + separator.show() + menu.prepend(item) + menu.show() + found_match = True + break + + if not found_match: + # Links + matches = re.finditer(link, text) + for match in matches: + if match.start() < line_offset and match.end() > line_offset: + text = text[text.find("http://"):-1] + + item.connect("activate", lambda w: webbrowser.open(text)) + + logger.debug(text) + + statusitem = Gtk.MenuItem.new() + statusitem.show() + + spinner = Gtk.Spinner.new() + spinner.start() + statusitem.add(spinner) + spinner.show() + + thread = threading.Thread(target=check_url, + args=(text, statusitem, spinner)) + thread.start() + + webphoto_item = Gtk.MenuItem.new() + webphoto_item.show() + spinner_2 = Gtk.Spinner.new() + spinner_2.start() + webphoto_item.add(spinner_2) + spinner_2.show() + + thread_image = threading.Thread(target=get_web_thumbnail, + args=(text, webphoto_item, spinner_2)) + + thread_image.start() + + item.set_label(_("Open Link in Webbrowser")) + item.show() + + menu.prepend(separator) + separator.show() + + menu.prepend(webphoto_item) + menu.prepend(statusitem) + menu.prepend(item) + menu.show() + + + found_match = True + break + + if not found_match: + matches = re.finditer(image, text) + for match in matches: + if match.start() < line_offset and match.end() > line_offset: + path = match.group(2) + if path.startswith("file://"): + path = path[7:] + logger.info(path) + pb = GdkPixbuf.Pixbuf.new_from_file_at_size(path, 400, 300) + image = Gtk.Image.new_from_pixbuf(pb) + image.show() + item.add(image) + item.set_property('width-request', 50) + item.show() + menu.prepend(separator) + separator.show() + menu.prepend(item) + menu.show() + found_match = True + break + + if not found_match: + matches = re.finditer(footnote, text) + for match in matches: + if match.start() < line_offset and match.end() > line_offset: + logger.debug(match.group(1)) + footnote_match = re.compile("\[\^" + match.group(1) + "\]: (.+(?:\n|\Z)(?:^[\t].+(?:\n|\Z))*)", re.MULTILINE) + replace = re.compile("^\t", re.MULTILINE) + start, end = self.TextBuffer.get_bounds() + fn_match = re.search(footnote_match, self.TextBuffer.get_text(start, end, False)) + label = Gtk.Label() + label.set_alignment(0.0, 0.5) + logger.debug(fn_match) + if fn_match: + result = re.sub(replace, "", fn_match.group(1)) + if result.endswith("\n"): + result = result[:-1] + else: + result = _("No matching footnote found") + label.set_max_width_chars(40) + label.set_line_wrap(True) + label.set_text(result) + label.show() + item.add(label) + item.show() + + menu.prepend(separator) + separator.show() + menu.prepend(item) + menu.show() + found_match = True + break + return + + def move_popup(self): + pass diff --git a/build/lib/uberwriter/UberwriterSearchAndReplace.py b/build/lib/uberwriter/UberwriterSearchAndReplace.py new file mode 100644 index 0000000..6db1380 --- /dev/null +++ b/build/lib/uberwriter/UberwriterSearchAndReplace.py @@ -0,0 +1,150 @@ +# -*- Mode: Python; coding: utf-8; indent-tabs-mode: nil; tab-width: 4 -*- +### BEGIN LICENSE +# Copyright (C) 2012, Wolf Vollprecht +# This program is free software: you can redistribute it and/or modify it +# under the terms of the GNU General Public License version 3, as published +# by the Free Software Foundation. +# +# This program is distributed in the hope that it will be useful, but +# WITHOUT ANY WARRANTY; without even the implied warranties of +# MERCHANTABILITY, SATISFACTORY QUALITY, or FITNESS FOR A PARTICULAR +# PURPOSE. See the GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License along +# with this program. If not, see . +### END LICENSE + +import os, re +import subprocess +from gi.repository import Gtk, Gdk +import time +# from plugins import plugins + +import logging +logger = logging.getLogger('uberwriter') + +class UberwriterSearchAndReplace(): + """ + Adds (regex) search and replace functionality to + uberwriter + """ + def __init__(self, parentwindow): + self.parentwindow = parentwindow + self.box = parentwindow.builder.get_object("searchreplaceholder") + self.searchentry = parentwindow.builder.get_object("searchentrybox") + self.searchentry.connect('changed', self.search) + self.searchentry.connect('activate', self.scrolltonext) + + self.open_replace_button = parentwindow.builder.get_object("replace") + self.open_replace_button.connect("toggled", self.toggle_replace) + + self.textbuffer = parentwindow.TextBuffer + self.texteditor = parentwindow.TextEditor + + self.nextbutton = parentwindow.builder.get_object("next_result") + self.prevbutton = parentwindow.builder.get_object("previous_result") + self.regexbutton = parentwindow.builder.get_object("regex") + self.casesensitivebutton = parentwindow.builder.get_object("case_sensitive") + + self.replacebox = parentwindow.builder.get_object("replacebox") + self.replacebox.hide() + self.replace_one_button = parentwindow.builder.get_object("replace_one") + self.replace_all_button = parentwindow.builder.get_object("replace_all") + self.replaceentry = parentwindow.builder.get_object("replaceentrybox") + + self.replace_all_button.connect('clicked', self.replace_all) + self.replace_one_button.connect('clicked', self.replace_clicked) + self.replaceentry.connect('activate', self.replace_clicked) + + self.nextbutton.connect('clicked', self.scrolltonext) + self.prevbutton.connect('clicked', self.scrolltoprev) + self.regexbutton.connect('toggled', self.search) + self.casesensitivebutton.connect('toggled', self.search) + self.highlight = self.textbuffer.create_tag('search_highlight', + background="yellow") + + def toggle_replace(self, widget, data=None): + if widget.get_active(): + self.replacebox.show_all() + else: + self.replacebox.hide() + + def toggle_search(self, widget=None, data=None): + """ + show search box + """ + if self.box.get_visible(): + self.box.hide() + else: + self.box.show() + + def search(self, widget=None, data=None, scroll=True): + searchtext = self.searchentry.get_text() + buf = self.textbuffer + context_start = buf.get_start_iter() + context_end = buf.get_end_iter() + text = buf.get_slice(context_start, context_end, False) + + self.textbuffer.remove_tag(self.highlight, context_start, context_end) + + # case sensitive? + flags = False + if not self.casesensitivebutton.get_active(): + flags = flags | re.I + + # regex? + if not self.regexbutton.get_active(): + searchtext = re.escape(searchtext) + + matches = re.finditer(searchtext, text, flags) + + self.matchiters = [] + self.active = 0 + for match in matches: + startIter = buf.get_iter_at_offset(match.start()) + endIter = buf.get_iter_at_offset(match.end()) + self.matchiters.append((startIter, endIter)) + self.textbuffer.apply_tag(self.highlight, startIter, endIter) + if scroll: + self.scrollto(self.active) + logger.debug(searchtext) + + def scrolltonext(self, widget, data=None): + self.scrollto(self.active + 1) + + def scrolltoprev(self, widget, data=None): + self.scrollto(self.active - 1) + + def scrollto(self, index): + if not len(self.matchiters): + return + if(index < len(self.matchiters)): + self.active = index + else: + self.active = 0 + + matchiter = self.matchiters[self.active] + self.texteditor.scroll_to_iter(matchiter[0], 0.0, True, 0.0, 0.5) + + def hide(self): + self.box.hide() + + def replace_clicked(self, widget, data=None): + self.replace(self.active) + + def replace_all(self, widget=None, data=None): + while self.matchiters: + match = self.matchiters[0] + self.textbuffer.delete(match[0], match[1]) + self.textbuffer.insert(match[0], self.replaceentry.get_text()) + self.search(scroll=False) + + def replace(self, searchindex, inloop=False): + match = self.matchiters[searchindex] + self.textbuffer.delete(match[0], match[1]) + self.textbuffer.insert(match[0], self.replaceentry.get_text()) + active = self.active + self.search(scroll=False) + self.active = active + self.parentwindow.MarkupBuffer.markup_buffer() + self.scrollto(self.active) \ No newline at end of file diff --git a/build/lib/uberwriter/UberwriterSidebar.py b/build/lib/uberwriter/UberwriterSidebar.py new file mode 100644 index 0000000..e963ee6 --- /dev/null +++ b/build/lib/uberwriter/UberwriterSidebar.py @@ -0,0 +1,176 @@ +# -*- Mode: Python; coding: utf-8; indent-tabs-mode: nil; tab-width: 4 -*- +### BEGIN LICENSE +# Copyright (C) 2012, Wolf Vollprecht +# This program is free software: you can redistribute it and/or modify it +# under the terms of the GNU General Public License version 3, as published +# by the Free Software Foundation. +# +# This program is distributed in the hope that it will be useful, but +# WITHOUT ANY WARRANTY; without even the implied warranties of +# MERCHANTABILITY, SATISFACTORY QUALITY, or FITNESS FOR A PARTICULAR +# PURPOSE. See the GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License along +# with this program. If not, see . +### END LICENSE + +import os +import subprocess +from gi.repository import Gtk, Gdk + +# from plugins import plugins + +import logging +logger = logging.getLogger('uberwriter') + +class Shelve(): + """ + Shelve holds a collection of folders + folders: + List of folders + name: + descriptive name of shelve e.g. blog, notes etc. + """ + + name = "" + folders = [] + + def __init__(self, name, folders): + self.name = name + self.folders = folders + + def get_tree(self, store): + node = {} + for folder in self.folders: + node[folder] = store.append(None, [os.path.basename(folder), folder]) + for root, dirs, files in os.walk(folder): + logger.debug(root) + for directory in dirs: + node[root + "/" + directory] = store.append(node[root], [directory, root + "/" + directory]) + for filename in files: + store.append(node[root], [filename, root + "/" + filename]) + + +class UberwriterSidebar(): + """ + Presentational class for shelves and files managed by the "sidebar" + + parentwindow: + Reference to UberwriterWindow + """ + def __init__(self, parentwindow): + """ + Initialize Treeview and Treestore + """ + + self.parentwindow = parentwindow + self.paned_window = parentwindow.paned_window + self.sidebar_box = parentwindow.sidebar_box + + # (GtkBox *box, + # GtkWidget *child, + # gboolean expand, + # gboolean fill, + # guint padding); + + self.shelve_store = Gtk.ListStore(str) + self.shelve_store.append(["testshelve"]) + self.shelves_dropdown = Gtk.ComboBox.new_with_model_and_entry(self.shelve_store) + + self.sidebar_box.pack_start(self.shelves_dropdown, False, False, 5) + + self.sidebar_scrolledwindow = Gtk.ScrolledWindow() + self.sidebar_scrolledwindow.set_hexpand(True) + self.sidebar_scrolledwindow.set_vexpand(True) + + self.store = Gtk.TreeStore(str, str) + self.active_shelf = Shelve("testshelve", ["/home/wolf/Documents/Texte"]) + self.active_shelf.get_tree(self.store) + + self.treeview = Gtk.TreeView(self.store) + self.treeview.set_headers_visible(False) + # expand first folder (root folder, but not children) + self.treeview.expand_row(Gtk.TreePath.new_from_string("0"), False) + + renderer = Gtk.CellRendererText() + column = Gtk.TreeViewColumn("Title", renderer, text=0) + self.treeview.append_column(column) + # new selection + self.treeview.connect('cursor_changed', self.get_selected_file) + # right click handler + self.treeview.connect('button-press-event', self.handle_button_press) + self.treeview.show() + + self.sidebar_scrolledwindow.add(self.treeview) + self.sidebar_box.pack_start(self.sidebar_scrolledwindow, True, True, 5) + + self.menu_box = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, spacing=6) + self.menu_button = Gtk.MenuButton.new() + + # TODO refactor + mb_menu = Gtk.Menu.new() + mitem = Gtk.MenuItem.new_with_label('etstasd asd as d') + mitem.show() + mb_menu.append(mitem) + mb_menu.show() + + self.menu_button.set_popup(mb_menu) + + self.menu_box.pack_start(self.menu_button, False, False, 5) + self.sidebar_box.pack_end(self.menu_box, False, False, 5) + + self.sidebar_box.show_all() + self.paned_window.pack1(self.sidebar_box, True, True); + self.paned_window.show_all() + + + def get_selected_file(self, widget, data=None): + """ + Handle left click on file + """ + selection = self.treeview.get_selection() + if not selection: + return + selection.set_mode(Gtk.SelectionMode.SINGLE) + treemodel, treeiter = selection.get_selected() + selected_file = treemodel.get_value(treeiter, 1) + self.parentwindow.load_file(selected_file) + logger.debug(selected_file) + + def handle_button_press(self, widget, event): + """ + Handle right click (context menu) + """ + if event.type == Gdk.EventType.BUTTON_PRESS and event.button == 3: + # reference to self to not have it garbage collected + self.popup = Gtk.Menu.new() + pathinfo = self.treeview.get_path_at_pos(event.x, event.y) + if pathinfo: + path, col, cellx, celly = pathinfo + treeiter = self.store.get_iter(path) + filename = self.store.get_value(treeiter, 1) + item = Gtk.MenuItem.new() + item.set_label("Open ...") + item.connect("activate", self.context_menu_open_file) + item.filename = filename + item.show() + self.popup.append(item) + self.popup.show() + self.popup.popup(None, None, None, None, event.button, event.time) + return True + + def get_treeview(self): + """ + Return Treeview to append to scrolled window + """ + return self.treeview + + def context_menu_open_file(self, widget, data=None): + """ + Open selected file with xdg-open + """ + selected_file = widget.filename + subprocess.call(["xdg-open", selected_file]) + + def close_sidebar(self): + pass diff --git a/build/lib/uberwriter/UberwriterTextEditor.py b/build/lib/uberwriter/UberwriterTextEditor.py new file mode 100644 index 0000000..50342a2 --- /dev/null +++ b/build/lib/uberwriter/UberwriterTextEditor.py @@ -0,0 +1,440 @@ +### BEGIN LICENSE +# Copyright (C) 2012, Wolf Vollprecht +# This program is free software: you can redistribute it and/or modify it +# under the terms of the GNU General Public License version 3, as published +# by the Free Software Foundation. +# +# This program is distributed in the hope that it will be useful, but +# WITHOUT ANY WARRANTY; without even the implied warranties of +# MERCHANTABILITY, SATISFACTORY QUALITY, or FITNESS FOR A PARTICULAR +# PURPOSE. See the GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License along +# with this program. If not, see . +### END LICENSE +"""Module for the TextView widgth wich encapsulates management of TextBuffer +and TextIter for common functionality, such as cut, copy, paste, undo, redo, +and highlighting of text. + +Using +#create the TextEditor and set the text +editor = TextEditor() +editor.text = "Text to add to the editor" + +#use cut, works the same for copy, paste, undo, and redo +def __handle_on_cut(self, widget, data=None): + self.editor.cut() + +#add string to highlight +self.editor.add_highlight("Ubuntu") +self.editor.add_highlight("Quickly") + +#remove highlights +self.editor.clear_highlight("Ubuntu") +self.editor.clear_all_highlight() + +Configuring +#Configure as a TextView +self.editor.set_wrap_mode(Gtk.WRAP_CHAR) + +#Access the Gtk.TextBuffer if needed +buffer = self.editor.get_buffer() + +Extending +A TextEditor is Gtk.TextView + +""" + + +try: + from gi.repository import Gtk + from gi.repository import Gdk + +except: + print("couldn't load depencies") + +import logging +logger = logging.getLogger('uberwriter') + + +class UndoableInsert(object): + """something that has been inserted into our textbuffer""" + def __init__(self, text_iter, text, length, fflines): + self.offset = text_iter.get_offset() - fflines + self.text = text + self.length = length + if self.length > 1 or self.text in ("\r", "\n", " "): + self.mergeable = False + else: + self.mergeable = True + + +class UndoableDelete(object): + """something that has ben deleted from our textbuffer""" + def __init__(self, text_buffer, start_iter, end_iter, fflines): + self.text = text_buffer.get_text(start_iter, end_iter, False) + self.start = start_iter.get_offset() - fflines + self.end = end_iter.get_offset() - fflines + # need to find out if backspace or delete key has been used + # so we don't mess up during redo + insert_iter = text_buffer.get_iter_at_mark(text_buffer.get_insert()) + if insert_iter.get_offset() <= self.start: + self.delete_key_used = True + else: + self.delete_key_used = False + if self.end - self.start > 1 or self.text in ("\r", "\n", " "): + self.mergeable = False + else: + self.mergeable = True + + +class TextEditor(Gtk.TextView): + """TextEditor encapsulates management of TextBuffer and TextIter for + common functionality, such as cut, copy, paste, undo, redo, and + highlighting of text. + + """ + + def __init__(self): + """Create a TextEditor + + """ + + Gtk.TextView.__init__(self) + self.undo_max = None + + self.insert_event = self.get_buffer().connect("insert-text", self.on_insert_text) + self.delete_event = self.get_buffer().connect("delete-range", self.on_delete_range) + display = self.get_display() + self.clipboard = Gtk.Clipboard.get_for_display(display, Gdk.SELECTION_CLIPBOARD) + + self.fflines = 0 + + self.undo_stack = [] + self.redo_stack = [] + self.not_undoable_action = False + self.undo_in_progress = False + + @property + def text(self): + """ + text - a string specifying all the text currently + in the TextEditor's buffer. + + This property is read/write. + """ + start_iter = self.get_buffer().get_iter_at_offset(0) + end_iter = self.get_buffer().get_iter_at_offset(-1) + return self.get_buffer().get_text(start_iter, end_iter, False) + + @property + def can_undo(self): + return bool(self.undo_stack) + + @property + def can_redo(self): + return bool(self.redo_stack) + + + @text.setter + def text(self, text): + self.get_buffer().set_text(text) + + def append(self, text): + """append: appends text to the end of the textbuffer. + + arguments: + text - a string to add to the buffer. The text will be the + last text in the buffer. The insertion cursor will not be moved. + + """ + + end_iter = self.get_buffer().get_iter_at_offset(-1) + self.get_buffer().insert(end_iter, text) + + def prepend(self, text): + """prepend: appends text to the start of the textbuffer. + + arguments: + text - a string to add to the buffer. The text will be the + first text in the buffer. The insertion cursor will not be moved. + + """ + + start_iter = self.get_buffer().get_iter_at_offset(0) + self.get_buffer().insert(start_iter, text) + insert_iter = self.get_buffer().get_iter_at_offset(len(text)-1) + self.get_buffer().place_cursor(insert_iter) + + def cursor_to_end(self): + """cursor_to_end: moves the insertion curson to the last position + in the buffer. + + """ + + end_iter = self.get_buffer().get_iter_at_offset(-1) + self.get_buffer().place_cursor(end_iter) + + def cursor_to_start(self): + """cursor_to_start: moves the insertion curson to the first position + in the buffer. + + """ + + start_iter = self.get_buffer().get_iter_at_offset(0) + self.get_buffer().place_cursor(start_iter) + + def cut(self, widget=None, data=None): + """cut: cut currently selected text and put it on the clipboard. + This function can be called as a function, or assigned as a signal + handler. + + """ + + self.get_buffer().cut_clipboard(self.clipboard, True) + + def copy(self, widget=None, data=None): + """copy: copy currently selected text to the clipboard. + This function can be called as a function, or assigned as a signal + handler. + + """ + + self.get_buffer().copy_clipboard(self.clipboard) + + def paste(self, widget=None, data=None): + """paste: Insert any text currently on the clipboard into the + buffer. + This function can be called as a function, or assigned as a signal + handler. + + """ + + self.get_buffer().paste_clipboard(self.clipboard,None,True) + + def undo(self, widget=None, data=None): + """undo inserts or deletions + undone actions are being moved to redo stack""" + if not self.undo_stack: + return + self.begin_not_undoable_action() + self.undo_in_progress = True + undo_action = self.undo_stack.pop() + self.redo_stack.append(undo_action) + buf = self.get_buffer() + if isinstance(undo_action, UndoableInsert): + offset = undo_action.offset + self.fflines + start = buf.get_iter_at_offset(offset) + stop = buf.get_iter_at_offset( + offset + undo_action.length + ) + buf.delete(start, stop) + buf.place_cursor(start) + else: + start = buf.get_iter_at_offset(undo_action.start + self.fflines) + buf.insert(start, undo_action.text) + if undo_action.delete_key_used: + buf.place_cursor(start) + else: + stop = buf.get_iter_at_offset(undo_action.end + self.fflines) + buf.place_cursor(stop) + self.end_not_undoable_action() + self.undo_in_progress = False + + def redo(self, widget=None, data=None): + """redo inserts or deletions + + redone actions are moved to undo stack""" + if not self.redo_stack: + return + self.begin_not_undoable_action() + self.undo_in_progress = True + redo_action = self.redo_stack.pop() + self.undo_stack.append(redo_action) + buf = self.get_buffer() + if isinstance(redo_action, UndoableInsert): + start = buf.get_iter_at_offset(redo_action.offset) + buf.insert(start, redo_action.text) + new_cursor_pos = buf.get_iter_at_offset( + redo_action.offset + redo_action.length + ) + buf.place_cursor(new_cursor_pos) + else: + start = buf.get_iter_at_offset(redo_action.start) + stop = buf.get_iter_at_offset(redo_action.end) + buf.delete(start, stop) + buf.place_cursor(start) + self.end_not_undoable_action() + self.undo_in_progress = False + + def on_insert_text(self, textbuffer, text_iter, text, length): + """ + _on_insert: internal function to handle programatically inserted + text. Do not call directly. + """ + def can_be_merged(prev, cur): + """see if we can merge multiple inserts here + + will try to merge words or whitespace + can't merge if prev and cur are not mergeable in the first place + can't merge when user set the input bar somewhere else + can't merge across word boundaries""" + WHITESPACE = (' ', '\t') + if not cur.mergeable or not prev.mergeable: + return False + elif cur.offset != (prev.offset + prev.length): + return False + elif cur.text in WHITESPACE and not prev.text in WHITESPACE: + return False + elif prev.text in WHITESPACE and not cur.text in WHITESPACE: + return False + return True + + if not self.undo_in_progress: + self.redo_stack = [] + if self.not_undoable_action: + return + + logger.debug(text) + logger.debug("b: %i, l: %i" % (length, len(text))) + undo_action = UndoableInsert(text_iter, text, len(text), self.fflines) + try: + prev_insert = self.undo_stack.pop() + except IndexError: + self.undo_stack.append(undo_action) + return + if not isinstance(prev_insert, UndoableInsert): + self.undo_stack.append(prev_insert) + self.undo_stack.append(undo_action) + return + if can_be_merged(prev_insert, undo_action): + prev_insert.length += undo_action.length + prev_insert.text += undo_action.text + self.undo_stack.append(prev_insert) + else: + self.undo_stack.append(prev_insert) + self.undo_stack.append(undo_action) + + def on_delete_range(self, text_buffer, start_iter, end_iter): + """ + On delete + """ + def can_be_merged(prev, cur): + """see if we can merge multiple deletions here + + will try to merge words or whitespace + can't merge if prev and cur are not mergeable in the first place + can't merge if delete and backspace key were both used + can't merge across word boundaries""" + + WHITESPACE = (' ', '\t') + if not cur.mergeable or not prev.mergeable: + return False + elif prev.delete_key_used != cur.delete_key_used: + return False + elif prev.start != cur.start and prev.start != cur.end: + return False + elif cur.text not in WHITESPACE and \ + prev.text in WHITESPACE: + return False + elif cur.text in WHITESPACE and \ + prev.text not in WHITESPACE: + return False + return True + + if not self.undo_in_progress: + self.redo_stack = [] + if self.not_undoable_action: + return + undo_action = UndoableDelete(text_buffer, start_iter, end_iter, self.fflines) + try: + prev_delete = self.undo_stack.pop() + except IndexError: + self.undo_stack.append(undo_action) + return + if not isinstance(prev_delete, UndoableDelete): + self.undo_stack.append(prev_delete) + self.undo_stack.append(undo_action) + return + if can_be_merged(prev_delete, undo_action): + if prev_delete.start == undo_action.start: # delete key used + prev_delete.text += undo_action.text + prev_delete.end += (undo_action.end - undo_action.start) + else: # Backspace used + prev_delete.text = "%s%s" % (undo_action.text, + prev_delete.text) + prev_delete.start = undo_action.start + self.undo_stack.append(prev_delete) + else: + self.undo_stack.append(prev_delete) + self.undo_stack.append(undo_action) + + def begin_not_undoable_action(self): + """don't record the next actions + + toggles self.not_undoable_action""" + self.not_undoable_action = True + + def end_not_undoable_action(self): + """record next actions + + toggles self.not_undoable_action""" + self.not_undoable_action = False + +class TestWindow(Gtk.Window): + """For testing and demonstrating AsycnTaskProgressBox. + + """ + def __init__(self): + #create a window a VBox to hold the controls + Gtk.Window.__init__(self) + self.set_title("TextEditor Test Window") + windowbox = Gtk.VBox(False, 2) + windowbox.show() + self.add(windowbox) + self.editor = TextEditor() + self.editor.show() + windowbox.pack_end(self.editor, True, True, 0) + self.set_size_request(200,200) + self.show() + self.maximize() + + self.connect("destroy", Gtk.main_quit) + self.editor.text = "this is some inserted text" + self.editor.append("\nLine 3") + self.editor.prepend("Line1\n") + self.editor.cursor_to_end() + self.editor.cursor_to_start() + self.editor.undo_max = 100 + cut_button = Gtk.Button("Cut") + cut_button.connect("clicked",self.editor.cut) + cut_button.show() + windowbox.pack_start(cut_button, False, False, 0) + + copy_button = Gtk.Button("Copy") + copy_button.connect("clicked",self.editor.copy) + copy_button.show() + windowbox.pack_start(copy_button, False, False, 0) + + paste_button = Gtk.Button("Paste") + paste_button.connect("clicked",self.editor.paste) + paste_button.show() + windowbox.pack_start(paste_button, False, False, 0) + + undo_button = Gtk.Button("Undo") + undo_button.connect("clicked",self.editor.undo) + undo_button.show() + windowbox.pack_start(undo_button, False, False, 0) + + redo_button = Gtk.Button("Redo") + redo_button.connect("clicked",self.editor.redo) + redo_button.show() + windowbox.pack_start(redo_button, False, False, 0) + + print(self.editor.text) + + +if __name__== "__main__": + test = TestWindow() + Gtk.main() + diff --git a/build/lib/uberwriter/UberwriterWindow.py b/build/lib/uberwriter/UberwriterWindow.py new file mode 100644 index 0000000..39883c5 --- /dev/null +++ b/build/lib/uberwriter/UberwriterWindow.py @@ -0,0 +1,1217 @@ +# -*- Mode: Python; coding: utf-8; indent-tabs-mode: nil; tab-width: 4 -*- +### BEGIN LICENSE +# Copyright (C) 2012, Wolf Vollprecht +# This program is free software: you can redistribute it and/or modify it +# under the terms of the GNU General Public License version 3, as published +# by the Free Software Foundation. +# +# This program is distributed in the hope that it will be useful, but +# WITHOUT ANY WARRANTY; without even the implied warranties of +# MERCHANTABILITY, SATISFACTORY QUALITY, or FITNESS FOR A PARTICULAR +# PURPOSE. See the GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License along +# with this program. If not, see . +### END LICENSE + +import locale +import subprocess +import os +import codecs +import webbrowser +import urllib +import pickle + +from locale import gettext as _ +locale.textdomain('uberwriter') + +import mimetypes + +from gi.repository import Gtk, Gdk, GObject, WebKit # pylint: disable=E0611 +from gi.repository import Pango # pylint: disable=E0611 + +import cairo + +import re + + +from .MarkupBuffer import MarkupBuffer +from .FormatShortcuts import FormatShortcuts +from .UberwriterTextEditor import TextEditor +from .UberwriterInlinePreview import UberwriterInlinePreview +from .UberwriterSidebar import UberwriterSidebar +from .UberwriterSearchAndReplace import UberwriterSearchAndReplace + +import logging +logger = logging.getLogger('uberwriter') + +print('This file is imported') + +# Spellcheck + +import locale +try: + from gtkspellcheck import SpellChecker +except ImportError: + from uberwriter_lib.gtkspellcheck import SpellChecker + +try: + import apt + APT_ENABLED = True +except: + APT_ENABLED = False + +from uberwriter_lib import Window +from uberwriter_lib import helpers +from .AboutUberwriterDialog import AboutUberwriterDialog +from .UberwriterAdvancedExportDialog import UberwriterAdvancedExportDialog + +# Some Globals +# TODO move them somewhere for better +# accesibility from other files + +CONFIG_PATH = os.path.expanduser("~/.config/uberwriter/") + +# gtk_text_view_forward_display_line_end () !! ! +# move-viewport signal +# See texteditor_lib.Window.py for more details about how this class works +class UberwriterWindow(Window): + + __gtype_name__ = "UberwriterWindow" + + def scrolled(self, widget): + """if window scrolled + focusmode make font black again""" + if self.focusmode: + if self.textchange == False: + if self.scroll_count >= 1: + self.TextBuffer.apply_tag( + self.MarkupBuffer.blackfont, + self.TextBuffer.get_start_iter(), + self.TextBuffer.get_end_iter()) + else: + self.scroll_count += 1 + else: + self.scroll_count = 0 + self.typewriter() + self.textchange = False + + def after_modify_text(self, *arg): + if self.focusmode: + self.typewriter() + + def after_insert_at_cursor(self, *arg): + if self.focusmode: + self.typewriter() + + def paste_done(self, *args): + self.MarkupBuffer.markup_buffer(0) + + def init_typewriter(self): + + self.TextEditor.begin_not_undoable_action() + + ci = self.TextBuffer.get_iter_at_mark(self.TextBuffer.get_mark('insert')) + co = ci.get_offset() + + fflines = int(round((self.window_height - 55) / (2 * 30))) + self.fflines = fflines + self.TextEditor.fflines = fflines + + s = '\n' * fflines + + start_iter = self.TextBuffer.get_iter_at_offset(0) + self.TextBuffer.insert(start_iter, s) + + end_iter = self.TextBuffer.get_iter_at_offset(-1) + self.TextBuffer.insert(end_iter, s) + + ne_ci = self.TextBuffer.get_iter_at_offset(co + fflines) + self.TextBuffer.place_cursor(ne_ci) + + # Scroll it to the center + self.TextEditor.scroll_to_mark(self.TextBuffer.get_mark('insert'), 0.0, True, 0.0, 0.5) + + self.TextEditor.end_not_undoable_action() + + self.text_change_event = self.TextBuffer.connect('changed', self.text_changed) + + self.typewriter_initiated = True + + def typewriter(self): + cursor = self.TextBuffer.get_mark("insert") + cursor_iter = self.TextBuffer.get_iter_at_mark(cursor) + self.TextEditor.scroll_to_iter(cursor_iter, 0.0, True, 0.0, 0.5) + + def remove_typewriter(self): + # self.TextBuffer.disconnect(self.TextEditor.delete_event) + # self.TextBuffer.disconnect(self.TextEditor.insert_event) + self.TextEditor.begin_not_undoable_action() + + startIter = self.TextBuffer.get_start_iter() + endLineIter = startIter.copy() + endLineIter.forward_lines(self.fflines) + self.TextBuffer.delete(startIter, endLineIter) + startIter = self.TextBuffer.get_end_iter() + endLineIter = startIter.copy() + + # Move to line before last line + endLineIter.backward_lines(self.fflines - 1) + + # Move to last char in last line + endLineIter.backward_char() + self.TextBuffer.delete(startIter, endLineIter) + + self.fflines = 0 + self.TextEditor.fflines = 0 + + self.TextEditor.end_not_undoable_action() + + # self.TextEditor.insert_event = self.TextBuffer.connect("insert-text",self.TextEditor._on_insert) + # self.TextEditor.delete_event = self.TextBuffer.connect("delete-range",self.TextEditor._on_delete) + self.text_change_event = self.TextBuffer.connect('changed', self.text_changed) + + + + WORDCOUNT = re.compile(r"[\s#*\+\-]+", re.UNICODE) + def update_line_and_char_count(self): + if self.status_bar_visible == False: + return + + self.char_count.set_text(str(self.TextBuffer.get_char_count() - + (2 * self.fflines))) + + text = self.get_text() + words = re.split(self.WORDCOUNT, text) + length = len(words) + # Last word a "space" + if len(words[-1]) == 0: + length = length - 1 + # First word a "space" (happens in focus mode...) + if len(words[0]) == 0: + length = length - 1 + if length == -1: + length = 0 + self.word_count.set_text(str(length)) + + # TODO rename line_count to word_count + + def get_text(self): + if self.focusmode == False: + start_iter = self.TextBuffer.get_start_iter() + end_iter = self.TextBuffer.get_end_iter() + + else: + start_iter = self.TextBuffer.get_iter_at_line(self.fflines) + rbline = self.TextBuffer.get_line_count() - self.fflines + end_iter = self.TextBuffer.get_iter_at_line(rbline) + + return self.TextBuffer.get_text(start_iter, end_iter, False) + + def mark_set(self, buffer, location, mark, data=None): + if self.focusmode and (mark.get_name() == 'insert' or + mark.get_name() == 'selection_bound'): + akt_lines = self.TextBuffer.get_line_count() + lb = self.fflines + rb = akt_lines - self.fflines + #print "a %d, lb %d, rb %d" % (akt_lines, lb, rb) + #lb = self.TextBuffer.get_iter_at_line(self.fflines) + #rbline = self.TextBuffer.get_line_count() - self.fflines + #rb = self.TextBuffer.get_iter_at_line( + # rbline) + #rb.backward_line() + + + linecount = location.get_line() + #print "a %d, lb %d, rb %d, lc %d" % (akt_lines, lb, rb, linecount) + + if linecount < lb: + move_to_line = self.TextBuffer.get_iter_at_line(lb) + self.TextBuffer.move_mark(mark, move_to_line) + elif linecount >= rb: + move_to_line = self.TextBuffer.get_iter_at_line(rb) + move_to_line.backward_char() + self.TextBuffer.move_mark(mark, move_to_line) + + def after_mark_set(self, buffer, location, mark, data=None): + if self.focusmode and mark.get_name() == 'insert': + self.typewriter() + + + def delete_from_cursor(self, editor, typ, count, Data=None): + if not self.focusmode: + return + cursor = self.TextBuffer.get_mark("insert") + cursor_iter = self.TextBuffer.get_iter_at_mark(cursor) + if count < 0 and cursor_iter.starts_line(): + lb = self.fflines + linecount = cursor_iter.get_line() + #print "lb %d, lc %d" % (lb, linecount) + if linecount <= lb: + self.TextEditor.emit_stop_by_name('delete-from-cursor') + elif count > 0 and cursor_iter.ends_line(): + akt_lines = self.TextBuffer.get_line_count() + rb = akt_lines - self.fflines + linecount = cursor_iter.get_line() + 1 + #print "rb %d, lc %d" % (rb, linecount) + if linecount >= rb: + self.TextEditor.emit_stop_by_name('delete-from-cursor') + + def backspace(self, data=None): + if not self.focusmode: + return + + cursor = self.TextBuffer.get_mark("insert") + cursor_iter = self.TextBuffer.get_iter_at_mark(cursor) + if cursor_iter.starts_line(): + lb = self.fflines + linecount = cursor_iter.get_line() + #print "lb %d, lc %d" % (lb, linecount) + + if linecount <= lb: + self.TextEditor.emit_stop_by_name('backspace') + + + def cursor_moved(self, widget, a, b, data=None): + pass + + def after_cursor_moved(self, widget, step, count, extend_selection, data=None): + if self.focusmode: + self.typewriter() + + def text_changed(self, widget, data=None): + if self.did_change == False: + self.did_change = True + title = self.get_title() + self.set_title("* " + title) + + self.MarkupBuffer.markup_buffer(1) + self.textchange = True + + self.buffer_modified_for_status_bar = True + self.update_line_and_char_count() + + def toggle_fullscreen(self, widget, data=None): + if widget.get_active(): + self.fullscreen() + key, mod = Gtk.accelerator_parse("Escape") + self.fullscreen_button.add_accelerator("activate", + self.accel_group, key, mod, Gtk.AccelFlags.VISIBLE) + + # Hide Menu + self.menubar.hide() + + else: + self.unfullscreen() + key, mod = Gtk.accelerator_parse("Escape") + self.fullscreen_button.remove_accelerator( + self.accel_group, key, mod) + self.menubar.show() + + self.TextEditor.grab_focus() + + def delete_text(self, widget): + pass + + def cut_text(self, widget, data=None): + self.TextEditor.cut() + + def paste_text(self, widget, data=None): + self.TextEditor.paste() + + def copy_text(self, widget, data=None): + self.TextEditor.copy() + + def undo(self, widget, data=None): + self.TextEditor.undo() + + def redo(self, widget, data=None): + self.TextEditor.redo() + + def set_italic(self, widget, data=None): + """Ctrl + I""" + self.FormatShortcuts.italic() + + def set_bold(self, widget, data=None): + """Ctrl + B""" + self.FormatShortcuts.bold() + + def insert_horizontal_rule(self, widget, data=None): + """Ctrl + R""" + self.FormatShortcuts.rule() + + def insert_unordered_list_item(self, widget, data=None): + """Ctrl + U""" + self.FormatShortcuts.unordered_list_item() + + def insert_ordered_list(self, widget, data=None): + """CTRL + O""" + self.FormatShortcuts.ordered_list_item() + + def insert_heading(self, widget, data=None): + """CTRL + H""" + self.FormatShortcuts.heading() + + def set_focusmode(self, widget, data=None): + if widget.get_active(): + self.init_typewriter() + self.MarkupBuffer.focusmode_highlight() + self.focusmode = True + self.TextEditor.grab_focus() + + if self.spellcheck != False: + self.SpellChecker._misspelled.set_property('underline', 0) + + else: + self.remove_typewriter() + self.focusmode = False + self.TextBuffer.remove_tag(self.MarkupBuffer.grayfont, + self.TextBuffer.get_start_iter(), + self.TextBuffer.get_end_iter()) + self.TextBuffer.remove_tag(self.MarkupBuffer.blackfont, + self.TextBuffer.get_start_iter(), + self.TextBuffer.get_end_iter()) + + self.MarkupBuffer.markup_buffer(1) + self.TextEditor.grab_focus() + self.update_line_and_char_count() + + if self.spellcheck != False: + self.SpellChecker._misspelled.set_property('underline', 4) + + def window_resize(self, widget, data=None): + # To calc padding top / bottom + self.window_height = widget.get_size()[1] + w_width = widget.get_size()[0] + # Calculate left / right margin + + if(w_width < 900): + self.MarkupBuffer.set_multiplier(8) + pango_font = Pango.FontDescription("Ubuntu Mono 12px") + self.TextEditor.modify_font(pango_font) + lm = (widget.get_size()[0] - 600) / 2 + + elif(w_width < 1400): + self.MarkupBuffer.set_multiplier(10) + pango_font = Pango.FontDescription("Ubuntu Mono 15px") + self.TextEditor.modify_font(pango_font) + lm = (widget.get_size()[0] - 700) / 2 + + else: + self.MarkupBuffer.set_multiplier(13) + pango_font = Pango.FontDescription("Ubuntu Mono 17px") + self.TextEditor.modify_font(pango_font) + lm = (widget.get_size()[0] - 1000) / 2 + + self.TextEditor.set_left_margin(lm) + self.TextEditor.set_right_margin(lm) + + self.MarkupBuffer.recalculate(lm) + + if self.focusmode: + self.remove_typewriter() + self.init_typewriter() + + def window_close(self, widget, data=None): + return True + + + def save_document(self, widget, data=None): + if self.filename: + logger.info("saving") + filename = self.filename + f = codecs.open(filename, encoding="utf-8", mode='w') + f.write(self.get_text()) + f.close() + if self.did_change: + self.did_change = False + title = self.get_title() + self.set_title(title[2:]) + return Gtk.ResponseType.OK + + else: + + filefilter = Gtk.FileFilter.new() + filefilter.add_mime_type('text/x-markdown') + filefilter.add_mime_type('text/plain') + filefilter.set_name('MarkDown (.md)') + filechooser = Gtk.FileChooserDialog( + _("Save your File"), + self, + Gtk.FileChooserAction.SAVE, + (Gtk.STOCK_CANCEL, Gtk.ResponseType.CANCEL, + Gtk.STOCK_SAVE, Gtk.ResponseType.OK) + ) + + filechooser.set_do_overwrite_confirmation(True) + filechooser.add_filter(filefilter) + response = filechooser.run() + if response == Gtk.ResponseType.OK: + filename = filechooser.get_filename() + + if filename[-3:] != ".md": + filename = filename + ".md" + try: + self.recent_manager.add_item("file:/ " + filename) + except: + pass + + f = codecs.open(filename, encoding="utf-8", mode='w') + + f.write(self.get_text()) + f.close() + + self.filename = filename + self.set_title(os.path.basename(filename) + self.title_end) + + self.did_change = False + filechooser.destroy() + return response + + elif response == Gtk.ResponseType.CANCEL: + filechooser.destroy() + return response + + def save_document_as(self, widget, data=None): + filechooser = Gtk.FileChooserDialog( + "Save your File", + self, + Gtk.FileChooserAction.SAVE, + (Gtk.STOCK_CANCEL, Gtk.ResponseType.CANCEL, + Gtk.STOCK_SAVE, Gtk.ResponseType.OK) + ) + filechooser.set_do_overwrite_confirmation(True) + if self.filename: + filechooser.set_filename(self.filename) + response = filechooser.run() + if response == Gtk.ResponseType.OK: + + filename = filechooser.get_filename() + if filename[-3:] != ".md": + filename = filename + ".md" + try: + self.recent_manager.remove_item("file:/" + filename) + self.recent_manager.add_item("file:/ " + filename) + except: + pass + + f = codecs.open(filename, encoding="utf-8", mode='w') + f.write(self.get_text()) + f.close() + + self.filename = filename + self.set_title(os.path.basename(filename) + self.title_end) + + try: + self.recent_manager.add_item(filename) + except: + pass + + filechooser.destroy() + self.did_change = False + + elif response == Gtk.ResponseType.CANCEL: + filechooser.destroy() + + def export(self, export_type="html"): + filechooser = Gtk.FileChooserDialog( + "Export as %s" % export_type.upper(), + self, + Gtk.FileChooserAction.SAVE, + (Gtk.STOCK_CANCEL, Gtk.ResponseType.CANCEL, + Gtk.STOCK_SAVE, Gtk.ResponseType.OK) + ) + + filechooser.set_do_overwrite_confirmation(True) + if self.filename: + filechooser.set_filename(self.filename[:-2] + export_type.lower()) + + response = filechooser.run() + if response == Gtk.ResponseType.OK: + filename = filechooser.get_filename() + if filename.endswith("." + export_type): + filename = filename[:-len(export_type)-1] + filechooser.destroy() + else: + filechooser.destroy() + return + + # Converting text to bytes for python 3 + text = bytes(self.get_text(), "utf-8") + + output_dir = os.path.abspath(os.path.join(filename, os.path.pardir)) + + basename = os.path.basename(filename) + + args = ['pandoc', '--from=markdown', '--smart'] + + if export_type == "pdf": + args.append("-o%s.pdf" % basename) + + elif export_type == "odt": + args.append("-o%s.odt" % basename) + + elif export_type == "html": + css = helpers.get_media_file('uberwriter.css') + args.append("-c%s" % css) + args.append("-o%s.html" % basename) + args.append("--mathjax") + + p = subprocess.Popen(args, stdin=subprocess.PIPE, stdout=subprocess.PIPE, cwd=output_dir) + output = p.communicate(text)[0] + + return filename + + def export_as_odt(self, widget, data=None): + self.export("odt") + + def export_as_html(self, widget, data=None): + self.export("html") + + def export_as_pdf(self, widget, data=None): + if self.texlive_installed == False and APT_ENABLED: + try: + cache = apt.Cache() + inst = cache["texlive"].is_installed + except: + inst = True + + if inst == False: + dialog = Gtk.MessageDialog(self, + Gtk.DialogFlags.MODAL | Gtk.DialogFlags.DESTROY_WITH_PARENT, + Gtk.MessageType.INFO, + None, + _("You can not export to PDF.") + ) + dialog.format_secondary_markup(_("Please install texlive from the software center.")) + response = dialog.run() + return + else: + self.texlive_installed = True + self.export("pdf") + + def copy_html_to_clipboard(self, widget, date=None): + """Copies only html without headers etc. to Clipboard""" + + args = ['pandoc', '--from=markdown', '--smart', '-thtml'] + p = subprocess.Popen(args, stdin=subprocess.PIPE, stdout=subprocess.PIPE) + + text = bytes(self.get_text(), "utf-8") + output = p.communicate(text)[0] + + cb = Gtk.Clipboard.get(Gdk.SELECTION_CLIPBOARD) + cb.set_text(output.decode("utf-8"), -1) + cb.store() + + def open_document(self, widget): + if self.check_change() == Gtk.ResponseType.CANCEL: + return + + filefilter = Gtk.FileFilter.new() + filefilter.add_mime_type('text/x-markdown') + filefilter.add_mime_type('text/plain') + filefilter.set_name(_('MarkDown or Plain Text')) + + filechooser = Gtk.FileChooserDialog( + _("Open a .md-File"), + self, + Gtk.FileChooserAction.OPEN, + (Gtk.STOCK_CANCEL, Gtk.ResponseType.CANCEL, + Gtk.STOCK_OPEN, Gtk.ResponseType.OK) + ) + filechooser.add_filter(filefilter) + response = filechooser.run() + if response == Gtk.ResponseType.OK: + filename = filechooser.get_filename() + self.load_file(filename) + filechooser.destroy() + + elif response == Gtk.ResponseType.CANCEL: + filechooser.destroy() + + def check_change(self): + if self.did_change and len(self.get_text()): + dialog = Gtk.MessageDialog(self, + Gtk.DialogFlags.MODAL | Gtk.DialogFlags.DESTROY_WITH_PARENT, + Gtk.MessageType.WARNING, + None, + _("You have not saved your changes.") + ) + dialog.add_button(_("Close without Saving"), Gtk.ResponseType.NO) + dialog.add_button(_("Cancel"), Gtk.ResponseType.CANCEL) + dialog.add_button(_("Save now"), Gtk.ResponseType.YES).grab_focus() + dialog.set_title(_('Unsaved changes')) + dialog.set_default_size(200, 150) + response = dialog.run() + if response == Gtk.ResponseType.YES: + title = self.get_title() + if self.save_document(widget = None) == Gtk.ResponseType.CANCEL: + dialog.destroy() + return self.check_change() + else: + dialog.destroy() + return response + elif response == Gtk.ResponseType.CANCEL: + dialog.destroy() + return response + elif response == Gtk.ResponseType.NO: + dialog.destroy() + return response + + def new_document(self, widget): + if self.check_change() == Gtk.ResponseType.CANCEL: + return + else: + self.TextBuffer.set_text('') + self.TextEditor.undos = [] + self.TextEditor.redos = [] + + self.did_change = False + self.filename = None + self.set_title("New File" + self.title_end) + + def menu_activate_focusmode(self, widget): + self.focusmode_button.emit('activate') + + def menu_activate_fullscreen(self, widget): + self.fullscreen_button.emit('activate') + + def menu_activate_preview(self, widget): + self.preview_button.emit('activate') + + # Not added as menu button as of now. Standard is typewriter active. + def toggle_typewriter(self, widget, data=None): + self.typewriter_active = widget.get_active() + + def toggle_spellcheck(self, widget, data=None): + if self.spellcheck: + if widget.get_active(): + self.SpellChecker.enable() + else: + self.SpellChecker.disable() + elif widget.get_active(): + try: + self.SpellChecker = SpellChecker(self.TextEditor, locale.getdefaultlocale()[0], collapse=False) + self.spellcheck = True + except: + self.SpellChecker = None + self.spellcheck = False + dialog = Gtk.MessageDialog(self, + Gtk.DialogFlags.MODAL | Gtk.DialogFlags.DESTROY_WITH_PARENT, + Gtk.MessageType.INFO, + None, + _("You can not enable the Spell Checker.") + ) + dialog.format_secondary_text(_("Please install 'hunspell' or 'aspell' dictionarys for your language from the software center.")) + response = dialog.run() + return + return + + def on_drag_data_received(self, widget, drag_context, x, y, + data, info, time): + """Handle drag and drop events""" + + if info == 1: + # uri target + uris = data.get_uris() + for uri in uris: + uri = urllib.parse.unquote_plus(uri) + mime = mimetypes.guess_type(uri) + + if mime[0] is not None and mime[0].startswith('image'): + text = "![Insert image title here](%s)" % uri + ll = 2 + lr = 23 + else: + text = "[Insert link title here](%s)" % uri + ll = 1 + lr = 22 + + self.TextBuffer.insert_at_cursor(text) + insert_mark = self.TextBuffer.get_insert() + selection_bound = self.TextBuffer.get_selection_bound() + cursor_iter = self.TextBuffer.get_iter_at_mark(insert_mark) + cursor_iter.backward_chars(len(text) - ll) + self.TextBuffer.move_mark(insert_mark, cursor_iter) + cursor_iter.forward_chars(lr) + self.TextBuffer.move_mark(selection_bound, cursor_iter) + + elif info == 2: + # Text target + self.TextBuffer.insert_at_cursor(data.get_text()) + + self.present() + + def toggle_preview(self, widget, data=None): + if widget.get_active(): + # Insert a tag with ID to scroll to + # self.TextBuffer.insert_at_cursor('') + # TODO + # Find a way to find the next header, scroll to the next header. + + args = ['pandoc', + '--from=markdown', + '--smart', + '-thtml', + '--mathjax', + '-c', helpers.get_media_file('uberwriter.css')] + + p = subprocess.Popen(args, stdin=subprocess.PIPE, stdout=subprocess.PIPE) + + text = bytes(self.get_text(), "utf-8") + output = p.communicate(text)[0] + + # Load in Webview and scroll to #ID + self.webview = WebKit.WebView() + self.webview.load_html_string(output.decode("utf-8"), 'file://localhost/') + + # Delete the cursor-scroll mark again + # cursor_iter = self.TextBuffer.get_iter_at_mark(self.TextBuffer.get_insert()) + # begin_del = cursor_iter.copy() + # begin_del.backward_chars(30) + # self.TextBuffer.delete(begin_del, cursor_iter) + + self.ScrolledWindow.remove(self.TextEditor) + self.ScrolledWindow.add(self.webview) + self.webview.show() + + # Making the background white + + white_background = helpers.get_media_path('white.png') + surface = cairo.ImageSurface.create_from_png(white_background) + self.background_pattern = cairo.SurfacePattern(surface) + self.background_pattern.set_extend(cairo.EXTEND_REPEAT) + # This saying that all links will be opened in default browser, but local files are opened in appropriate apps: + self.webview.connect("navigation-requested", self.on_click_link) + else: + self.ScrolledWindow.remove(self.webview) + self.webview.destroy() + self.ScrolledWindow.add(self.TextEditor) + self.TextEditor.show() + surface = cairo.ImageSurface.create_from_png(self.background_image) + self.background_pattern = cairo.SurfacePattern(surface) + self.background_pattern.set_extend(cairo.EXTEND_REPEAT) + self.queue_draw() + + def on_click_link(self, view, frame, req, data=None): + # This provide ability for self.webview to open links in default browser + if(req.get_uri().startswith("http://")): + webbrowser.open(req.get_uri()) + return True # Don't let the event "bubble up" + + def dark_mode_toggled(self, widget, data=None): + # Save state for saving settings later + self.dark_mode = widget.get_active() + if self.dark_mode: + # Dark Mode is on + css = open(helpers.get_media_path('style_dark.css'), 'rb') + css_data = css.read() + css.close() + self.style_provider.load_from_data(css_data) + self.background_image = helpers.get_media_path('bg_dark.png') + self.MarkupBuffer.dark_mode(True) + + else: + # Dark mode off + css = open(helpers.get_media_path('style.css'), 'rb') + css_data = css.read() + css.close() + self.style_provider.load_from_data(css_data) + self.background_image = helpers.get_media_path('bg_light.png') + self.MarkupBuffer.dark_mode(False) + + surface = cairo.ImageSurface.create_from_png(self.background_image) + self.background_pattern = cairo.SurfacePattern(surface) + self.background_pattern.set_extend(cairo.EXTEND_REPEAT) + + Gtk.StyleContext.add_provider_for_screen( + Gdk.Screen.get_default(), self.style_provider, + Gtk.STYLE_PROVIDER_PRIORITY_APPLICATION + ) + # Redraw contents of window (self) + self.queue_draw() + + def load_file(self, filename=None): + """Open File from command line or open / open recent etc.""" + if filename: + if filename.startswith('file://'): + filename = filename[7:] + filename = urllib.parse.unquote_plus(filename) + try: + self.preview_button.set_active(False) + self.filename = filename + f = codecs.open(filename, encoding="utf-8", mode='r') + self.TextBuffer.set_text(f.read()) + f.close() + self.MarkupBuffer.markup_buffer(0) + self.set_title(os.path.basename(filename) + self.title_end) + self.TextEditor.undo_stack = [] + self.TextEditor.redo_stack = [] + # ei = self.TextBuffer.get_end_iter() + # anchor = self.TextBuffer.create_child_anchor(ei) + # al = Gtk.Label.new('asd') + # al.set_text('...') + # al.show() + # self.TextEditor.add_child_at_anchor(al, anchor) + + except Exception as e: + logger.warning("Error Reading File: %r" % e) + self.did_change = False + else: + logger.warning("No File arg") + + def draw_bg(self, widget, context): + context.set_source(self.background_pattern) + context.paint() + + # Help Menu + def open_launchpad_translation(self, widget, data=None): + webbrowser.open("https://translations.launchpad.net/uberwriter") + + def open_launchpad_help(self, widget, data=None): + webbrowser.open("https://answers.launchpad.net/uberwriter") + + def open_pandoc_markdown(self, widget, data=None): + webbrowser.open("http://johnmacfarlane.net/pandoc/README.html#pandocs-markdown") + + def open_uberwriter_markdown(self, widget, data=None): + self.load_file(helpers.get_media_file('uberwriter_markdown.md')) + + def open_search_and_replace(self, widget, data=None): + self.searchreplace.toggle_search() + + def open_advanced_export(self, widget, data=None): + if self.UberwriterAdvancedExportDialog is not None: + advexp = self.UberwriterAdvancedExportDialog() # pylint: disable= + + response = advexp.run() + if response == 1: + advexp.advanced_export(bytes(self.get_text(), "utf-8")) + + advexp.destroy() + + def open_recent(self, widget, data=None): + if data: + if self.check_change() == Gtk.ResponseType.CANCEL: + return + else: + self.load_file(data) + + def generate_recent_files_menu(self, parent_menu): + # Recent file filter + self.recent_manager = Gtk.RecentManager.get_default() + + self.recent_files_menu = Gtk.RecentChooserMenu.new_for_manager(self.recent_manager) + self.recent_files_menu.set_sort_type(Gtk.RecentSortType.MRU) + + recent_filter = Gtk.RecentFilter.new() + recent_filter.add_mime_type('text/x-markdown') + self.recent_files_menu.set_filter(recent_filter) + menu = Gtk.Menu.new() + + for entry in self.recent_files_menu.get_items(): + if entry.exists(): + item = Gtk.MenuItem.new_with_label(entry.get_display_name()) + item.connect('activate', self.open_recent, entry.get_uri()) + menu.append(item) + item.show() + + menu.show() + parent_menu.set_submenu(menu) + parent_menu.show() + + def poll_for_motion(self): + if (self.was_motion == False + and self.status_bar_visible + and self.buffer_modified_for_status_bar): + self.status_bar.set_state_flags(Gtk.StateFlags.INSENSITIVE, True) + self.status_bar_visible = False + self.buffer_modified_for_status_bar = False + return False + + self.was_motion = False + return True + + def on_motion_notify(self, widget, data=None): + self.was_motion = True + if self.status_bar_visible == False: + self.status_bar_visible = True + self.buffer_modified_for_status_bar = False + self.update_line_and_char_count() + self.status_bar.set_state_flags(Gtk.StateFlags.NORMAL, True) + GObject.timeout_add(3000, self.poll_for_motion) + + def move_popup(self, widget, data=None): + pass + + def finish_initializing(self, builder): # pylint: disable=E1002 + """Set up the main window""" + super(UberwriterWindow, self).finish_initializing(builder) + + self.AboutDialog = AboutUberwriterDialog + self.UberwriterAdvancedExportDialog = UberwriterAdvancedExportDialog + self.builder = builder + + # Code for other initialization actions should be added here. + + # Texlive checker + self.texlive_installed = False + + self.set_name('UberwriterWindow') + + self.title_end = " – UberWriter" + self.set_title("New File" + self.title_end) + + # Drag and drop + self.drag_dest_set(Gtk.DestDefaults.ALL, [], Gdk.DragAction.COPY) + + self.target_list = Gtk.TargetList.new([]) + self.target_list.add_uri_targets(1) + self.target_list.add_text_targets(2) + + self.drag_dest_set_target_list(self.target_list) + + self.focusmode = False + + self.word_count = builder.get_object('word_count') + self.char_count = builder.get_object('char_count') + self.menubar = builder.get_object('menubar1') + + # Wire up buttons + self.fullscreen_button = builder.get_object('fullscreen_toggle') + self.focusmode_button = builder.get_object('focus_toggle') + self.preview_button = builder.get_object('preview_toggle') + + self.fullscreen_button.set_name('fullscreen_toggle') + self.focusmode_button.set_name('focus_toggle') + self.preview_button.set_name('preview_toggle') + + # Setup status bar hide after 3 seconds + + self.status_bar = builder.get_object('status_bar_box') + self.status_bar.set_name('status_bar_box') + self.status_bar_visible = True + self.was_motion = True + self.buffer_modified_for_status_bar = False + self.connect("motion-notify-event", self.on_motion_notify) + GObject.timeout_add(3000, self.poll_for_motion) + + self.accel_group = Gtk.AccelGroup() + self.add_accel_group(self.accel_group) + + # Setup light background + + + self.TextEditor = TextEditor() + + base_leftmargin = 100 + self.TextEditor.set_left_margin(base_leftmargin) + self.TextEditor.set_left_margin(40) + + self.TextEditor.set_wrap_mode(Gtk.WrapMode.WORD) + + self.TextEditor.show() + + self.ScrolledWindow = builder.get_object('editor_scrolledwindow') + self.ScrolledWindow.add(self.TextEditor) + + # Draw background + self.background_image = helpers.get_media_path('bg_light.png') + self.ScrolledWindow.connect('draw', self.draw_bg) + surface = cairo.ImageSurface.create_from_png(self.background_image) + self.background_pattern = cairo.SurfacePattern(surface) + self.background_pattern.set_extend(cairo.EXTEND_REPEAT) + + + self.PreviewPane = builder.get_object('preview_scrolledwindow') + + pangoFont = Pango.FontDescription("Ubuntu Mono 15px") + + + # self.scw = builder.get_object('scrolledwindow1') + # self.scw.add(self.sidebar.get_treeview()) + + # http://nullege.com/codes/show/src%40c%40o%40comix-HEAD%40trunk%40src%40labels.py/31/gtk.Label.set_attributes/python + # ## TODO + # attr_list = Pango.AttrList.new() + # attr_list.insert(Pango.Attribute.LetterSpacing.new(100)) + + # self.TextEditor.set_attributes(attr_list) + + self.TextEditor.modify_font(pangoFont) + + self.TextEditor.set_margin_top(38) + self.TextEditor.set_margin_bottom(16) + + self.TextEditor.set_pixels_above_lines(4) + self.TextEditor.set_pixels_below_lines(4) + self.TextEditor.set_pixels_inside_wrap(8) + + tab_array = Pango.TabArray.new(1, True) + tab_array.set_tab(0, Pango.TabAlign.LEFT, 20) + self.TextEditor.set_tabs(tab_array) + + self.TextBuffer = self.TextEditor.get_buffer() + self.TextBuffer.set_text('') + + # Init Window height for top/bottom padding + + self.window_height = self.get_size()[1] + + self.text_change_event = self.TextBuffer.connect('changed', self.text_changed) + + self.TextEditor.connect('move-cursor', self.cursor_moved) + + # Init file name with None + self.filename = None + + self.generate_recent_files_menu(self.builder.get_object('recent')) + + self.style_provider = Gtk.CssProvider() + + css = open(helpers.get_media_path('style.css'), 'rb') + css_data = css.read() + css.close() + + self.style_provider.load_from_data(css_data) + + Gtk.StyleContext.add_provider_for_screen( + Gdk.Screen.get_default(), self.style_provider, + Gtk.STYLE_PROVIDER_PRIORITY_APPLICATION + ) + + # Still needed. + self.fflines = 0 + + # Markup and Shortcuts for the TextBuffer + self.MarkupBuffer = MarkupBuffer(self, self.TextBuffer, base_leftmargin) + self.MarkupBuffer.markup_buffer() + self.FormatShortcuts = FormatShortcuts(self.TextBuffer, self.TextEditor) + + # Scrolling -> Dark or not? + self.textchange = False + self.scroll_count = 0 + + self.TextBuffer.connect('mark-set', self.mark_set) + + self.TextEditor.drag_dest_unset() + + # Events to preserve margin. (To be deleted.) + self.TextEditor.connect('delete-from-cursor', self.delete_from_cursor) + self.TextEditor.connect('backspace', self.backspace) + + self.TextBuffer.connect('paste-done', self.paste_done) + # self.connect('key-press-event', self.alt_mod) + + # Events for Typewriter mode + self.TextBuffer.connect_after('mark-set', self.after_mark_set) + self.TextBuffer.connect_after('changed', self.after_modify_text) + self.TextEditor.connect_after('move-cursor', self.after_cursor_moved) + self.TextEditor.connect_after('insert-at-cursor', self.after_insert_at_cursor) + + # Setting up inline preview + self.InlinePreview = UberwriterInlinePreview(self.TextEditor, self.TextBuffer) + + # Vertical scrolling + self.vadjustment = self.TextEditor.get_vadjustment() + self.vadjustment.connect('value-changed', self.scrolled) + + # Setting up spellcheck + try: + self.SpellChecker = SpellChecker(self.TextEditor, + locale.getdefaultlocale()[0], collapse=False) + self.spellcheck = True + except: + self.SpellChecker = None + self.spellcheck = False + builder.get_object("disable_spellcheck").set_active(False) + + if self.spellcheck: + self.SpellChecker.append_filter('[#*]+', SpellChecker.FILTER_WORD) + + self.did_change = False + + ### + # Sidebar initialization test + ### + self.paned_window = builder.get_object("main_pained") + self.sidebar_box = builder.get_object("sidebar_box") + self.sidebar = UberwriterSidebar(self) + + ### + # Search and replace initialization + # Same interface as Sidebar ;) + ### + + self.searchreplace = UberwriterSearchAndReplace(self) + + + # Window resize + self.connect("configure-event", self.window_resize) + self.connect("delete-event", self.on_delete_called) + self.load_settings(builder) + + def alt_mod(self, widget, event, data=None): + # TODO: Click and open when alt is pressed + if event.state & Gdk.ModifierType.MOD2_MASK: + logger.info("Alt pressed") + return + + def on_delete_called(self, widget, data=None): + """Called when the TexteditorWindow is closed.""" + logger.info('delete called') + if self.check_change() == Gtk.ResponseType.CANCEL: + return True + return False + + def on_mnu_close_activate(self, widget, data=None): + """ + Signal handler for closing the UberwriterWindow. + Overriden from parent Window Class + """ + if self.on_delete_called(self): # Really destroy? + return + else: + self.destroy() + return + + def on_destroy(self, widget, data=None): + """Called when the TexteditorWindow is closed.""" + # Clean up code for saving application state should be added here. + self.window_close(widget) + self.save_settings() + Gtk.main_quit() + + def save_settings(self): + + if not os.path.exists(CONFIG_PATH): + try: + os.makedirs(CONFIG_PATH) + except Exception as e: + logger.debug("Failed to make uberwriter config path in\ + ~/.config/uberwriter. Error: %r" % e) + try: + settings = dict() + settings["dark_mode"] = self.dark_mode + settings["spellcheck"] = self.SpellChecker.enabled + f = open(CONFIG_PATH + "settings.pickle", "wb+") + pickle.dump(settings, f) + f.close() + logger.debug("Saved settings: %r" % settings) + except Exception as e: + logger.debug("Error writing settings file to disk. Error: %r" % e) + + def load_settings(self, builder): + dark_mode_button = builder.get_object("dark_mode") + spellcheck_button = builder.get_object("disable_spellcheck") + try: + f = open(CONFIG_PATH + "settings.pickle", "rb") + settings = pickle.load(f) + f.close() + self.dark_mode = settings['dark_mode'] + dark_mode_button.set_active(settings['dark_mode']) + spellcheck_button.set_active(settings['spellcheck']) + logger.debug("loaded settings: %r" % settings) + except Exception as e: + logger.debug("(First Run?) Error loading settings from home dir. \ + Error: %r", e) + return 1 diff --git a/build/lib/uberwriter/__init__.py b/build/lib/uberwriter/__init__.py new file mode 100644 index 0000000..633752e --- /dev/null +++ b/build/lib/uberwriter/__init__.py @@ -0,0 +1,56 @@ +# -*- Mode: Python; coding: utf-8; indent-tabs-mode: nil; tab-width: 4 -*- +### BEGIN LICENSE +# Copyright (C) 2012, Wolf Vollprecht +# This program is free software: you can redistribute it and/or modify it +# under the terms of the GNU General Public License version 3, as published +# by the Free Software Foundation. +# +# This program is distributed in the hope that it will be useful, but +# WITHOUT ANY WARRANTY; without even the implied warranties of +# MERCHANTABILITY, SATISFACTORY QUALITY, or FITNESS FOR A PARTICULAR +# PURPOSE. See the GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License along +# with this program. If not, see . +### END LICENSE + +import optparse + +import locale +import os +from locale import gettext as _ +locale.textdomain('uberwriter') + +from gi.repository import Gtk # pylint: disable=E0611 + +from . import UberwriterWindow + +from uberwriter_lib import set_up_logging, get_version + +def parse_options(): + """Support for command line options""" + parser = optparse.OptionParser(version="%%prog %s" % get_version()) + parser.add_option( + "-v", "--verbose", action="count", dest="verbose", + help=_("Show debug messages (-vv debugs uberwriter_lib also)")) + (options, args) = parser.parse_args() + + set_up_logging(options) + + # print args + + return options, args + +def main(): + 'constructor for your class instances' + (options, args) = parse_options() + + # Run the application. + if args: + for arg in args: + window = UberwriterWindow.UberwriterWindow() + window.load_file(arg) + else: + window = UberwriterWindow.UberwriterWindow() + window.show() + Gtk.main() diff --git a/build/lib/uberwriter_lib/AboutDialog.py b/build/lib/uberwriter_lib/AboutDialog.py new file mode 100644 index 0000000..262ccb5 --- /dev/null +++ b/build/lib/uberwriter_lib/AboutDialog.py @@ -0,0 +1,50 @@ +# -*- Mode: Python; coding: utf-8; indent-tabs-mode: nil; tab-width: 4 -*- +### BEGIN LICENSE +# Copyright (C) 2012, Wolf Vollprecht +# This program is free software: you can redistribute it and/or modify it +# under the terms of the GNU General Public License version 3, as published +# by the Free Software Foundation. +# +# This program is distributed in the hope that it will be useful, but +# WITHOUT ANY WARRANTY; without even the implied warranties of +# MERCHANTABILITY, SATISFACTORY QUALITY, or FITNESS FOR A PARTICULAR +# PURPOSE. See the GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License along +# with this program. If not, see . +### END LICENSE + +### DO NOT EDIT THIS FILE ### + +from gi.repository import Gtk # pylint: disable=E0611 + +from . helpers import get_builder + +class AboutDialog(Gtk.AboutDialog): + __gtype_name__ = "AboutDialog" + + def __new__(cls): + """Special static method that's automatically called by Python when + constructing a new instance of this class. + + Returns a fully instantiated AboutDialog object. + """ + builder = get_builder('AboutUberwriterDialog') + new_object = builder.get_object("about_uberwriter_dialog") + new_object.finish_initializing(builder) + return new_object + + def finish_initializing(self, builder): + """Called while initializing this instance in __new__ + + finish_initalizing should be called after parsing the ui definition + and creating a AboutDialog object with it in order + to finish initializing the start of the new AboutUberwriterDialog + instance. + + Put your initialization code in here and leave __init__ undefined. + """ + # Get a reference to the builder and set up the signals. + self.builder = builder + self.ui = builder.get_ui(self) + diff --git a/build/lib/uberwriter_lib/AdvancedExportDialog.py b/build/lib/uberwriter_lib/AdvancedExportDialog.py new file mode 100644 index 0000000..57f2ed9 --- /dev/null +++ b/build/lib/uberwriter_lib/AdvancedExportDialog.py @@ -0,0 +1,48 @@ +# -*- Mode: Python; coding: utf-8; indent-tabs-mode: nil; tab-width: 4 -*- +### BEGIN LICENSE +# Copyright (C) 2012, Wolf Vollprecht +# This program is free software: you can redistribute it and/or modify it +# under the terms of the GNU General Public License version 3, as published +# by the Free Software Foundation. +# +# This program is distributed in the hope that it will be useful, but +# WITHOUT ANY WARRANTY; without even the implied warranties of +# MERCHANTABILITY, SATISFACTORY QUALITY, or FITNESS FOR A PARTICULAR +# PURPOSE. See the GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License along +# with this program. If not, see . +### END LICENSE + +from gi.repository import Gtk # pylint: disable=E0611 + +from . helpers import get_builder + +class AdvancedExportDialog(Gtk.Dialog): + __gtype_name__ = "AdvancedExportDialog" + + def __new__(cls): + """Special static method that's automatically called by Python when + constructing a new instance of this class. + + Returns a fully instantiated AdvancedExportDialog object. + """ + builder = get_builder('UberwriterAdvancedExportDialog') + new_object = builder.get_object("uberwriter_advanced_export_dialog") + new_object.finish_initializing(builder) + return new_object + + def finish_initializing(self, builder): + """Called while initializing this instance in __new__ + + finish_initalizing should be called after parsing the ui definition + and creating a AdvancedExportDialog object with it in order + to finish initializing the start of the new AboutUberwriterDialog + instance. + + Put your initialization code in here and leave __init__ undefined. + """ + # Get a reference to the builder and set up the signals. + self.builder = builder + self.ui = builder.get_ui(self) + diff --git a/build/lib/uberwriter_lib/Builder.py b/build/lib/uberwriter_lib/Builder.py new file mode 100644 index 0000000..39cbcb5 --- /dev/null +++ b/build/lib/uberwriter_lib/Builder.py @@ -0,0 +1,325 @@ +# -*- Mode: Python; coding: utf-8; indent-tabs-mode: nil; tab-width: 4 -*- +### BEGIN LICENSE +# Copyright (C) 2012, Wolf Vollprecht +# This program is free software: you can redistribute it and/or modify it +# under the terms of the GNU General Public License version 3, as published +# by the Free Software Foundation. +# +# This program is distributed in the hope that it will be useful, but +# WITHOUT ANY WARRANTY; without even the implied warranties of +# MERCHANTABILITY, SATISFACTORY QUALITY, or FITNESS FOR A PARTICULAR +# PURPOSE. See the GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License along +# with this program. If not, see . +### END LICENSE + +### DO NOT EDIT THIS FILE ### + +'''Enhances builder connections, provides object to access glade objects''' + +from gi.repository import GObject, Gtk # pylint: disable=E0611 + +import inspect +import functools +import logging +logger = logging.getLogger('uberwriter_lib') + +from xml.etree.cElementTree import ElementTree + +# this module is big so uses some conventional prefixes and postfixes +# *s list, except self.widgets is a dictionary +# *_dict dictionary +# *name string +# ele_* element in a ElementTree + + +# pylint: disable=R0904 +# the many public methods is a feature of Gtk.Builder +class Builder(Gtk.Builder): + ''' extra features + connects glade defined handler to default_handler if necessary + auto connects widget to handler with matching name or alias + auto connects several widgets to a handler via multiple aliases + allow handlers to lookup widget name + logs every connection made, and any on_* not made + ''' + + def __init__(self): + Gtk.Builder.__init__(self) + self.widgets = {} + self.glade_handler_dict = {} + self.connections = [] + self._reverse_widget_dict = {} + +# pylint: disable=R0201 +# this is a method so that a subclass of Builder can redefine it + def default_handler(self, + handler_name, filename, *args, **kwargs): + '''helps the apprentice guru + + glade defined handlers that do not exist come here instead. + An apprentice guru might wonder which signal does what he wants, + now he can define any likely candidates in glade and notice which + ones get triggered when he plays with the project. + this method does not appear in Gtk.Builder''' + logger.debug('''tried to call non-existent function:%s() + expected in %s + args:%s + kwargs:%s''', handler_name, filename, args, kwargs) +# pylint: enable=R0201 + + def get_name(self, widget): + ''' allows a handler to get the name (id) of a widget + + this method does not appear in Gtk.Builder''' + return self._reverse_widget_dict.get(widget) + + def add_from_file(self, filename): + '''parses xml file and stores wanted details''' + Gtk.Builder.add_from_file(self, filename) + + # extract data for the extra interfaces + tree = ElementTree() + tree.parse(filename) + + ele_widgets = tree.getiterator("object") + for ele_widget in ele_widgets: + name = ele_widget.attrib['id'] + widget = self.get_object(name) + + # populate indexes - a dictionary of widgets + self.widgets[name] = widget + + # populate a reversed dictionary + self._reverse_widget_dict[widget] = name + + # populate connections list + ele_signals = ele_widget.findall("signal") + + connections = [ + (name, + ele_signal.attrib['name'], + ele_signal.attrib['handler']) for ele_signal in ele_signals] + + if connections: + self.connections.extend(connections) + + ele_signals = tree.getiterator("signal") + for ele_signal in ele_signals: + self.glade_handler_dict.update( + {ele_signal.attrib["handler"]: None}) + + def connect_signals(self, callback_obj): + '''connect the handlers defined in glade + + reports successful and failed connections + and logs call to missing handlers''' + filename = inspect.getfile(callback_obj.__class__) + callback_handler_dict = dict_from_callback_obj(callback_obj) + connection_dict = {} + connection_dict.update(self.glade_handler_dict) + connection_dict.update(callback_handler_dict) + for item in connection_dict.items(): + if item[1] is None: + # the handler is missing so reroute to default_handler + handler = functools.partial( + self.default_handler, item[0], filename) + + connection_dict[item[0]] = handler + + # replace the run time warning + logger.warn("expected handler '%s' in %s", + item[0], filename) + + # connect glade define handlers + Gtk.Builder.connect_signals(self, connection_dict) + + # let's tell the user how we applied the glade design + for connection in self.connections: + widget_name, signal_name, handler_name = connection + logger.debug("connect builder by design '%s', '%s', '%s'", + widget_name, signal_name, handler_name) + + def get_ui(self, callback_obj=None, by_name=True): + '''Creates the ui object with widgets as attributes + + connects signals by 2 methods + this method does not appear in Gtk.Builder''' + + result = UiFactory(self.widgets) + + # Hook up any signals the user defined in glade + if callback_obj is not None: + # connect glade define handlers + self.connect_signals(callback_obj) + + if by_name: + auto_connect_by_name(callback_obj, self) + + return result + + +# pylint: disable=R0903 +# this class deliberately does not provide any public interfaces +# apart from the glade widgets +class UiFactory(): + ''' provides an object with attributes as glade widgets''' + def __init__(self, widget_dict): + self._widget_dict = widget_dict + for (widget_name, widget) in widget_dict.items(): + setattr(self, widget_name, widget) + + # Mangle any non-usable names (like with spaces or dashes) + # into pythonic ones + cannot_message = """cannot bind ui.%s, name already exists + consider using a pythonic name instead of design name '%s'""" + consider_message = """consider using a pythonic name instead of design name '%s'""" + + for (widget_name, widget) in widget_dict.items(): + pyname = make_pyname(widget_name) + if pyname != widget_name: + if hasattr(self, pyname): + logger.debug(cannot_message, pyname, widget_name) + else: + logger.debug(consider_message, widget_name) + setattr(self, pyname, widget) + + def iterator(): + '''Support 'for o in self' ''' + return iter(widget_dict.values()) + setattr(self, '__iter__', iterator) + + def __getitem__(self, name): + 'access as dictionary where name might be non-pythonic' + return self._widget_dict[name] +# pylint: enable=R0903 + + +def make_pyname(name): + ''' mangles non-pythonic names into pythonic ones''' + pyname = '' + for character in name: + if (character.isalpha() or character == '_' or + (pyname and character.isdigit())): + pyname += character + else: + pyname += '_' + return pyname + + +# Until bug https://bugzilla.gnome.org/show_bug.cgi?id=652127 is fixed, we +# need to reimplement inspect.getmembers. GObject introspection doesn't +# play nice with it. +def getmembers(obj, check): + members = [] + for k in dir(obj): + try: + attr = getattr(obj, k) + except: + continue + if check(attr): + members.append((k, attr)) + members.sort() + return members + + +def dict_from_callback_obj(callback_obj): + '''a dictionary interface to callback_obj''' + methods = getmembers(callback_obj, inspect.ismethod) + + aliased_methods = [x[1] for x in methods if hasattr(x[1], 'aliases')] + + # a method may have several aliases + #~ @alias('on_btn_foo_clicked') + #~ @alias('on_tool_foo_activate') + #~ on_menu_foo_activate(): + #~ pass + alias_groups = [(x.aliases, x) for x in aliased_methods] + + aliases = [] + for item in alias_groups: + for alias in item[0]: + aliases.append((alias, item[1])) + + dict_methods = dict(methods) + dict_aliases = dict(aliases) + + results = {} + results.update(dict_methods) + results.update(dict_aliases) + + return results + + +def auto_connect_by_name(callback_obj, builder): + '''finds handlers like on__ and connects them + + i.e. find widget,signal pair in builder and call + widget.connect(signal, on__)''' + + callback_handler_dict = dict_from_callback_obj(callback_obj) + + for item in builder.widgets.items(): + (widget_name, widget) = item + signal_ids = [] + try: + widget_type = type(widget) + while widget_type: + signal_ids.extend(GObject.signal_list_ids(widget_type)) + widget_type = GObject.type_parent(widget_type) + except RuntimeError: # pylint wants a specific error + pass + signal_names = [GObject.signal_name(sid) for sid in signal_ids] + + # Now, automatically find any the user didn't specify in glade + for sig in signal_names: + # using convention suggested by glade + sig = sig.replace("-", "_") + handler_names = ["on_%s_%s" % (widget_name, sig)] + + # Using the convention that the top level window is not + # specified in the handler name. That is use + # on_destroy() instead of on_windowname_destroy() + if widget is callback_obj: + handler_names.append("on_%s" % sig) + + do_connect(item, sig, handler_names, + callback_handler_dict, builder.connections) + + log_unconnected_functions(callback_handler_dict, builder.connections) + + +def do_connect(item, signal_name, handler_names, + callback_handler_dict, connections): + '''connect this signal to an unused handler''' + widget_name, widget = item + + for handler_name in handler_names: + target = handler_name in callback_handler_dict.keys() + connection = (widget_name, signal_name, handler_name) + duplicate = connection in connections + if target and not duplicate: + widget.connect(signal_name, callback_handler_dict[handler_name]) + connections.append(connection) + + logger.debug("connect builder by name '%s','%s', '%s'", + widget_name, signal_name, handler_name) + + +def log_unconnected_functions(callback_handler_dict, connections): + '''log functions like on_* that we could not connect''' + + connected_functions = [x[2] for x in connections] + + handler_names = callback_handler_dict.keys() + unconnected = [x for x in handler_names if x.startswith('on_')] + + for handler_name in connected_functions: + try: + unconnected.remove(handler_name) + except ValueError: + pass + + for handler_name in unconnected: + logger.debug("Not connected to builder '%s'", handler_name) diff --git a/build/lib/uberwriter_lib/LatexToPNG.py b/build/lib/uberwriter_lib/LatexToPNG.py new file mode 100644 index 0000000..858962e --- /dev/null +++ b/build/lib/uberwriter_lib/LatexToPNG.py @@ -0,0 +1,108 @@ +# -*- Mode: Python; coding: utf-8; indent-tabs-mode: nil; tab-width: 4 -*- +""" +Based on latex2png.py from Stuart Rackham + +AUTHOR + Written by Stuart Rackham, + The code was inspired by Kjell Magne Fauske's code: + http://fauskes.net/nb/htmleqII/ + + See also: + http://www.amk.ca/python/code/mt-math + http://code.google.com/p/latexmath2png/ + +COPYING + Copyright (C) 2010 Stuart Rackham. Free use of this software is + granted under the terms of the MIT License. +""" + +import os, sys, tempfile, subprocess + +class LatexToPNG(): + + TEX_HEADER = r'''\documentclass{article} + \usepackage{amsmath} + \usepackage{amsthm} + \usepackage{amssymb} + \usepackage{bm} + \newcommand{\mx}[1]{\mathbf{\bm{#1}}} % Matrix command + \newcommand{\vc}[1]{\mathbf{\bm{#1}}} % Vector command + \newcommand{\T}{\text{T}} % Transpose + \pagestyle{empty} + \begin{document}''' + + TEX_FOOTER = r'''\end{document}''' + + def __init__(self): + self.temp_result = tempfile.NamedTemporaryFile(suffix='.png') + + def latex2png(self, tex, outfile, dpi, modified): + '''Convert LaTeX input file infile to PNG file named outfile.''' + outfile = os.path.abspath(outfile) + outdir = os.path.dirname(outfile) + texfile = tempfile.mktemp(suffix='.tex', dir=os.path.dirname(outfile)) + basefile = os.path.splitext(texfile)[0] + dvifile = basefile + '.dvi' + temps = [basefile + ext for ext in ('.tex','.dvi', '.aux', '.log')] + skip = False + + tex = '%s\n%s\n%s\n' % (self.TEX_HEADER, tex.strip(), self.TEX_FOOTER) + + open(texfile, 'w').write(tex) + saved_pwd = os.getcwd() + + os.chdir(outdir) + + args = ['latex', '-halt-on-error', texfile] + p = subprocess.Popen(args, + stderr=subprocess.STDOUT, + stdout=subprocess.PIPE) + + output = p.stdout + output_lines = output.readlines() + if os.path.isfile(dvifile): # DVI File exists + # Convert DVI file to PNG. + args = ['dvipng', + '-D', str(dpi), + '-T', 'tight', + '-x', '1000', + '-z', '9', + '-bg', 'Transparent', + '-o', outfile, + dvifile] + + p = subprocess.Popen(args) + p.communicate() + + else: + self.clean_up(temps) + ''' + Errors in Latex output start with "! " + Stripping exclamation marks and superflous newlines + and telling the user what he's done wrong. + ''' + i = [] + error = "" + for line in output_lines: + line = line.decode('utf-8') + if line.startswith("!"): + error += line[2:] # removing "! " + if error.endswith("\n"): + error = error[:-1] + raise Exception(error) + + def generatepng(self, formula): + try: + self.temp_result = tempfile.NamedTemporaryFile(suffix='.png') + formula = "$" + formula + "$" + self.latex2png(formula, self.temp_result.name, 300, False) + return (True, self.temp_result.name) + + except Exception as e: + self.temp_result.close() + return (False, e.args[0]) + + def clean_up(self, files): + for f in files: + if os.path.isfile(f): + os.remove(f) \ No newline at end of file diff --git a/build/lib/uberwriter_lib/PreferencesDialog.py b/build/lib/uberwriter_lib/PreferencesDialog.py new file mode 100644 index 0000000..14d1c72 --- /dev/null +++ b/build/lib/uberwriter_lib/PreferencesDialog.py @@ -0,0 +1,64 @@ +# -*- Mode: Python; coding: utf-8; indent-tabs-mode: nil; tab-width: 4 -*- +### BEGIN LICENSE +# Copyright (C) 2012, Wolf Vollprecht +# This program is free software: you can redistribute it and/or modify it +# under the terms of the GNU General Public License version 3, as published +# by the Free Software Foundation. +# +# This program is distributed in the hope that it will be useful, but +# WITHOUT ANY WARRANTY; without even the implied warranties of +# MERCHANTABILITY, SATISFACTORY QUALITY, or FITNESS FOR A PARTICULAR +# PURPOSE. See the GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License along +# with this program. If not, see . +### END LICENSE + +### DO NOT EDIT THIS FILE ### + +"""this dialog adjusts values in gsettings +""" + +from gi.repository import Gtk # pylint: disable=E0611 +import logging +logger = logging.getLogger('uberwriter_lib') + +from . helpers import get_builder, show_uri, get_help_uri + +class PreferencesDialog(Gtk.Dialog): + __gtype_name__ = "PreferencesDialog" + + def __new__(cls): + """Special static method that's automatically called by Python when + constructing a new instance of this class. + + Returns a fully instantiated PreferencesDialog object. + """ + builder = get_builder('PreferencesUberwriterDialog') + new_object = builder.get_object("preferences_uberwriter_dialog") + new_object.finish_initializing(builder) + return new_object + + def finish_initializing(self, builder): + """Called while initializing this instance in __new__ + + finish_initalizing should be called after parsing the ui definition + and creating a PreferencesDialog object with it in order to + finish initializing the start of the new PerferencesUberwriterDialog + instance. + + Put your initialization code in here and leave __init__ undefined. + """ + + # Get a reference to the builder and set up the signals. + self.builder = builder + self.ui = builder.get_ui(self, True) + + # code for other initialization actions should be added here + + def on_btn_close_clicked(self, widget, data=None): + self.destroy() + + def on_btn_help_clicked(self, widget, data=None): + show_uri(self, "ghelp:%s" % get_help_uri('preferences')) + diff --git a/build/lib/uberwriter_lib/Window.py b/build/lib/uberwriter_lib/Window.py new file mode 100644 index 0000000..4fe72a4 --- /dev/null +++ b/build/lib/uberwriter_lib/Window.py @@ -0,0 +1,129 @@ +# -*- Mode: Python; coding: utf-8; indent-tabs-mode: nil; tab-width: 4 -*- +### BEGIN LICENSE +# Copyright (C) 2012, Wolf Vollprecht +# This program is free software: you can redistribute it and/or modify it +# under the terms of the GNU General Public License version 3, as published +# by the Free Software Foundation. +# +# This program is distributed in the hope that it will be useful, but +# WITHOUT ANY WARRANTY; without even the implied warranties of +# MERCHANTABILITY, SATISFACTORY QUALITY, or FITNESS FOR A PARTICULAR +# PURPOSE. See the GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License along +# with this program. If not, see . +### END LICENSE + +### DO NOT EDIT THIS FILE ### + +from gi.repository import Gio, Gtk # pylint: disable=E0611 +import logging +logger = logging.getLogger('uberwriter_lib') + +from . helpers import get_builder, show_uri, get_help_uri + +# This class is meant to be subclassed by UberwriterWindow. It provides +# common functions and some boilerplate. +class Window(Gtk.Window): + __gtype_name__ = "Window" + + # To construct a new instance of this method, the following notable + # methods are called in this order: + # __new__(cls) + # __init__(self) + # finish_initializing(self, builder) + # __init__(self) + # + # For this reason, it's recommended you leave __init__ empty and put + # your initialization code in finish_initializing + + def __new__(cls): + """Special static method that's automatically called by Python when + constructing a new instance of this class. + + Returns a fully instantiated BaseUberwriterWindow object. + """ + builder = get_builder('UberwriterWindow') + new_object = builder.get_object("uberwriter_window") + new_object.finish_initializing(builder) + return new_object + + def finish_initializing(self, builder): + """Called while initializing this instance in __new__ + + finish_initializing should be called after parsing the UI definition + and creating a UberwriterWindow object with it in order to finish + initializing the start of the new UberwriterWindow instance. + """ + # Get a reference to the builder and set up the signals. + self.builder = builder + self.ui = builder.get_ui(self, True) + self.PreferencesDialog = None # class + self.preferences_dialog = None # instance + self.AboutDialog = None # class + + self.settings = Gio.Settings("net.launchpad.uberwriter") + self.settings.connect('changed', self.on_preferences_changed) + + # Optional application indicator support + # Run 'quickly add indicator' to get started. + # More information: + # http://owaislone.org/quickly-add-indicator/ + # https://wiki.ubuntu.com/DesktopExperienceTeam/ApplicationIndicators + try: + from uberwriter import indicator + # self is passed so methods of this class can be called from indicator.py + # Comment this next line out to disable appindicator + self.indicator = indicator.new_application_indicator(self) + except ImportError: + pass + + def on_mnu_contents_activate(self, widget, data=None): + show_uri(self, "ghelp:%s" % get_help_uri()) + + def on_mnu_about_activate(self, widget, data=None): + """Display the about box for uberwriter.""" + if self.AboutDialog is not None: + about = self.AboutDialog() # pylint: disable=E1102 + response = about.run() + about.destroy() + + def on_mnu_preferences_activate(self, widget, data=None): + """Display the preferences window for uberwriter.""" + + """ From the PyGTK Reference manual + Say for example the preferences dialog is currently open, + and the user chooses Preferences from the menu a second time; + use the present() method to move the already-open dialog + where the user can see it.""" + if self.preferences_dialog is not None: + logger.debug('show existing preferences_dialog') + self.preferences_dialog.present() + elif self.PreferencesDialog is not None: + logger.debug('create new preferences_dialog') + self.preferences_dialog = self.PreferencesDialog() # pylint: disable=E1102 + self.preferences_dialog.connect('destroy', self.on_preferences_dialog_destroyed) + self.preferences_dialog.show() + # destroy command moved into dialog to allow for a help button + + def on_mnu_close_activate(self, widget, data=None): + """Signal handler for closing the UberwriterWindow.""" + self.destroy() + + def on_destroy(self, widget, data=None): + """Called when the UberwriterWindow is closed.""" + # Clean up code for saving application state should be added here. + Gtk.main_quit() + + def on_preferences_changed(self, settings, key, data=None): + logger.debug('preference changed: %s = %s' % (key, str(settings.get_value(key)))) + + def on_preferences_dialog_destroyed(self, widget, data=None): + '''only affects gui + + logically there is no difference between the user closing, + minimising or ignoring the preferences dialog''' + logger.debug('on_preferences_dialog_destroyed') + # to determine whether to create or present preferences_dialog + self.preferences_dialog = None + diff --git a/build/lib/uberwriter_lib/__init__.py b/build/lib/uberwriter_lib/__init__.py new file mode 100644 index 0000000..5ec5c82 --- /dev/null +++ b/build/lib/uberwriter_lib/__init__.py @@ -0,0 +1,25 @@ +# -*- Mode: Python; coding: utf-8; indent-tabs-mode: nil; tab-width: 4 -*- +### BEGIN LICENSE +# Copyright (C) 2012, Wolf Vollprecht +# This program is free software: you can redistribute it and/or modify it +# under the terms of the GNU General Public License version 3, as published +# by the Free Software Foundation. +# +# This program is distributed in the hope that it will be useful, but +# WITHOUT ANY WARRANTY; without even the implied warranties of +# MERCHANTABILITY, SATISFACTORY QUALITY, or FITNESS FOR A PARTICULAR +# PURPOSE. See the GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License along +# with this program. If not, see . +### END LICENSE + +### DO NOT EDIT THIS FILE ### + +'''facade - makes uberwriter_lib package easy to refactor + +while keeping its api constant''' +from . helpers import set_up_logging +from . Window import Window +from . uberwriterconfig import get_version + diff --git a/build/lib/uberwriter_lib/gtkspellcheck/__init__.py b/build/lib/uberwriter_lib/gtkspellcheck/__init__.py new file mode 100644 index 0000000..0c3f557 --- /dev/null +++ b/build/lib/uberwriter_lib/gtkspellcheck/__init__.py @@ -0,0 +1,57 @@ +# -*- coding:utf-8 -*- +# +# Copyright (C) 2012, Maximilian Köhl +# Copyright (C) 2012, Carlos Jenkins +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program. If not, see . + +# Python 2/3 unicode +import sys +if sys.version_info.major == 3: + u = lambda x: x +else: + u = lambda x: x.decode('utf-8') + +# Metadata +__version__ = '3.0' +__project__ = 'Python GTK Spellcheck' +__short_name__ = 'pygtkspellcheck' +__authors__ = u('Maximilian Köhl & Carlos Jenkins') +__emails__ = u('linuxmaxi@googlemail.com & carlos@jenkins.co.cr') +__website__ = 'http://koehlma.github.com/projects/pygtkspellcheck.html' +__download_url__ = 'https://github.com/koehlma/pygtkspellcheck/tarball/master' +__source__ = 'https://github.com/koehlma/pygtkspellcheck/' +__vcs__ = 'git://github.com/koehlma/pygtkspellcheck.git' +__copyright__ = u('2012, Maximilian Köhl & Carlos Jenkins') +__desc_short__ = 'A simple but quite powerful Python spell checking library for GtkTextViews based on Enchant.' +__desc_long__ = ('It supports both Gtk\'s Python bindings, PyGObject and' + 'PyGtk, and for both Python 2 and 3 with automatic switching' + 'and binding autodetection. For automatic translation of the' + 'user interface it can use GEdit\'s translation files.') + +__metadata__ = {'__version__' : __version__, + '__project__' : __project__, + '__short_name__' : __short_name__, + '__authors__' : __authors__, + '__emails__' : __emails__, + '__website__' : __website__, + '__download_url__' : __download_url__, + '__source__' : __source__, + '__vcs__' : __vcs__, + '__copyright__' : __copyright__, + '__desc_short__' : __desc_short__, + '__desc_long__' : __desc_long__} + +# import SpellChecker class +from . spellcheck import SpellChecker \ No newline at end of file diff --git a/build/lib/uberwriter_lib/gtkspellcheck/spellcheck.py b/build/lib/uberwriter_lib/gtkspellcheck/spellcheck.py new file mode 100644 index 0000000..001b7aa --- /dev/null +++ b/build/lib/uberwriter_lib/gtkspellcheck/spellcheck.py @@ -0,0 +1,638 @@ +# -*- coding:utf-8 -*- +# +# Copyright (C) 2012, Maximilian Köhl +# Copyright (C) 2012, Carlos Jenkins +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program. If not, see . + +""" +A simple but quite powerful spellchecking library written in pure Python for Gtk +based on Enchant. It supports PyGObject as well as PyGtk for Python 2 and 3 with +automatic switching and binding detection. For automatic translation of the user +interface it can use Gedit’s translation files. +""" + +import enchant +import gettext +import logging +import re +import sys + +from ..pylocales import code_to_name + +# public objects +__all__ = ['SpellChecker', 'NoDictionariesFound', 'NoGtkBindingFound'] + +# logger +logger = logging.getLogger(__name__) + +class NoDictionariesFound(Exception): + """ + There aren't any dictionaries installed on the current system so + spellchecking could not work in any way. + """ + +class NoGtkBindingFound(Exception): + """ + Could not find any loaded Gtk binding. + """ + +# find any loaded gtk binding +if 'gi.repository.Gtk' in sys.modules: + gtk = sys.modules['gi.repository.Gtk'] + _pygobject = True +elif 'gtk' in sys.modules: + gtk = sys.modules['gtk'] + _pygobject = False +else: + raise NoGtkBindingFound('could not find any loaded Gtk binding') + +# select base list class +try: + from collections import UserList + _list = UserList +except ImportError: + _list = list + +if sys.version_info.major == 3: + _py3k = True +else: + _py3k = False + +# select base string +if _py3k: + basestring = str + +# map between Gedit's translation and PyGtkSpellcheck's +_GEDIT_MAP = {'Languages' : 'Languages', + 'Ignore All' : 'Ignore _All', + 'Suggestions' : 'Suggestions', + '(no suggestions)' : '(no suggested words)', + 'Add "{}" to Dictionary' : 'Add w_ord'} + +# translation +if gettext.find('gedit'): + _gedit = gettext.translation('gedit', fallback=True).gettext + _ = lambda message: _gedit(_GEDIT_MAP[message]).replace('_', '') +else: + locale_name = 'py{}gtkspellcheck'.format(sys.version_info.major) + _ = gettext.translation(locale_name, fallback=True).gettext + +class SpellChecker(object): + """ + Main spellchecking class, everything important happens here. + + :param view: GtkTextView the SpellChecker should be attached to. + :param language: The language which should be used for spellchecking. + Use a combination of two letter lower-case ISO 639 language code with a + two letter upper-case ISO 3166 country code, for example en_US or de_DE. + :param prefix: A prefix for some internal GtkTextMarks. + :param collapse: Enclose suggestions in its own menu. + :param params: Dictionary with Enchant broker parameters that should be set + e.g. `enchant.myspell.dictionary.path`. + + .. attribute:: languages + + A list of supported languages. + + .. function:: exists(language) + + Checks if a language exists. + + :param language: language to check + """ + FILTER_WORD = 'word' + FILTER_LINE = 'line' + FILTER_TEXT = 'text' + + DEFAULT_FILTERS = {FILTER_WORD : [r'[0-9.,]+'], + FILTER_LINE : [(r'(https?|ftp|file):((//)|(\\\\))+[\w\d:' + r'#@%/;$()~_?+-=\\.&]+'), + r'[\w\d]+@[\w\d.]+'], + FILTER_TEXT : []} + + class _LanguageList(_list): + def __init__(self, *args, **kwargs): + if sys.version_info.major == 3: + super().__init__(*args, **kwargs) + else: + _list.__init__(self, *args, **kwargs) + self.mapping = dict(self) + + @classmethod + def from_broker(cls, broker): + return cls(sorted([(language, code_to_name(language)) + for language in broker.list_languages()], + key=lambda language: language[1])) + + def exists(self, language): + return language in self.mapping + + class _Mark(): + def __init__(self, buffer, name, start): + self._buffer = buffer + self._name = name + self._mark = self._buffer.create_mark(self._name, start, True) + + @property + def iter(self): + return self._buffer.get_iter_at_mark(self._mark) + + @property + def inside_word(self): + return self.iter.inside_word() + + @property + def word(self): + start = self.iter + if not start.starts_word(): + start.backward_word_start() + end = self.iter + if end.inside_word(): + end.forward_word_end() + return start, end + + def move(self, location): + self._buffer.move_mark(self._mark, location) + + def __init__(self, view, language='en', prefix='gtkspellchecker', + collapse=True, params={}): + self._view = view + self.collapse = collapse + self._view.connect('populate-popup', + lambda entry, menu:self._extend_menu(menu)) + self._view.connect('popup-menu', self._click_move_popup) + self._view.connect('button-press-event', self._click_move_button) + self._prefix = prefix + if _pygobject: + self._misspelled = gtk.TextTag.new('{}-misspelled'\ + .format(self._prefix)) + else: + self._misspelled = gtk.TextTag('{}-misspelled'.format(self._prefix)) + self._misspelled.set_property('underline', 4) + self._broker = enchant.Broker() + for param, value in params.items(): self._broker.set_param(param, value) + self.languages = SpellChecker._LanguageList.from_broker(self._broker) + if self.languages.exists(language): + self._language = language + elif self.languages.exists('en'): + logger.warning(('no installed dictionary for language "{}", ' + 'fallback to english'.format(language))) + self._language = 'en' + else: + if self.languages: + self._language = self.languages[0][0] + logger.warning(('no installed dictionary for language "{}" ' + 'and english, fallback to first language in' + 'language list ("{}")').format(language, + self._language)) + else: + logger.critical('no dictionaries found') + raise NoDictionariesFound() + self._dictionary = self._broker.request_dict(self._language) + self._deferred_check = False + self._filters = dict(SpellChecker.DEFAULT_FILTERS) + self._regexes = {SpellChecker.FILTER_WORD : re.compile('|'.join( + self._filters[SpellChecker.FILTER_WORD])), + SpellChecker.FILTER_LINE : re.compile('|'.join( + self._filters[SpellChecker.FILTER_LINE])), + SpellChecker.FILTER_TEXT : re.compile('|'.join( + self._filters[SpellChecker.FILTER_TEXT]), + re.MULTILINE)} + self._enabled = True + self.buffer_initialize() + + @property + def language(self): + """ + The language used for spellchecking. + """ + return self._language + + @language.setter + def language(self, language): + if language != self._language and self.languages.exists(language): + self._language = language + self._dictionary = self._broker.request_dict(language) + self.recheck() + + @property + def enabled(self): + """ + Enable or disable spellchecking. + """ + return self._enabled + + @enabled.setter + def enabled(self, enabled): + if enabled and not self._enabled: + self.enable() + elif not enabled and self._enabled: + self.disable() + + def buffer_initialize(self): + """ + Initialize the GtkTextBuffer associated with the GtkTextView. If you + have associated a new GtkTextBuffer with the GtkTextView call this + method. + """ + self._buffer = self._view.get_buffer() + self._buffer.connect('insert-text', self._before_text_insert) + self._buffer.connect_after('insert-text', self._after_text_insert) + self._buffer.connect_after('delete-range', self._range_delete) + self._buffer.connect_after('mark-set', self._mark_set) + start = self._buffer.get_bounds()[0] + self._marks = {'insert-start' : SpellChecker._Mark(self._buffer, + '{}-insert-start'.format(self._prefix), start), + 'insert-end' : SpellChecker._Mark(self._buffer, + '{}-insert-end'.format(self._prefix), start), + 'click' : SpellChecker._Mark(self._buffer, + '{}-click'.format(self._prefix), start)} + self._table = self._buffer.get_tag_table() + self._table.add(self._misspelled) + self.ignored_tags = [] + def tag_added(tag, *args): + if hasattr(tag, 'spell_check') and not getattr(tag, 'spell_check'): + self.ignored_tags.append(tag) + def tag_removed(tag, *args): + if tag in self.ignored_tags: + self.ignored_tags.remove(tag) + self._table.connect('tag-added', tag_added) + self._table.connect('tag-removed', tag_removed) + self._table.foreach(tag_added, None) + self.no_spell_check = self._table.lookup('no-spell-check') + if not self.no_spell_check: + if _pygobject: + self.no_spell_check = gtk.TextTag.new('no-spell-check') + else: + self.no_spell_check = gtk.TextTag('no-spell-check') + self._table.add(self.no_spell_check) + self.recheck() + + def recheck(self): + """ + Rechecks the spelling of the whole text. + """ + start, end = self._buffer.get_bounds() + self.check_range(start, end, True) + + def disable(self): + """ + Disable spellchecking. + """ + self._enabled = False + start, end = self._buffer.get_bounds() + self._buffer.remove_tag(self._misspelled, start, end) + + def enable(self): + """ + Enable spellchecking. + """ + self._enabled = True + self.recheck() + + def append_filter(self, regex, filter_type): + """ + Append a new filter to the filter list. Filters are useful to ignore + some misspelled words based on regular expressions. + + :param regex: The regex used for filtering. + :param filter_type: The type of the filter. + + Filter Types: + + :const:`SpellChecker.FILTER_WORD`: The regex must match the whole word + you want to filter. The word separation is done by Pango's word + separation algorithm so, for example, urls won't work here because + they are split in many words. + + :const:`SpellChecker.FILTER_LINE`: If the expression you want to match + is a single line expression use this type. It should not be an open + end expression because then the rest of the line with the text you + want to filter will become correct. + + :const:`SpellChecker.FILTER_TEXT`: Use this if you want to filter + multiline expressions. The regex will be compiled with the + `re.MULTILINE` flag. Same with open end expressions apply here. + """ + self._filters[filter_type].append(regex) + if filter_type == SpellChecker.FILTER_TEXT: + self._regexes[filter_type] = re.compile('|'.join( + self._filters[filter_type]), re.MULTILINE) + else: + self._regexes[filter_type] = re.compile('|'.join( + self._filters[filter_type])) + + def remove_filter(self, regex, filter_type): + """ + Remove a filter from the filter list. + + :param regex: The regex which used for filtering. + :param filter_type: The type of the filter. + """ + self._filters[filter_type].remove(regex) + if filter_type == SpellChecker.FILTER_TEXT: + self._regexes[filter_type] = re.compile('|'.join( + self._filters[filter_type]), re.MULTILINE) + else: + self._regexes[filter_type] = re.compile('|'.join( + self._filters[filter_type])) + + def append_ignore_tag(self, tag): + """ + Appends a tag to the list of ignored tags. A string will be automatic + resolved into a tag object. + + :param tag: Tag object or tag name. + """ + if isinstance(tag, basestring): + tag = self._table.lookup(tag) + self.ignored_tags.append(tag) + + def remove_ignore_tag(self, tag): + """ + Removes a tag from the list of ignored tags. A string will be automatic + resolved into a tag object. + + :param tag: Tag object or tag name. + """ + if isinstance(tag, basestring): + tag = self._table.lookup(tag) + self.ignored_tags.remove(tag) + + def add_to_dictionary(self, word): + """ + Adds a word to user's dictionary. + + :param word: The word to add. + """ + self._dictionary.add_to_pwl(word) + self.recheck() + + def ignore_all(self, word): + """ + Ignores a word for the current session. + + :param word: The word to ignore. + """ + self._dictionary.add_to_session(word) + self.recheck() + + def check_range(self, start, end, force_all=False): + """ + Checks a specified range between two GtkTextIters. + + :param start: Start iter - checking starts here. + :param end: End iter - checking ends here. + """ + if not self._enabled: + return + if end.inside_word(): end.forward_word_end() + if not start.starts_word() and (start.inside_word() or + start.ends_word()): + start.backward_word_start() + self._buffer.remove_tag(self._misspelled, start, end) + cursor = self._buffer.get_iter_at_mark(self._buffer.get_insert()) + precursor = cursor.copy() + precursor.backward_char() + highlight = (cursor.has_tag(self._misspelled) or + precursor.has_tag(self._misspelled)) + if not start.get_offset(): + start.forward_word_end() + start.backward_word_start() + word_start = start.copy() + while word_start.compare(end) < 0: + word_end = word_start.copy() + word_end.forward_word_end() + in_word = ((word_start.compare(cursor) < 0) and + (cursor.compare(word_end) <= 0)) + if in_word and not force_all: + if highlight: + self._check_word(word_start, word_end) + else: + self._deferred_check = True + else: + self._check_word(word_start, word_end) + self._deferred_check = False + word_end.forward_word_end() + word_end.backward_word_start() + if word_start.equal(word_end): + break + word_start = word_end.copy() + + def _languages_menu(self): + def _set_language(item, code): + self.language = code + if _pygobject: + menu = gtk.Menu.new() + group = [] + else: + menu = gtk.Menu() + group = gtk.RadioMenuItem() + connect = [] + for code, name in self.languages: + if _pygobject: + item = gtk.RadioMenuItem.new_with_label(group, name) + group.append(item) + else: + item = gtk.RadioMenuItem(group, name) + if code == self.language: + item.set_active(True) + connect.append((item, code)) + menu.append(item) + for item, code in connect: + item.connect('activate', _set_language, code) + return menu + + def _suggestion_menu(self, word): + menu = [] + suggestions = self._dictionary.suggest(word) + if not suggestions: + if _pygobject: + item = gtk.MenuItem.new() + label = gtk.Label.new('') + else: + item = gtk.MenuItem() + label = gtk.Label() + try: + label.set_halign(gtk.Align.LEFT) + except AttributeError: + label.set_alignment(0.0, 0.5) + label.set_markup('{text}'.format(text=_('(no suggestions)'))) + item.add(label) + menu.append(item) + else: + for suggestion in suggestions: + if _pygobject: + item = gtk.MenuItem.new() + label = gtk.Label.new('') + else: + item = gtk.MenuItem() + label = gtk.Label() + label.set_markup('{text}'.format(text=suggestion)) + try: + label.set_halign(gtk.Align.LEFT) + except AttributeError: + label.set_alignment(0.0, 0.5) + item.add(label) + item.connect('activate', self._replace_word, word, suggestion) + menu.append(item) + if _pygobject: + menu.append(gtk.SeparatorMenuItem.new()) + item = gtk.MenuItem.new_with_label( + _('Add "{}" to Dictionary').format(word)) + else: + menu.append(gtk.SeparatorMenuItem()) + item = gtk.MenuItem(_('Add "{}" to Dictionary').format(word)) + item.connect('activate', lambda *args: self.add_to_dictionary(word)) + menu.append(item) + if _pygobject: + item = gtk.MenuItem.new_with_label(_('Ignore All')) + else: + item = gtk.MenuItem(_('Ignore All')) + item.connect('activate', lambda *args: self.ignore_all(word)) + menu.append(item) + return menu + + def _extend_menu(self, menu): + if not self._enabled: + return + if _pygobject: + separator = gtk.SeparatorMenuItem.new() + else: + separator = gtk.SeparatorMenuItem() + separator.show() + menu.prepend(separator) + if _pygobject: + languages = gtk.MenuItem.new_with_label(_('Languages')) + else: + languages = gtk.MenuItem(_('Languages')) + languages.set_submenu(self._languages_menu()) + languages.show_all() + menu.prepend(languages) + if self._marks['click'].inside_word: + start, end = self._marks['click'].word + if start.has_tag(self._misspelled): + if _py3k: + word = self._buffer.get_text(start, end, False) + else: + word = self._buffer.get_text(start, end, + False).decode('utf-8') + items = self._suggestion_menu(word) + if self.collapse: + if _pygobject: + suggestions = gtk.MenuItem.new_with_label( + _('Suggestions')) + submenu = gtk.Menu.new() + else: + suggestions = gtk.MenuItem(_('Suggestions')) + submenu = gtk.Menu() + for item in items: + submenu.append(item) + suggestions.set_submenu(submenu) + suggestions.show_all() + menu.prepend(suggestions) + else: + items.reverse() + for item in items: + menu.prepend(item) + menu.show_all() + + def _click_move_popup(self, *args): + self._marks['click'].move(self._buffer.get_iter_at_mark( + self._buffer.get_insert())) + return False + + def _click_move_button(self, widget, event): + if event.button == 3: + if self._deferred_check: self._check_deferred_range(True) + x, y = self._view.window_to_buffer_coords(2, int(event.x), + int(event.y)) + self._marks['click'].move(self._view.get_iter_at_location(x, y)) + return False + + def _before_text_insert(self, textbuffer, location, text, length): + self._marks['insert-start'].move(location) + + def _after_text_insert(self, textbuffer, location, text, length): + start = self._marks['insert-start'].iter + self.check_range(start, location) + self._marks['insert-end'].move(location) + + def _range_delete(self, textbuffer, start, end): + self.check_range(start, end) + + def _mark_set(self, textbuffer, location, mark): + if mark == self._buffer.get_insert() and self._deferred_check: + self._check_deferred_range(False) + + def _replace_word(self, item, old_word, new_word): + start, end = self._marks['click'].word + offset = start.get_offset() + self._buffer.begin_user_action() + self._buffer.delete(start, end) + self._buffer.insert(self._buffer.get_iter_at_offset(offset), new_word) + self._buffer.end_user_action() + self._dictionary.store_replacement(old_word, new_word) + + def _check_deferred_range(self, force_all): + start = self._marks['insert-start'].iter + end = self._marks['insert-end'].iter + self.check_range(start, end, force_all) + + def _check_word(self, start, end): + if start.has_tag(self.no_spell_check): + return + for tag in self.ignored_tags: + if start.has_tag(tag): + return + if _py3k: + word = self._buffer.get_text(start, end, False).strip() + else: + word = self._buffer.get_text(start, end, False).decode('utf-8').strip() + if len(self._filters[SpellChecker.FILTER_WORD]): + if self._regexes[SpellChecker.FILTER_WORD].match(word): + return + if len(self._filters[SpellChecker.FILTER_LINE]): + line_start = self._buffer.get_iter_at_line(start.get_line()) + line_end = end.copy() + line_end.forward_to_line_end() + if _py3k: + line = self._buffer.get_text(line_start, line_end, False) + else: + line = self._buffer.get_text(line_start, line_end, + False).decode('utf-8') + for match in self._regexes[SpellChecker.FILTER_LINE].finditer(line): + if match.start() <= start.get_line_offset() <= match.end(): + start = self._buffer.get_iter_at_line_offset( + start.get_line(), match.start()) + end = self._buffer.get_iter_at_line_offset(start.get_line(), + match.end()) + self._buffer.remove_tag(self._misspelled, start, end) + return + if len(self._filters[SpellChecker.FILTER_TEXT]): + text_start, text_end = self._buffer.get_bounds() + if _py3k: + text = self._buffer.get_text(text_start, text_end, False) + else: + text = self._buffer.get_text(text_start, text_end, + False).decode('utf-8') + for match in self._regexes[SpellChecker.FILTER_TEXT].finditer(text): + if match.start() <= start.get_offset() <= match.end(): + start = self._buffer.get_iter_at_offset(match.start()) + end = self._buffer.get_iter_at_offset(match.end()) + self._buffer.remove_tag(self._misspelled, start, end) + return + if not self._dictionary.check(word): + self._buffer.apply_tag(self._misspelled, start, end) \ No newline at end of file diff --git a/build/lib/uberwriter_lib/helpers.py b/build/lib/uberwriter_lib/helpers.py new file mode 100644 index 0000000..a7562fd --- /dev/null +++ b/build/lib/uberwriter_lib/helpers.py @@ -0,0 +1,117 @@ +# -*- Mode: Python; coding: utf-8; indent-tabs-mode: nil; tab-width: 4 -*- +### BEGIN LICENSE +# Copyright (C) 2012, Wolf Vollprecht +# This program is free software: you can redistribute it and/or modify it +# under the terms of the GNU General Public License version 3, as published +# by the Free Software Foundation. +# +# This program is distributed in the hope that it will be useful, but +# WITHOUT ANY WARRANTY; without even the implied warranties of +# MERCHANTABILITY, SATISFACTORY QUALITY, or FITNESS FOR A PARTICULAR +# PURPOSE. See the GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License along +# with this program. If not, see . +### END LICENSE + +### DO NOT EDIT THIS FILE ### + +"""Helpers for an Ubuntu application.""" +import logging +import os + +from . uberwriterconfig import get_data_file +from . Builder import Builder + +from locale import gettext as _ + +def get_builder(builder_file_name): + """Return a fully-instantiated Gtk.Builder instance from specified ui + file + + :param builder_file_name: The name of the builder file, without extension. + Assumed to be in the 'ui' directory under the data path. + """ + # Look for the ui file that describes the user interface. + ui_filename = get_data_file('ui', '%s.ui' % (builder_file_name,)) + if not os.path.exists(ui_filename): + ui_filename = None + + builder = Builder() + builder.set_translation_domain('uberwriter') + builder.add_from_file(ui_filename) + return builder + + +# Owais Lone : To get quick access to icons and stuff. +def get_media_file(media_file_name): + media_filename = get_data_file('media', '%s' % (media_file_name,)) + if not os.path.exists(media_filename): + media_filename = None + + return "file:///"+media_filename + +def get_media_path(media_file_name): + media_filename = get_data_file('media', '%s' % (media_file_name,)) + if not os.path.exists(media_filename): + media_filename = None + return "/"+media_filename + +class NullHandler(logging.Handler): + def emit(self, record): + pass + +def set_up_logging(opts): + # add a handler to prevent basicConfig + root = logging.getLogger() + null_handler = NullHandler() + root.addHandler(null_handler) + + formatter = logging.Formatter("%(levelname)s:%(name)s: %(funcName)s() '%(message)s'") + + logger = logging.getLogger('uberwriter') + logger_sh = logging.StreamHandler() + logger_sh.setFormatter(formatter) + logger.addHandler(logger_sh) + + lib_logger = logging.getLogger('uberwriter_lib') + lib_logger_sh = logging.StreamHandler() + lib_logger_sh.setFormatter(formatter) + lib_logger.addHandler(lib_logger_sh) + + # Set the logging level to show debug messages. + if opts.verbose: + logger.setLevel(logging.DEBUG) + logger.debug('logging enabled') + if opts.verbose and opts.verbose > 1: + lib_logger.setLevel(logging.DEBUG) + +def get_help_uri(page=None): + # help_uri from source tree - default language + here = os.path.dirname(__file__) + help_uri = os.path.abspath(os.path.join(here, '..', 'help', 'C')) + + if not os.path.exists(help_uri): + # installed so use gnome help tree - user's language + help_uri = 'uberwriter' + + # unspecified page is the index.page + if page is not None: + help_uri = '%s#%s' % (help_uri, page) + + return help_uri + +def show_uri(parent, link): + from gi.repository import Gtk # pylint: disable=E0611 + screen = parent.get_screen() + Gtk.show_uri(screen, link, Gtk.get_current_event_time()) + +def alias(alternative_function_name): + '''see http://www.drdobbs.com/web-development/184406073#l9''' + def decorator(function): + '''attach alternative_function_name(s) to function''' + if not hasattr(function, 'aliases'): + function.aliases = [] + function.aliases.append(alternative_function_name) + return function + return decorator diff --git a/build/lib/uberwriter_lib/pylocales/__init__.py b/build/lib/uberwriter_lib/pylocales/__init__.py new file mode 100644 index 0000000..b89b0cc --- /dev/null +++ b/build/lib/uberwriter_lib/pylocales/__init__.py @@ -0,0 +1,55 @@ +# -*- coding:utf-8 -*- +# +# Copyright (C) 2012, Maximilian Köhl +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program. If not, see . + +# Python 2/3 unicode +import sys +if sys.version_info.major == 3: + u = lambda x: x +else: + u = lambda x: x.decode('utf-8') + +# Metadata +__version__ = '1.1' +__project__ = 'PyLocales' +__short_name__ = 'pylocales' +__authors__ = u('Maximilian Köhl & Carlos Jenkins') +__emails__ = u('linuxmaxi@googlemail.com & carlos@jenkins.co.cr') +__website__ = 'http://pygtkspellcheck.readthedocs.org/' +__source__ = 'https://github.com/koehlma/pygtkspellcheck/' +__vcs__ = 'git://github.com/koehlma/pygtkspellcheck.git' +__copyright__ = u('2012, Maximilian Köhl & Carlos Jenkins') +__desc_short__ = 'Query the ISO 639/3166 database about a country or a language.' +__desc_long__ = ('Query the ISO 639/3166 database about a country or a' + 'language. The locales database contains ISO 639 languages' + 'definitions and ISO 3166 countries definitions. This package' + 'provides translation for countries and languages names if' + 'iso-codes package is installed (Ubuntu/Debian).') + +__metadata__ = {'__version__' : __version__, + '__project__' : __project__, + '__short_name__' : __short_name__, + '__authors__' : __authors__, + '__emails__' : __emails__, + '__website__' : __website__, + '__source__' : __source__, + '__vcs__' : __vcs__, + '__copyright__' : __copyright__, + '__desc_short__' : __desc_short__, + '__desc_long__' : __desc_long__} + +# Should only import Public Objects +from .locales import * diff --git a/build/lib/uberwriter_lib/pylocales/locales.py b/build/lib/uberwriter_lib/pylocales/locales.py new file mode 100644 index 0000000..a912ef8 --- /dev/null +++ b/build/lib/uberwriter_lib/pylocales/locales.py @@ -0,0 +1,138 @@ +# -*- coding:utf-8 -*- +# +# Copyright (C) 2012, Maximilian Köhl +# Copyright (C) 2012, Carlos Jenkins +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program. If not, see . + +""" +Query the ISO 639/3166 database about a country or a language. The locales +database contains ISO 639 languages definitions and ISO 3166 countries +definitions. This package provides translation for countries and languages names +if iso-codes package is installed (Ubuntu/Debian). + +@see utils/locales/build.py to know the database tables and structure. +""" + +import gettext +import logging +import os +import sqlite3 + +# Public Objects +__all__ = ['Country', 'Language', 'LanguageNotFound', + 'CountryNotFound', 'code_to_name'] + +# Translation +_translator_language = gettext.translation('iso_639', fallback=True).gettext +_translator_country = gettext.translation('iso_3166', fallback=True).gettext + +# Decides where the database is located. If an application provides an +# os.path.get_module_path monkey patch to determine the path where the module +# is located it uses this. If not it searches in the directory of this source +# code file. +__path__ = None +if hasattr(os.path, 'get_module_path'): + __path__ = os.path.get_module_path(__file__) + if not os.path.isfile(os.path.join(__path__, 'locales.db')): + __path__ = None +if __path__ is None: + __path__ = os.path.abspath(os.path.realpath(os.path.dirname(__file__))) + +# Loading the Database +_database = sqlite3.connect(os.path.join(__path__, 'locales.db')) + +logger = logging.getLogger(__name__) + +# Exceptions +class LanguageNotFound(Exception): + """ + The specified language wasn't found in the database. + """ + +class CountryNotFound(Exception): + """ + The specified country wasn't found in the database. + """ + +class Country(object): + def __init__(self, rowid): + country = _database.execute('SELECT * FROM countries WHERE rowid == ?', (rowid,)).fetchone() + self.name = country[0] + self.official_name = country[1] + self.alpha_2 = country[2] + self.alpha_3 = country[3] + self.numeric = country[4] + self.translation = _translator_country(self.name) + + @classmethod + def get_country(cls, code, codec): + country = _database.execute('SELECT rowid FROM countries WHERE %s == ?' % (codec), (code,)).fetchone() + if country: + return cls(country[0]) + raise CountryNotFound('code: %s, codec: %s' % (code, codec)) + + @classmethod + def by_alpha_2(cls, code): + return Country.get_country(code, 'alpha_2') + + @classmethod + def by_alpha_3(cls, code): + return Country.get_country(code, 'alpha_3') + + @classmethod + def by_numeric(cls, code): + return Country.get_country(code, 'numeric') + +class Language(object): + def __init__(self, rowid): + language = _database.execute('SELECT * FROM languages WHERE rowid == ?', (rowid,)).fetchone() + self.name = language[0] + self.iso_639_2B = language[1] + self.iso_639_2T = language[2] + self.iso_639_1 = language[3] + self.translation = _translator_language(self.name) + + @classmethod + def get_language(cls, code, codec): + language = _database.execute('SELECT rowid FROM languages WHERE %s == ?' % (codec), (code,)).fetchone() + if language: + return cls(language[0]) + raise LanguageNotFound('code: %s, codec: %s' % (code, codec)) + + @classmethod + def by_iso_639_2B(cls, code): + return Language.get_language(code, 'iso_639_2B') + + @classmethod + def by_iso_639_2T(cls, code): + return Language.get_language(code, 'iso_639_2T') + + @classmethod + def by_iso_639_1(cls, code): + return Language.get_language(code, 'iso_639_1') + + +def code_to_name(code, separator='_'): + """ + Get the natural name of a language based on it's code. + """ + logger.debug('requesting name for code "{}"'.format(code)) + code = code.split(separator) + if len(code) > 1: + lang = Language.by_iso_639_1(code[0]).translation + country = Country.by_alpha_2(code[1]).translation + return '{lang} ({country})'.format(lang=lang, country=country) + else: + return Language.by_iso_639_1(code[0]).translation \ No newline at end of file diff --git a/build/lib/uberwriter_lib/tables.py b/build/lib/uberwriter_lib/tables.py new file mode 100644 index 0000000..c67fb32 --- /dev/null +++ b/build/lib/uberwriter_lib/tables.py @@ -0,0 +1,209 @@ +# -*- encoding: utf-8 -*- +import re +import vim + + +def cjk_width(text): + import sys + if sys.version_info[0] < 3: + if not isinstance(text, unicode): + text = text.decode("utf-8") + from unicodedata import east_asian_width + return sum(1+(east_asian_width(c) in "WF") for c in text) + + +def create_separarator(widths, char): + """Genera una linea para separar filas de una tabla. + + El parametro `widths` es un lista indicando el ancho de cada + columna. En cambio el argumento `char` es el caracter que se + tiene que utilizar para imprimir. + + El valor retornado es un string. + + Por ejemplo:: + + >>> create_separarator([2, 4], '-') + '+----+------+' + """ + + line = [] + + for w in widths: + line.append("+" + char * (w + 2)) + + line.append("+") + return ''.join(line) + + +def create_line(columns, widths): + """Crea una fila de la tabla separando los campos con un '|'. + + El argumento `columns` es una lista con las celdas que se + quieren imprimir y el argumento `widths` tiene el ancho + de cada columna. Si la columna es mas ancha que el texto + a imprimir se agregan espacios vacíos. + + Por ejemplo:: + + >>> create_line(['nombre', 'apellido'], [7, 10]) + '| nombre | apellido |' + """ + + line = zip(columns, widths) + result = [] + + for text, width in line: + spaces = " " * (width - cjk_width(text)) + text = "| " + text + spaces + " " + result.append(text) + + result.append("|") + return ''.join(result) + + +def create_table(content): + """Imprime una tabla en formato restructuredText. + + El argumento `content` tiene que ser una lista + de celdas. + + Por ejemplo:: + + >>> print create_table([['software', 'vesion'], ['python', '3.2'], ['vim', '7.3']]) + +----------+--------+ + | software | vesion | + +==========+========+ + | python | 3.2 | + +----------+--------+ + | vim | 7.3 | + +----------+--------+ + """ + + # obtiene las columnas de toda la tabla. + columns = zip(*content) + # calcula el tamano maximo que debe tener cada columna. + widths = [max([cjk_width(x) for x in i]) for i in columns] + + result = [] + + result.append(create_separarator(widths, '-')) + result.append(create_line(content[0], widths)) + result.append(create_separarator(widths, '=')) + + for line in content[1:]: + result.append(create_line(line, widths)) + result.append(create_separarator(widths, '-')) + + return '\n'.join(result) + + +def are_in_a_table(current_line): + "Indica si el cursor se encuentra dentro de una tabla." + return "|" in current_line or "+" in current_line + + +def are_in_a_paragraph(current_line): + "Indica si la linea actual es parte de algun parrafo" + return len(current_line.strip()) >= 1 + + +def get_table_bounds(current_row_index, are_in_callback): + """Obtiene el numero de fila donde comienza y termina la tabla. + + el argumento `are_in_callback` tiene que ser una función + que indique si una determinada linea pertenece o no + a la tabla que se quiere medir (o crear). + + Retorna ambos valores como una tupla. + """ + + top = 0 + buffer = vim.current.buffer + max = len(buffer) + bottom = max - 1 + + for a in range(current_row_index, top, -1): + if not are_in_callback(buffer[a]): + top = a + 1 + break + + for b in range(current_row_index, max): + if not are_in_callback(buffer[b]): + bottom = b - 1 + break + + return top, bottom + + +def remove_spaces(string): + "Elimina los espacios innecesarios de una fila de tabla." + return re.sub("\s\s+", " ", string) + + +def create_separators_removing_spaces(string): + return re.sub("\s\s+", "|", string) + + +def extract_cells_as_list(string): + "Extrae el texto de una fila de tabla y lo retorna como una lista." + string = remove_spaces(string) + return [item.strip() for item in string.split('|') if item] + + +def extract_table(buffer, top, bottom): + full_table_text = buffer[top:bottom] + # selecciona solamente las lineas que tienen celdas con texto. + only_text_lines = [x for x in full_table_text if '|' in x] + # extrae las celdas y descarta los separadores innecesarios. + return [extract_cells_as_list(x) for x in only_text_lines] + + +def extract_words_as_lists(buffer, top, bottom): + "Genera una lista de palabras para crear una lista." + + lines = buffer[top:bottom + 1] + return [create_separators_removing_spaces(line).split('|') for line in lines] + + +def copy_to_buffer(buffer, string, index): + lines = string.split('\n') + for line in lines: + buffer[index] = line + index += 1 + + +def fix_table(current_row_index): + """Arregla una tabla para que todas las columnas tengan el mismo ancho. + + `initial_row` es un numero entero que indica en que + linea se encuenta el cursor.""" + + # obtiene el indice donde comienza y termina la tabla. + r1, r2 = get_table_bounds(current_row_index, are_in_a_table) + + # extrae de la tabla solo las celdas de texto + table_as_list = extract_table(vim.current.buffer, r1, r2) + + # genera una nueva tabla tipo restructured text y la dibuja en el buffer. + table_content = create_table(table_as_list) + copy_to_buffer(vim.current.buffer, table_content, r1) + + +def FixTable(): + (row, col) = vim.current.window.cursor + line = vim.current.buffer[row - 1] + + if are_in_a_table(line): + fix_table(row - 1) + else: + print("No estoy en una tabla. Terminando...") + + +def CreateTable(): + (row, col) = vim.current.window.cursor + + top, bottom = get_table_bounds(row - 1, are_in_a_paragraph) + lines = extract_words_as_lists(vim.current.buffer, top, bottom) + table_content = create_table(lines) + vim.current.buffer[top:bottom + 1] = table_content.split('\n') diff --git a/build/lib/uberwriter_lib/uberwriterconfig.py b/build/lib/uberwriter_lib/uberwriterconfig.py new file mode 100644 index 0000000..1ed2e44 --- /dev/null +++ b/build/lib/uberwriter_lib/uberwriterconfig.py @@ -0,0 +1,69 @@ +# -*- Mode: Python; coding: utf-8; indent-tabs-mode: nil; tab-width: 4 -*- +### BEGIN LICENSE +# Copyright (C) 2012, Wolf Vollprecht +# This program is free software: you can redistribute it and/or modify it +# under the terms of the GNU General Public License version 3, as published +# by the Free Software Foundation. +# +# This program is distributed in the hope that it will be useful, but +# WITHOUT ANY WARRANTY; without even the implied warranties of +# MERCHANTABILITY, SATISFACTORY QUALITY, or FITNESS FOR A PARTICULAR +# PURPOSE. See the GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License along +# with this program. If not, see . +### END LICENSE + +### DO NOT EDIT THIS FILE ### + +__all__ = [ + 'project_path_not_found', + 'get_data_file', + 'get_data_path', + ] + +# Where your project will look for your data (for instance, images and ui +# files). By default, this is ../data, relative your trunk layout +__uberwriter_data_directory__ = '../data/' +__license__ = 'GPL-3' +__version__ = 'VERSION' + +import os + +from locale import gettext as _ + +class project_path_not_found(Exception): + """Raised when we can't find the project directory.""" + + +def get_data_file(*path_segments): + """Get the full path to a data file. + + Returns the path to a file underneath the data directory (as defined by + `get_data_path`). Equivalent to os.path.join(get_data_path(), + *path_segments). + """ + return os.path.join(get_data_path(), *path_segments) + + +def get_data_path(): + """Retrieve uberwriter data path + + This path is by default /../data/ in trunk + and /usr/share/uberwriter in an installed version but this path + is specified at installation time. + """ + + # Get pathname absolute or relative. + path = os.path.join( + os.path.dirname(__file__), __uberwriter_data_directory__) + + abs_data_path = os.path.abspath(path) + if not os.path.exists(abs_data_path): + raise project_path_not_found + + return abs_data_path + + +def get_version(): + return __version__ diff --git a/build/mo/uberwriter-de/LC_MESSAGES/uberwriter.mo b/build/mo/uberwriter-de/LC_MESSAGES/uberwriter.mo new file mode 100644 index 0000000..232e845 Binary files /dev/null and b/build/mo/uberwriter-de/LC_MESSAGES/uberwriter.mo differ diff --git a/build/mo/uberwriter-en_GB/LC_MESSAGES/uberwriter.mo b/build/mo/uberwriter-en_GB/LC_MESSAGES/uberwriter.mo new file mode 100644 index 0000000..475094f Binary files /dev/null and b/build/mo/uberwriter-en_GB/LC_MESSAGES/uberwriter.mo differ diff --git a/build/mo/uberwriter-es/LC_MESSAGES/uberwriter.mo b/build/mo/uberwriter-es/LC_MESSAGES/uberwriter.mo new file mode 100644 index 0000000..dcf6455 Binary files /dev/null and b/build/mo/uberwriter-es/LC_MESSAGES/uberwriter.mo differ diff --git a/build/mo/uberwriter-eu/LC_MESSAGES/uberwriter.mo b/build/mo/uberwriter-eu/LC_MESSAGES/uberwriter.mo new file mode 100644 index 0000000..b06130c Binary files /dev/null and b/build/mo/uberwriter-eu/LC_MESSAGES/uberwriter.mo differ diff --git a/build/mo/uberwriter-pt_BR/LC_MESSAGES/uberwriter.mo b/build/mo/uberwriter-pt_BR/LC_MESSAGES/uberwriter.mo new file mode 100644 index 0000000..f8d49b7 Binary files /dev/null and b/build/mo/uberwriter-pt_BR/LC_MESSAGES/uberwriter.mo differ diff --git a/build/mo/uberwriter-ru/LC_MESSAGES/uberwriter.mo b/build/mo/uberwriter-ru/LC_MESSAGES/uberwriter.mo new file mode 100644 index 0000000..8bcda60 Binary files /dev/null and b/build/mo/uberwriter-ru/LC_MESSAGES/uberwriter.mo differ diff --git a/build/mo/uberwriter-zh_CN/LC_MESSAGES/uberwriter.mo b/build/mo/uberwriter-zh_CN/LC_MESSAGES/uberwriter.mo new file mode 100644 index 0000000..989fcd4 Binary files /dev/null and b/build/mo/uberwriter-zh_CN/LC_MESSAGES/uberwriter.mo differ diff --git a/build/scripts-3.2/uberwriter b/build/scripts-3.2/uberwriter new file mode 100755 index 0000000..949f723 --- /dev/null +++ b/build/scripts-3.2/uberwriter @@ -0,0 +1,47 @@ +#!/usr/bin/python3 +# -*- Mode: Python; coding: utf-8; indent-tabs-mode: nil; tab-width: 4 -*- +### BEGIN LICENSE +# Copyright (C) 2012, Wolf Vollprecht +# This program is free software: you can redistribute it and/or modify it +# under the terms of the GNU General Public License version 3, as published +# by the Free Software Foundation. +# +# This program is distributed in the hope that it will be useful, but +# WITHOUT ANY WARRANTY; without even the implied warranties of +# MERCHANTABILITY, SATISFACTORY QUALITY, or FITNESS FOR A PARTICULAR +# PURPOSE. See the GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License along +# with this program. If not, see . +### END LICENSE + +### DO NOT EDIT THIS FILE ### + +import sys +import os + +import locale +locale.textdomain('uberwriter') + +# Add project root directory (enable symlink and trunk execution) +PROJECT_ROOT_DIRECTORY = os.path.abspath( + os.path.dirname(os.path.dirname(os.path.realpath(sys.argv[0])))) + +python_path = [] +if os.path.abspath(__file__).startswith('/opt'): + locale.bindtextdomain('uberwriter', '/opt/extras.ubuntu.com/uberwriter/share/locale') + syspath = sys.path[:] # copy to avoid infinite loop in pending objects + for path in syspath: + opt_path = path.replace('/usr', '/opt/extras.ubuntu.com/uberwriter') + python_path.insert(0, opt_path) + sys.path.insert(0, opt_path) + os.putenv("XDG_DATA_DIRS", "%s:%s" % ("/opt/extras.ubuntu.com/uberwriter/share/", os.getenv("XDG_DATA_DIRS", "/usr/local/share/:/usr/share/"))) +if (os.path.exists(os.path.join(PROJECT_ROOT_DIRECTORY, 'uberwriter')) + and PROJECT_ROOT_DIRECTORY not in sys.path): + python_path.insert(0, PROJECT_ROOT_DIRECTORY) + sys.path.insert(0, PROJECT_ROOT_DIRECTORY) +if python_path: + os.putenv('PYTHONPATH', "%s:%s" % (os.getenv('PYTHONPATH', ''), ':'.join(python_path))) # for subprocesses + +import uberwriter +uberwriter.main() diff --git a/data/glib-2.0/schemas/gschemas.compiled b/data/glib-2.0/schemas/gschemas.compiled new file mode 100644 index 0000000..30e71a8 Binary files /dev/null and b/data/glib-2.0/schemas/gschemas.compiled differ diff --git a/data/glib-2.0/schemas/net.launchpad.uberwriter.gschema.xml b/data/glib-2.0/schemas/net.launchpad.uberwriter.gschema.xml new file mode 100644 index 0000000..e24efce --- /dev/null +++ b/data/glib-2.0/schemas/net.launchpad.uberwriter.gschema.xml @@ -0,0 +1,10 @@ + + + + + '' + Sample setting + Longer description of this sample setting. Talk about allowed values and what it does. + + + diff --git a/data/media/bg_dark.png b/data/media/bg_dark.png new file mode 100644 index 0000000..2570b6b Binary files /dev/null and b/data/media/bg_dark.png differ diff --git a/data/media/bg_light.png b/data/media/bg_light.png new file mode 100644 index 0000000..83b113d Binary files /dev/null and b/data/media/bg_light.png differ diff --git a/data/media/bg_light_old.png b/data/media/bg_light_old.png new file mode 100644 index 0000000..50024de Binary files /dev/null and b/data/media/bg_light_old.png differ diff --git a/data/media/icon-case-off.png b/data/media/icon-case-off.png new file mode 100644 index 0000000..281ae05 Binary files /dev/null and b/data/media/icon-case-off.png differ diff --git a/data/media/icon-regex-off.png b/data/media/icon-regex-off.png new file mode 100644 index 0000000..61ff932 Binary files /dev/null and b/data/media/icon-regex-off.png differ diff --git a/data/media/icon-reverse-off.png b/data/media/icon-reverse-off.png new file mode 100644 index 0000000..d6ec595 Binary files /dev/null and b/data/media/icon-reverse-off.png differ diff --git a/data/media/icon-word-off.png b/data/media/icon-word-off.png new file mode 100644 index 0000000..b0af0ca Binary files /dev/null and b/data/media/icon-word-off.png differ diff --git a/data/media/icon-wrap-off.png b/data/media/icon-wrap-off.png new file mode 100644 index 0000000..f9de6d3 Binary files /dev/null and b/data/media/icon-wrap-off.png differ diff --git a/data/media/icons/icon-case-off.png b/data/media/icons/icon-case-off.png new file mode 100644 index 0000000..281ae05 Binary files /dev/null and b/data/media/icons/icon-case-off.png differ diff --git a/data/media/icons/icon-regex-off.png b/data/media/icons/icon-regex-off.png new file mode 100644 index 0000000..61ff932 Binary files /dev/null and b/data/media/icons/icon-regex-off.png differ diff --git a/data/media/icons/icon-reverse-off.png b/data/media/icons/icon-reverse-off.png new file mode 100644 index 0000000..d6ec595 Binary files /dev/null and b/data/media/icons/icon-reverse-off.png differ diff --git a/data/media/icons/icon-word-off.png b/data/media/icons/icon-word-off.png new file mode 100644 index 0000000..b0af0ca Binary files /dev/null and b/data/media/icons/icon-word-off.png differ diff --git a/data/media/icons/icon-wrap-off.png b/data/media/icons/icon-wrap-off.png new file mode 100644 index 0000000..f9de6d3 Binary files /dev/null and b/data/media/icons/icon-wrap-off.png differ diff --git a/data/media/markdown-mark.svg b/data/media/markdown-mark.svg new file mode 100644 index 0000000..a907979 --- /dev/null +++ b/data/media/markdown-mark.svg @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/data/media/raw/raw_icons.svg b/data/media/raw/raw_icons.svg new file mode 100644 index 0000000..e80acdf --- /dev/null +++ b/data/media/raw/raw_icons.svg @@ -0,0 +1,241 @@ + + + + + + + + + + image/svg+xml + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/data/media/scrollToMark.htmlsnippet b/data/media/scrollToMark.htmlsnippet new file mode 100644 index 0000000..4244414 --- /dev/null +++ b/data/media/scrollToMark.htmlsnippet @@ -0,0 +1,3 @@ + \ No newline at end of file diff --git a/data/media/style.css b/data/media/style.css new file mode 100644 index 0000000..6676ba0 --- /dev/null +++ b/data/media/style.css @@ -0,0 +1,143 @@ +/* + TODO: + Look into compiling resources with glib-compile-resource etc. for + inclusion in templates +*/ + +#UberwriterWindow { + background: #FFF; +} +#UberwriterWindow GtkTextView { + border: none; + -GtkWidget-cursor-color: shade(@selected_bg_color, 0.9); + -GtkWidget-cursor-aspect-ratio: 0.05; + background: transparent ; + color: #222; +} + +#UberwriterWindow GtkTextView GtkButton { + margin: 0; + padding: 0; + background: #CCC; +} + +#UberwriterWindow GtkScrolledWindow { + background: white; +} + +#UberwriterWindow GtkToolbar { + background: transparent; + border: none; + padding: 0; +} + +#UberwriterWindow GtkTextView:selected { + background-color: @selected_bg_color; + color: @selected_fg_color; +} + +#UberwriterWindow GtkPaned, #UberwriterWindow GtkScrolledWindow, +#UberwriterWindow GtkScrolledWindow:backdrop { + background-color: white; + background-clip: initial; + background-origin: initial; + background-size: initial; + background-position: initial; + background-repeat: initial; + background-image: initial; +} + +#status_bar_box GtkLabel { + color: #666; + transition: 500ms ease-in-out; +} + +#status_bar_box GtkButton { + /* finding reset */ + background-color: initial; + text-shadow: inherit; + icon-shadow: inherit; + box-shadow: initial; + background-clip: initial; + background-origin: initial; + background-size: initial; + background-position: initial; + background-repeat: initial; + background-image: initial; + border-image-source: initial; + border-image-repeat: initial; + border-image-slice: initial; + border-image-width: initial; + + border-style: none; + -GtkButton-images: true; + border-radius: 2px; + color: #666; + padding: 3px 5px; + + -GtkButton-child-displacement-y: 0px; + -GtkButton-child-displacement-x: 0px; + -GtkButton-default-border: 0; + -GtkButton-image-spacing: 5px; + -GtkButton-interior-focus: false; + -GtkButton-inner-border: 0; + + transition: 500ms ease-in; + +} + +#status_bar_box GtkButton:hover, +#status_bar_box GtkButton:active:hover { + + transition: 0s ease-in; + color: #333; + background: #EEE; +} + + +#status_bar_box GtkButton:active { + color: #EEE; + background-color: #EEE; + background-image: none; + box-shadow: 0 0 2px rgba(0,0,0,0.4) +} + +#status_bar_box GtkLabel:insensitive { + color: rgba(255,255,255,0); + transition: 500ms ease-in-out; +} + +#status_bar_box GtkButton:insensitive { + background: rgba(255,255,255,0); + transition: 500ms ease-in-out; + box-shadow: 0 0 0 #FFF; +} +#status_bar_box GtkSeparator { + border-color: #999; + border-right: none; + transition: 500ms ease-in-out; + +} +#status_bar_box GtkSeparator:insensitive { + background: rgba(255,255,255,0); + border-color: rgba(255,255,255,0); + transition: 500ms ease-in-out; +} + +#PreviewMenuItem GtkImage { + border-radius: 2px; + color: #666; + padding: 3px 5px; + border: none; + background: #FFF; +} + + +#UberwriterWindow GtkTreeView { + color: #333; + font-size: 10; +} + +#UberwriterWindow GtkBox { + background: #FFF; +} \ No newline at end of file diff --git a/data/media/style_dark.css b/data/media/style_dark.css new file mode 100644 index 0000000..79fbf53 --- /dev/null +++ b/data/media/style_dark.css @@ -0,0 +1,183 @@ +/*@import url('reset.css');*/ +/* @import this colorsheet to get the default values for every property. + * This is useful when writing special CSS tests that should not be + * inluenced by themes - not even the default ones. + * Keep in mind that the output will be very ugly and not look like + * anything GTK. + * Also, when adding new style properties, please add them here. + */ + +/** { + color: inherit; + font-size: inherit; + background-color: initial; + font-family: inherit; + font-style: inherit; + font-variant: inherit; + font-weight: inherit; + text-shadow: inherit; + icon-shadow: inherit; + box-shadow: initial; + margin-top: initial; + margin-left: initial; + margin-bottom: initial; + margin-right: initial; + padding-top: initial; + padding-left: initial; + padding-bottom: initial; + padding-right: initial; + border-top-style: initial; + border-top-width: initial; + border-left-style: initial; + border-left-width: initial; + border-bottom-style: initial; + border-bottom-width: initial; + border-right-style: initial; + border-right-width: initial; + border-top-left-radius: initial; + border-top-right-radius: initial; + border-bottom-right-radius: initial; + border-bottom-left-radius: initial; + outline-style: initial; + outline-width: initial; + outline-offset: initial; + background-clip: initial; + background-origin: initial; + background-size: initial; + background-position: initial; + border-top-color: initial; + border-right-color: initial; + border-bottom-color: initial; + border-left-color: initial; + outline-color: initial; + background-repeat: initial; + background-image: initial; + border-image-source: initial; + border-image-repeat: initial; + border-image-slice: initial; + border-image-width: initial; + transition-property: initial; + transition-duration: initial; + transition-timing-function: initial; + transition-delay: initial; + gtk-key-bindings: initial; + + -GtkWidget-focus-line-width: 0; + -GtkWidget-focus-padding: 0; + -GtkNotebook-initial-gap: 0; +} +*/ + +#UberwriterWindow { + background: #FFF; + color: #CCC; +} +#UberwriterWindow GtkTextView { + + border: none; + -GtkWidget-cursor-color: shade(@selected_bg_color, 1.2); + -GtkWidget-cursor-aspect-ratio: 0.05; + background: transparent ; + color: #DDD; + /*font: Rough_Typewriter 15;*/ + /*font: Georgia 15;*/ +} + +#UberwriterWindow GtkScrolledWindow { + background: transparent; +} + +#UberwriterWindow GtkTextView:selected { + background-color: @selected_bg_color; + color: @selected_fg_color; +} + +#UberwriterWindow GtkPaned { + background-color: transparent; + background-clip: initial; + background-origin: initial; + background-size: initial; + background-position: initial; + background-repeat: initial; + background-image: initial; +} + +#status_bar_box GtkLabel{ + color: #666; + transition: 500ms ease-in-out; + text-shadow: none; +} + +#status_bar_box GtkButton { + /* finding reset */ + background-color: initial; + text-shadow: inherit; + icon-shadow: inherit; + box-shadow: initial; + background-clip: initial; + background-origin: initial; + background-size: initial; + background-position: initial; + background-repeat: initial; + background-image: initial; + border-image-source: initial; + border-image-repeat: initial; + border-image-slice: initial; + border-image-width: initial; + + border-style: none; + -GtkButton-images: true; + border-radius: 2px; + color: #666; + padding: 3px 5px; + + -GtkButton-child-displacement-y: 0px; + -GtkButton-child-displacement-x: 0; + -GtkButton-default-border: 0; + -GtkButton-image-spacing: 5px; + -GtkButton-interior-focus: false; + -GtkButton-inner-border: 0; + + transition: 500ms ease-in; + +} + +#status_bar_box GtkButton:hover, +#status_bar_box GtkButton:active:hover { + + transition: 0s ease-in; + color: #666; + background: #222; +} + + +#status_bar_box GtkButton:active { + color: #666; + box-shadow: inset 0 0 5px #333; + background-color: #222; + background-image: none; + box-shadow: 0 0 2px rgba(0,0,0,0.4) +} + +#status_bar_box GtkLabel:insensitive { + color: rgba(0,0,0,0); + transition: 500ms ease-in-out; +} + +#status_bar_box GtkButton:insensitive { + background: rgba(0,0,0,0); + transition: 500ms all ease-in-out; + box-shadow: 0 0 0 #000; +} + +#status_bar_box GtkSeparator { + border-color: #666; + border-right: none; + transition: 500ms ease-in-out; + +} +#status_bar_box GtkSeparator:insensitive { + background: rgba(0,0,0,0); + border-color: rgba(0,0,0,0); + transition: 500ms ease-in-out; +} \ No newline at end of file diff --git a/data/media/style_dark_old.css b/data/media/style_dark_old.css new file mode 100644 index 0000000..54dd0c8 --- /dev/null +++ b/data/media/style_dark_old.css @@ -0,0 +1,96 @@ +#UberwriterWindow { + background: #333; +} +#UberwriterWindow GtkTextView { + border: none; + -GtkWidget-cursor-color: #FA5B0F; + -GtkWidget-cursor-aspect-ratio: 0.05; + background-color: transparent; + color: #F3F3F3; +} +#UberwriterWindow GtkTextView:selected { + background-color: #888; + color: #DDD; +} +#fullscreen_toggle:hover, +#fullscreen_toggle:active:hover, +#focus_toggle:hover, +#focus_toggle:active:hover { + color: #999; + background-color: #222; + background-image: none; + text-shadow: none; + -unico-border-gradient: none; + -unico-glow-radius: 0; + -unico-glow-color: #000; + -unico-outer-stroke-color: #000; + -unico-outer-stroke-gradient: none; + -unico-outer-stroke-width: 0; + -unico-inner-stroke-gradient: none; + -unico-inner-stroke-width: 1px; + -unico-border-gradient: none; + -unico-focus-outer-stroke-color: #000; + -unico-outer-stroke-width: 0 0 0 0; + -GtkButton-default-border: 0; + -GtkButton-image-spacing: 0; + -GtkButton-interior-focus: false; + -unico-focus-border-color: #000; + -unico-focus-outer-stroke-color: #000; + -unico-inner-stroke-color: #000; + -unico-inner-stroke-width: 0; + +} +#fullscreen_toggle, +#focus_toggle { + border-style: none; + -unico-border-gradient: none; + -GtkButton-images: true; + transition: 0s ease-in-out; + color: #666; + padding: 3px 5px; + text-shadow: none; + -GtkButton-child-displacement-y: 0px; + -GtkButton-child-displacement-x: 0; + -GtkButton-default-border: 0; + -GtkButton-image-spacing: 5px; + -GtkButton-interior-focus: false; + -GtkButton-inner-border: 0; + +} +#fullscreen_toggle:active, +#focus_toggle:active { + color: #666; + box-shadow: inset 0 0 3 #000; + background-color: #111; + background-image: none; + border: 0px solid #000; + border-color: #333; + -unico-border-gradient: none; + -unico-glow-radius: 0; + -unico-glow-color: #000; + -unico-outer-stroke-color: #000; + -unico-outer-stroke-gradient: none; + -unico-outer-stroke-width: 0; + -unico-inner-stroke-gradient: none; + -unico-inner-stroke-width: 1px; + -unico-border-gradient: none; + -unico-focus-outer-stroke-color: #000; + -unico-outer-stroke-width: 0 0 0 0; + -GtkButton-default-border: 0; + -GtkButton-image-spacing: 0; + -GtkButton-interior-focus: false; + -unico-focus-border-color: #000; + -unico-focus-outer-stroke-color: #000; + -unico-inner-stroke-color: #000; + -unico-inner-stroke-width: 1; + +} + +.separator { + border-color: #444; + border-style: solid; + + -unico-border-gradient: none; + -unico-inner-stroke-color: alpha (#444, 0.6); + -unico-inner-stroke-gradient: none; +} diff --git a/data/media/uberwriter.css b/data/media/uberwriter.css new file mode 100644 index 0000000..1db127f --- /dev/null +++ b/data/media/uberwriter.css @@ -0,0 +1,82 @@ +/************************************ + + uberwriter.css + A simple and clean stylesheet + for pure text and stuff + +************************************/ + +body { + font-family: Georgia, Times, serif; + font-size: 1.em; + + color: #333; + + width: 550px; + margin: 0 auto; +} + + +h1, h2, h3, h4, h5, h6 { + margin-top: 2em; +} + +h1 { + margin-bottom: 2em; +} +blockquote { + border-left: 5px solid #666; + padding-left: 20px; + margin-left: 20px; +} + +p, li { + line-height: 1.8em; + margin-top: 10px; +} + +hr { + margin-top: 40px; + margin-bottom: 40px; + border: none; + width: 80%; + border-top: 1px solid #222; +} + +ol, ul { + margin-left: 0px; + padding-left: 0px; + li { + margin-left: 0; + + } +} + +li ol, li ul{ + margin-left: 30px; +} + +.title { + margin-bottom: 0px; +} +.author, .date { + font-family: Helvetica, Arial, sans-serif; + font-size: 14px; + display: inline-block; + color: #777; + margin-bottom: 30px; +} + +.author::after { + content: ' ,'; +} +.figure { + display: inline-block; +} +img { + max-width: 600px; +} +.caption { + text-align: center; + background: #F6F6F6; +} \ No newline at end of file diff --git a/data/media/uberwriter.svg b/data/media/uberwriter.svg new file mode 100644 index 0000000..85272eb --- /dev/null +++ b/data/media/uberwriter.svg @@ -0,0 +1,1126 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + image/svg+xml + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/data/media/uberwriter_markdown.md b/data/media/uberwriter_markdown.md new file mode 100644 index 0000000..aa5517e --- /dev/null +++ b/data/media/uberwriter_markdown.md @@ -0,0 +1,155 @@ +Markdown Tutorial for UberWriter +================================ + +I will try to give a short impressions on how I use markdown/pandocs capabilities to greatly reduce the time spent on formatting anything -- from websites to PDF Documents. + +You can find a much more exhaustive documentation for all features pandoc offers on pandoc's help page: [Link](http://johnmacfarlane.net/pandoc/README.html#pandocs-markdown) + +### Headers + +There are two styles for headers. One looks like this: + +# Header Level One +## Header Level Two + ... +###### Header Level Six + +And another one, that has only »two« levels: + +Header One +========== + +Header Two +---------- + +You can use both styles, whichever you prefer. Additionally, pandoc requires you to have a blank line before a header. + +### Paragraphs + +A paragraph is one or more lines of text followed by one or more blank line. Newlines are treated as spaces. If you need a hard line break, put two or more spaces at the end of a line, or type a backslash at the end of a line. + +### Block quotations + +Block quotations in markdown use the same convention as in emails. A generic block quote looks like this: + +> This is a block quote. +> This paragraph has two lines. +> +> > And block quotes can be nested, as well. + +Note the empty line you need to leave before the second level blockquote. + +### Code blocks + +There are two ways of creating a code block. You can indent your code four spaces or one tab. + + Code + +Or use a fenced code block: + +```javascript +a = function() { + return 0; +} +``` + +Which works as well. You can identify the language of your code block to add syntax highlighting to the resulting document. + +Short code examples can be surrounded by backticks to make them appear verbatim: `this.code() == true`. + +### Lists + +#### Bullet List: + +* one +* two +* three + +#### Nested Lists: + +* fruits + + pears + + peaches +* vegetables + + broccoli + + ubuntu + - mint + - lubuntu + - kubuntu + +#### Numbered Lists: + +1. Item 1 +2. Item 2 +3. Item 3 + +### Title blocks + +To give your document some meta-information and a nice title, you can use title blocks at the top of your document: + + % title + % author(s) (separated by semicolons) + % date + +### Inline formatting + +Emphasizing some text is done by surrounding it with *s: + +This is *emphasized with asterisks*, and this will be a **bold text**. And even more ***krass***. And if you want to erase something: ~~completely gone~~ (sorrounded by ~) + +### Horizontal Rules + +Horizontal rules are easily created by putting three or more `***` or `---` on a line: + +***** + + +### Super- and subscripts + +Superscripts may be written by surrounding the superscripted text by ^ characters; subscripts may be written by surrounding the subscripted text by ~ characters. Thus, for example, + +H~2~O is a liquid. 2^10^ is 1024. + +### Math + +There are two ways to generate math type setting in pandoc: Inline math looks like this: + +This is inline $1 + 2 = 3$ math. + +Note that there are no spaces allowed next to the dollar signs. + +And there is also another format: + +This is a beautiful equation: $$\left|\sum_{i=1}^n x_i \bar{y}_i\right|^2 \leq \sum_{j=1}^n |x_j|^2 \sum_{k=1}^n |y_k|^2$$ And it stands on it's own. + +### Links + +Enclosing an URL in pointy brackets transforms them into links: + + + + +#### Inline Links: + +This is an [inline link](/url), and here's [one with +a title](http://fsf.org "click here for a good time!"). + +### Images + +![This is the caption](/url/of/image.png) + +### Footnotes + +An example for footnotes (you can place the referenced footnote wherever you want, e.g. at the bottom of your document): + +Here is a footnote reference,[^1] and another.[^longnote] + +[^1]: Here is the footnote. + +[^longnote]: Here's one with multiple blocks. + Subsequent paragraphs are indented to show that they belong to the previous footnote. + The whole paragraph can be indented, or just the first line. In this way, multi-paragraph footnotes work like multi-paragraph list items. + +There is also a different format for inline footnotes, that are easier to write: + +Here is an inline note.^[Inlines notes are easier to write, since you don't have to pick an identifier and move down to type the note.] \ No newline at end of file diff --git a/data/media/white.png b/data/media/white.png new file mode 100644 index 0000000..7c745ea Binary files /dev/null and b/data/media/white.png differ diff --git a/data/ui/AboutUberwriterDialog.ui b/data/ui/AboutUberwriterDialog.ui new file mode 100644 index 0000000..45b73f2 --- /dev/null +++ b/data/ui/AboutUberwriterDialog.ui @@ -0,0 +1,51 @@ + + + + + https://launchpad.net/uberwriter# Copyright (C) 2012, Wolf Vollprecht <w.vollprecht@gmail.com> +# This program is free software: you can redistribute it and/or modify it +# under the terms of the GNU General Public License version 3, as published +# by the Free Software Foundation. +# +# This program is distributed in the hope that it will be useful, but +# WITHOUT ANY WARRANTY; without even the implied warranties of +# MERCHANTABILITY, SATISFACTORY QUALITY, or FITNESS FOR A PARTICULAR +# PURPOSE. See the GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License along +# with this program. If not, see <http://www.gnu.org/licenses/>. +False + 5 + ../media/uberwriter.svg + normal + UberWriter + 12.07.9 + Copyright (C) 2012, Wolf Vollprecht <w.vollprecht@gmail.com> + Copyright (C) 2012, Wolf Vollprecht <w.vollprecht@gmail.com> + ../media/uberwriter.svg + + + True + False + vertical + 2 + + + True + False + end + + + False + True + end + 0 + + + + + + + + + \ No newline at end of file diff --git a/data/ui/UberwriterAdvancedExportDialog.ui b/data/ui/UberwriterAdvancedExportDialog.ui new file mode 100644 index 0000000..4e647b8 --- /dev/null +++ b/data/ui/UberwriterAdvancedExportDialog.ui @@ -0,0 +1,548 @@ + + + + + + False + 5 + dialog + + + False + vertical + 2 + + + False + end + + + gtk-cancel + False + True + True + True + False + True + + + False + True + 1 + + + + + Export + False + True + True + True + True + True + True + True + False + + + False + True + 2 + + + + + False + True + end + 0 + + + + + True + False + vertical + + + True + False + + + False + True + 0 + + + + + True + False + 0 + out + + + True + False + 12 + + + True + False + 5 + 5 + 5 + vertical + + + Smart + False + True + True + False + Pandoc can automatically make "--" to a long dash and more + False + 0 + True + True + + + False + True + 0 + + + + + Normalize + False + True + True + False + Removes things like double spaces or spaces at the beginning of a paragraph + False + 0 + True + + + False + True + 1 + + + + + Table of Contents + False + True + True + False + False + 0 + True + + + False + True + 2 + + + + + Standalone + False + True + True + False + Use a header and footer to include things like stylesheets and meta information + False + 0 + True + True + + + False + True + 3 + + + + + Number Sections + False + True + True + False + False + 0 + True + + + False + True + 4 + + + + + Strict Markdown + False + True + True + False + Use "strict" markdown instead of "pandoc" markdown + False + 0 + True + + + False + True + 5 + + + + + Slideshow incremental bullets + False + True + True + False + Show one bullet point after another in a slideshow + False + 0 + True + + + False + True + 6 + + + + + + + + + True + False + <b>General Options</b> + True + + + + + False + True + 5 + 4 + + + + + True + False + 0 + out + + + True + False + 12 + + + True + False + 5 + 5 + 5 + vertical + + + Highlight syntax + False + True + True + False + False + 0 + True + True + + + False + True + 0 + + + + + True + False + + + True + False + Choose a color theme for syntax highlighting + Highlight style + + + False + True + 0 + + + + + True + False + Choose a color theme for syntax highlighting + 0 + 0 + 1 + 0 + + pygments + kate + monochrome + espresso + zenburn + haddock + tango + + + + True + True + end + 1 + + + + + False + True + 1 + + + + + + + + + True + False + <b>Syntax highlighting</b> (HTML, LaTeX) + True + + + + + False + True + 5 + 5 + + + + + True + False + 0 + out + + + True + False + 12 + + + True + False + 5 + 5 + 5 + vertical + True + + + Self Contained + False + True + True + False + Produces a HTML that has no external dependencies (all images and stylesheets are included) + False + 0 + True + + + False + True + 0 + + + + + HTML 5 + False + True + True + False + Use HTML 5 syntax + False + 0 + True + + + False + True + 1 + + + + + True + False + + + True + False + Choose a CSS File that you want to use + 10 + CSS File + + + False + True + 0 + + + + + True + False + Choose a CSS File that you want to use + vertical + + + True + True + 1 + + + + + False + True + 2 + + + + + + + + + True + False + <b>HTML Options</b> + True + + + + + False + True + 5 + 6 + + + + + True + False + 0 + out + + + True + False + 12 + + + True + False + 5 + 5 + 5 + vertical + 5 + + + + + + + True + False + <b>Bibliography File</b> + True + + + + + False + True + 5 + 7 + + + + + True + False + True + + + Commandline Reference + False + True + True + True + True + False + none + http://johnmacfarlane.net/pandoc/README.html + + + False + True + 5 + 0 + + + + + True + True + 9 + + + + + False + True + 1 + + + + + + button2 + button1 + + + diff --git a/data/ui/UberwriterWindow.ui b/data/ui/UberwriterWindow.ui new file mode 100644 index 0000000..d6f58a4 --- /dev/null +++ b/data/ui/UberwriterWindow.ui @@ -0,0 +1,971 @@ + + + + + + + + True + False + Case Sensitive + icon-case-off.png + + + True + False + Activate Regex + icon-regex-off.png + + + True + False + 0.49000000953674316 + gtk-help + + + True + False + gtk-missing-image + + + True + False + gtk-missing-image + + + + text/plain + text/x-markdown + + + + True + False + UberWriter + 800 + 500 + ../media/uberwriter.svg + + + True + False + + + True + False + + + True + False + _File + True + + + True + False + + + gtk-new + True + False + True + True + + + + + + + gtk-open + True + False + True + True + + + + + + + True + False + Open Recent File + True + + + + + True + False + + + + + gtk-save + True + False + True + True + + + + + + + gtk-save-as + True + False + True + True + + + + + + + True + False + + + + + Export as HTML + True + False + image4 + False + + + + + + Export as PDF + True + False + image3 + False + + + + + + Export as ODT + True + False + image1 + False + + + + + + True + False + Advanced Export... + True + + + + + + True + False + + + + + True + False + Copy raw HTML to clipboard + True + + + + + + True + False + + + + + gtk-close + True + False + True + True + + + + + + + + + + True + False + _Edit + True + + + True + False + + + gtk-cut + True + False + True + True + + + + + + + gtk-copy + True + False + True + True + + + + + + + gtk-paste + True + False + True + True + + + + + + + True + False + + + + + gtk-undo + True + False + True + True + + + + + + + gtk-redo + True + False + True + True + + + + + + + + + + + + True + False + _View + True + + + True + False + + + True + False + Focus Mode + + + + + + + True + False + Fullscreen + + + + + + + True + False + Light text on a dark background + Dark Mode + True + + + + + + True + False + Switch to preview mode + Preview + True + + + + + + + True + False + Open Search and Replace + Search and Replace ... + True + + + + + + + False + + + + + False + Use Typewritermode (experimental) + True + True + + + + + + + True + False + + + + + True + False + Auto _Spellcheck + True + True + + + + + + + + + + + True + False + F_ormat + True + + + True + False + + + gtk-italic + True + False + True + True + + + + + + + gtk-bold + True + False + True + True + + + + + + + True + False + + + + + True + False + Unordered List Item + True + + + + + + + True + False + Horizontal Rule + True + + + + + + + False + False + Heading + True + + + + + + + + + + + True + False + _Help + True + + + True + False + + + True + False + Contents + + + + + + True + False + + + + + True + False + Short Markdown Tutorial + + + + + + True + False + Open Pandoc Online Markdown Help ... + + + + + + True + False + Get Help Online... + True + + + + + + True + False + Translate This Application... + True + + + + + + True + False + + + + + gtk-about + True + False + True + True + + + + + + + + + False + True + 0 + + + + + False + start + vertical + 5 + + + True + False + 5 + + + 100 + True + False + 5 + 0 + Search + + + False + True + 0 + + + + + True + True + + True + + + True + True + 1 + + + + + True + False + False + 1 + + + + True + False + True + Next Match + Next Match + Normal + True + go-down + + + False + True + + + + + True + False + True + Previous Match + Previous Match + Normal + go-up + + + False + True + + + + + True + False + Active + True + icon_case_sensitive1 + + + False + True + + + + + True + False + toolbutton + True + icon_regex1 + + + False + True + + + + + True + False + True + Open Replace + Open Replace + Open Replace + True + edit-find-replace + + + False + True + + + + + False + False + 5 + end + 2 + + + + + False + False + 0 + + + + + True + False + 5 + + + 100 + True + False + 5 + 0 + Replace with + + + False + True + 0 + + + + + True + True + + True + + + True + True + 1 + + + + + True + False + + + + Replace + True + True + True + + + False + True + 0 + + + + + Replace All + True + True + True + + + False + True + 1 + + + + + False + True + 5 + 2 + + + + + False + False + 1 + + + + + False + True + 5 + 1 + + + + + True + True + True + + + 200 + True + False + 5 + vertical + + + False + True + + + + + True + False + True + vertical + + + 500 + True + True + True + + + + + + True + True + 1 + + + + + 15 + True + False + end + 5 + 5 + 5 + + + Focus Mode + 15 + True + True + True + True + Go into focus mode + Go into focus mode + none + False + + + + False + True + 3 + 0 + + + + + Fullscreen + True + True + True + True + Go into fullscreen mode + Go into fullscreen mode + none + False + + + + False + True + 1 + + + + + Preview + True + True + True + True + Show HTML preview + Show HTML preview + none + False + + + + False + True + 2 + + + + + True + False + + + True + False + 5 + Words: + + + False + True + 0 + + + + + True + False + 5 + 1 + 0 + right + 4 + + + False + True + 1 + + + + + True + False + vertical + + + False + True + 6 + 2 + + + + + True + False + 5 + Characters: + + + False + True + 3 + + + + + True + False + 10 + 1 + 0 + 6 + + + False + True + 4 + + + + + False + True + end + 3 + + + + + False + True + 2 + + + + + True + False + + + + + False + True + 2 + + + + + + diff --git a/data/ui/about_uberwriter_dialog.xml b/data/ui/about_uberwriter_dialog.xml new file mode 100644 index 0000000..d19a1d1 --- /dev/null +++ b/data/ui/about_uberwriter_dialog.xml @@ -0,0 +1,9 @@ + + + + + + diff --git a/data/ui/icon-case-off.png b/data/ui/icon-case-off.png new file mode 100644 index 0000000..281ae05 Binary files /dev/null and b/data/ui/icon-case-off.png differ diff --git a/data/ui/icon-regex-off.png b/data/ui/icon-regex-off.png new file mode 100644 index 0000000..61ff932 Binary files /dev/null and b/data/ui/icon-regex-off.png differ diff --git a/data/ui/uberwriter_advanced_export_dialog.xml b/data/ui/uberwriter_advanced_export_dialog.xml new file mode 100644 index 0000000..d1585a2 --- /dev/null +++ b/data/ui/uberwriter_advanced_export_dialog.xml @@ -0,0 +1,9 @@ + + + + + + diff --git a/data/ui/uberwriter_window.xml b/data/ui/uberwriter_window.xml new file mode 100644 index 0000000..f85575d --- /dev/null +++ b/data/ui/uberwriter_window.xml @@ -0,0 +1,8 @@ + + + + + diff --git a/debian/changelog b/debian/changelog new file mode 100644 index 0000000..dc0739a --- /dev/null +++ b/debian/changelog @@ -0,0 +1,218 @@ +uberwriter (12.11.04-public) quantal; urgency=low + + [ Wolf ] + * Added utf 8 encoding to files, necessary or else build on launchpad + fails + -- Wolf Mon, 02 Nov 2012 03:20:00 +0200 + +uberwriter (12.11.03-public) quantal; urgency=low + + [ Wolf ] + * New Preview + * New Inline Preview + * New Session restore for spellcheck and darkmode + + -- Wolf Mon, 01 Nov 2012 22:20:00 +0200 + + +uberwriter (12.11.02-public1-beta) quantal; urgency=low + + [ Wolf ] + * Targetting quantal + + -- Wolf Mon, 01 Oct 2012 15:20:00 +0200 + +uberwriter (12.11.01-public1) quantal; urgency=low + + [ Wolf ] + * Bug resolved involving copy+paste and unicode chars + * Statusbar now fades away (at least in quantal) + * Targetting quantal + + -- Wolf Mon, 01 Oct 2012 11:20:00 +0200 + + +uberwriter (12.08.28-public1) precise; urgency=low + + [ Wolf ] + * Hotfixing a stupid wordcount bug + + -- Wolf Mon, 27 Aug 2012 23:10:00 +0200 + +uberwriter (12.08.27-public1) precise; urgency=low + + [ Wolf ] + * Recent Files now working + * Several bugfixes + + -- Wolf Mon, 27 Aug 2012 23:00:00 +0200 + +uberwriter (12.08.26-public1) precise; urgency=low + + [ Wolf ] + * Advanced Export Menu + + -- Wolf Mon, 27 Aug 2012 10:00:00 +0200 + +uberwriter (12.08.25-publicbeta2) precise; urgency=low + + [ Wolf ] + * Much more useful *.desktop File + + -- Wolf Sat, 25 Aug 2012 15:00:00 +0200 + +uberwriter (12.08.24-publicbeta) precise; urgency=low + + [ Wolf ] + * Various bugfixes + * Auto Spellcheck now settable + * Filename in window title + * ODT instead of RTF export + + -- Wolf Sun, 26 Jul 2012 02:36:23 +0200 + +uberwriter (12.08.04-public1) precise; urgency=low + + [ Wolf ] + * New Button style + * Blockquote get's better styled + * Many, many improvements + + -- Wolf Sun, 26 Jul 2012 02:36:23 +0200 + +uberwriter (12.08.03-public1) precise; urgency=low + + [ Wolf ] + * Added libglib to the correct section + + -- Wolf Sun, 19 Jul 2012 15:09:23 +0200 + +uberwriter (12.08.02-public1) precise; urgency=low + + [ Wolf ] + * Added libglib for launchpad compilation + + -- Wolf Sun, 19 Jul 2012 14:23:34 +0200 + +uberwriter (12.08.01-public1) precise; urgency=low + + [ Wolf ] + * Installs now in opt as promised + + -- Wolf Sun, 19 Jul 2012 14:23:34 +0200 + +uberwriter (12.07.58-public1) precise; urgency=low + + [ Wolf ] + * New Packaging, link probably broken. + + -- Wolf Sun, 15 Jul 2012 13:22:34 +0200 + +uberwriter (12.07.57-public1) precise; urgency=low + + [ Wolf ] + * Various Bugfixes + * Added a spellchecker + + -- Wolf Sun, 15 Jul 2012 13:22:34 +0200 + + +uberwriter (12.07.56-public1) precise; urgency=low + + [ Wolf ] + * Various Bugfixes + * New orange cursor + * No more jumping when switching to focus / typewriter mode + + -- Wolf Sun, 15 Jul 2012 13:22:34 +0200 + +uberwriter (12.07.48-public1) precise; urgency=low + + [ Wolf ] + * Sharing to PPA version bump. + + -- Wolf Sun, 15 Jul 2012 13:22:34 +0200 + +uberwriter (12.07.17-public1) precise; urgency=low + + [ Wolf ] + * New release. + + [ wolf ] + + -- Wolf Sun, 15 Jul 2012 13:22:34 +0200 + +uberwriter (12.07.10-public1ubuntu1) precise; urgency=low + + * + + -- Wolf Sun, 15 Jul 2012 03:20:37 +0200 + +uberwriter (12.07.10-public1) precise; urgency=low + + * New release. + + -- Wolf Sun, 15 Jul 2012 03:11:09 +0200 + +uberwriter (12.07.3ubuntu1) precise; urgency=low + + * + + -- Wolf Sun, 15 Jul 2012 02:50:23 +0200 + +uberwriter (12.07.3) precise; urgency=low + + * Added Dependencies for Pandoc & Latex + + -- Wolf Sun, 15 Jul 2012 02:40:15 +0200 + +uberwriter (12.07.2-public2) precise; urgency=low + + * New release. + + -- Wolf Sun, 15 Jul 2012 02:39:57 +0200 + +uberwriter (12.07.2-public1) precise; urgency=low + + * New release. + + -- Wolf Sun, 15 Jul 2012 02:04:06 +0200 + +uberwriter (12.07.2) precise; urgency=low + + * New release. + + -- Wolf Tue, 10 Jul 2012 01:59:10 +0200 + +uberwriter (12.07.1-public1) precise; urgency=low + + * New release. + + -- Wolf Tue, 10 Jul 2012 01:58:32 +0200 + +uberwriter (12.07.1) precise; urgency=low + + [ Wolf ] + * New release. + + [ wolf ] + + -- Wolf Tue, 10 Jul 2012 01:58:06 +0200 + +uberwriter (12.07) precise; urgency=low + + * Creating ubuntu package + + -- Wolf Mon, 09 Jul 2012 14:10:54 +0200 + +uberwriter (0.1-public1) precise; urgency=low + + * New release. + + -- Wolf Mon, 09 Jul 2012 14:03:43 +0200 + +uberwriter (0.1) precise; urgency=low + + * Initial release. + + -- Wolf Mon, 09 Jul 2012 13:54:01 +0200 diff --git a/debian/compat b/debian/compat new file mode 100644 index 0000000..45a4fb7 --- /dev/null +++ b/debian/compat @@ -0,0 +1 @@ +8 diff --git a/debian/control b/debian/control new file mode 100644 index 0000000..42a2af9 --- /dev/null +++ b/debian/control @@ -0,0 +1,34 @@ +Source: uberwriter +Section: python +Priority: extra +Build-Depends: debhelper (>= 8), + python3 (>= 3.2.3-3~), + python3-distutils-extra (>= 2.37-1~) +Maintainer: Wolf Vollprecht +Standards-Version: 3.9.3 +X-Python-Version: >= 3.2.3 + +Package: uberwriter +Architecture: all +Depends: ${misc:Depends}, + ${python3:Depends}, + python3-enchant, + gir1.2-gtk-3.0, + gir1.2-pango-1.0, + gir1.2-glib-2.0, + python3-cairo, + gir1.2-gdkpixbuf-2.0, + python3-apt, + gir1.2-webkit-3.0, + pandoc, + yelp, + gnome-web-photo, + ttf-ubuntu-font-family, + dvipng +Suggests: texlive +Description: UberWriter, beautiful distraction free writing + With UberWriter you get only one thing: An empty textbox, that is to + fill with your ideas. There are no settings, you don't have to choose a + font, it is only for writing.You can use markdown for all your markup + needs. PDF, RTF and HTML are generated with pandoc. For PDF generation it + is also required that you choose to install the texlive-luatex package. \ No newline at end of file diff --git a/debian/copyright b/debian/copyright new file mode 100644 index 0000000..097dbef --- /dev/null +++ b/debian/copyright @@ -0,0 +1,17 @@ +Format: http://www.debian.org/doc/packaging-manuals/copyright-format/1.0/ +Upstream-Name: uberwriter +Upstream-Contact: Wolf Vollprecht +Source: https://launchpad.com/uberwriter + +Files: * +Copyright: (C) 2007, Joe Smith +Copyright: (C) 2010, Stuart Rackham +Copyright: (C) 2012, Carlos Jenkins +Copyright: (C) 2012, Maximilian Köhl +Copyright: (C) 2012, Rosetta Contributors and Canonical Ltd 2012 +Copyright: (C) 2012, Vova Kolobok +Copyright: (C) 2012, Wolf Vollprecht + +License: GPL-3 + The full text of the GPL is distributed in + /usr/share/common-licenses/GPL-3 on Debian systems. diff --git a/debian/files b/debian/files new file mode 100644 index 0000000..c446dae --- /dev/null +++ b/debian/files @@ -0,0 +1 @@ +uberwriter_12.11.04-public_all.deb python extra diff --git a/debian/quickly/changelog b/debian/quickly/changelog new file mode 100644 index 0000000..38a03db --- /dev/null +++ b/debian/quickly/changelog @@ -0,0 +1,5 @@ +uberwriter (0.1) precise; urgency=low + + * Initial release. + + -- Wolf Thu, 30 Aug 2012 08:12:09 +0200 diff --git a/debian/quickly/compat b/debian/quickly/compat new file mode 100644 index 0000000..45a4fb7 --- /dev/null +++ b/debian/quickly/compat @@ -0,0 +1 @@ +8 diff --git a/debian/quickly/control b/debian/quickly/control new file mode 100644 index 0000000..6cfd37d --- /dev/null +++ b/debian/quickly/control @@ -0,0 +1,29 @@ +Source: uberwriter +Section: python +Priority: extra +Build-Depends: debhelper (>= 8), + python (>= 2.6.6-3~), + python-distutils-extra (>= 2.10) +Maintainer: Wolf Vollprecht +Standards-Version: 3.9.3 +X-Python-Version: >= 2.6 + +Package: uberwriter +Architecture: all +Depends: ${misc:Depends}, + ${python:Depends}, + gir1.2-gtk-3.0, + gir1.2-pango-1.0, + gir1.2-glib-2.0, + uberwriter, + python-cairo, + python-enchant, + python-apt, + yelp +Description: A beautiful, simple and distraction free markdown editor. + UberWriter, beautiful distraction free writing With UberWriter you get + only one thing: An empty textbox, that is to fill with your ideas. + There are no settings, you don't have to choose a font, it is only for + writing.You can use markdown for all your markup needs. PDF, RTF and + HTML are generated with pandoc. For PDF generation it is also required + that you choose to install the texlive-luatex package. diff --git a/debian/quickly/copyright b/debian/quickly/copyright new file mode 100644 index 0000000..4c961fd --- /dev/null +++ b/debian/quickly/copyright @@ -0,0 +1,13 @@ +Format: http://www.debian.org/doc/packaging-manuals/copyright-format/1.0/ +Upstream-Name: uberwriter +Upstream-Contact: Wolf Vollprecht +Source: https://launchpad.com/uberwriter + +Files: * +Copyright: (C) 2007 Joe Smith +Copyright: (C) 2012, Carlos Jenkins +Copyright: (C) 2012 Wolf Vollprecht +Copyright: (C) 2012, Maximilian Köhl +License: GPL-3 + The full text of the GPL is distributed in + /usr/share/common-licenses/GPL-3 on Debian systems. diff --git a/debian/quickly/rules b/debian/quickly/rules new file mode 100755 index 0000000..2c0fe5e --- /dev/null +++ b/debian/quickly/rules @@ -0,0 +1,9 @@ +#!/usr/bin/make -f +%: +ifneq ($(shell dh -l | grep -xF translations),) + dh $@ --with python2,translations +else + dh $@ --with python2 +endif + + diff --git a/debian/rules b/debian/rules new file mode 100755 index 0000000..576731b --- /dev/null +++ b/debian/rules @@ -0,0 +1,22 @@ +#!/usr/bin/make -f +%: +ifneq ($(shell dh -l | grep -xF translations),) + dh $@ --with python3,translations +else + dh $@ --with python3 +endif + +override_dh_auto_install: + dh_auto_install -- --install-scripts=/opt/extras.ubuntu.com/uberwriter/bin --install-data=/opt/extras.ubuntu.com/uberwriter --install-lib=/opt/extras.ubuntu.com/uberwriter + +override_dh_python3: + dh_python3 /opt/extras.ubuntu.com/uberwriter + +override_dh_install: + dh_install + python3 setup.py install --root=$(CURDIR)/debian/uberwriter/ \ + --install-scripts=/opt/extras.ubuntu.com/uberwriter/bin \ + --install-data=/opt/extras.ubuntu.com/uberwriter \ + --install-lib=/opt/extras.ubuntu.com/uberwriter + + cp uberwriter_lib/pylocales/locales.db debian/uberwriter/opt/extras.ubuntu.com/uberwriter/uberwriter_lib/pylocales/locales.db diff --git a/debian/uberwriter.debhelper.log b/debian/uberwriter.debhelper.log new file mode 100644 index 0000000..b6ec0dd --- /dev/null +++ b/debian/uberwriter.debhelper.log @@ -0,0 +1,49 @@ +dh_auto_configure +dh_auto_build +dh_auto_test +dh_prep +dh_installdirs +override_dh_auto_install dh_auto_install +dh_auto_install +override_dh_install dh_install +dh_install +dh_installdocs +dh_installchangelogs +dh_installexamples +dh_installman +dh_installcatalogs +dh_installcron +dh_installdebconf +dh_installemacsen +dh_installifupdown +dh_installinfo +dh_pysupport +dh_python3 +dh_installinit +dh_installmenu +dh_installmime +dh_installmodules +dh_installlogcheck +dh_installlogrotate +dh_installpam +dh_installppp +dh_installudev +dh_installwm +dh_installxfonts +dh_installgsettings +dh_bugfiles +dh_ucf +dh_lintian +dh_gconf +dh_icons +dh_perl +dh_usrlocal +dh_link +dh_translations +dh_compress +dh_fixperms +dh_installdeb +dh_gencontrol +dh_md5sums +dh_builddeb +dh_builddeb diff --git a/debian/uberwriter.postinst.debhelper b/debian/uberwriter.postinst.debhelper new file mode 100644 index 0000000..ec0ca6a --- /dev/null +++ b/debian/uberwriter.postinst.debhelper @@ -0,0 +1,7 @@ + +# Automatically added by dh_python3: +if which py3compile >/dev/null 2>&1; then + py3compile -p uberwriter /opt/extras.ubuntu.com/uberwriter +fi + +# End automatically added section diff --git a/debian/uberwriter.prerm.debhelper b/debian/uberwriter.prerm.debhelper new file mode 100644 index 0000000..314c8b6 --- /dev/null +++ b/debian/uberwriter.prerm.debhelper @@ -0,0 +1,7 @@ + +# Automatically added by dh_python3: +if which py3clean >/dev/null 2>&1; then + py3clean -p uberwriter +fi + +# End automatically added section diff --git a/debian/uberwriter.substvars b/debian/uberwriter.substvars new file mode 100644 index 0000000..4e7212c --- /dev/null +++ b/debian/uberwriter.substvars @@ -0,0 +1,2 @@ +python3:Depends=python3, python3 (>= 3.2.3-3~) +misc:Depends= diff --git a/help/C/figures/icon.png b/help/C/figures/icon.png new file mode 100644 index 0000000..e5cf5ff Binary files /dev/null and b/help/C/figures/icon.png differ diff --git a/help/C/figures/icon_down.png b/help/C/figures/icon_down.png new file mode 100644 index 0000000..e1c2f52 Binary files /dev/null and b/help/C/figures/icon_down.png differ diff --git a/help/C/index.page b/help/C/index.page new file mode 100644 index 0000000..8954936 --- /dev/null +++ b/help/C/index.page @@ -0,0 +1,34 @@ + + + + + UberWriter + The UberWriter help. + + Wolf Vollprecht + w.vollprecht@gmail.com + 2012 + + +

Creative Commons Attribution-Share Alike 3.0 Unported License

+
+
+ + +<!-- This shows on the page in title font --> +<!-- the icon only shows when installed --> +<media type="image" mime="image/png" src="figures/icon_down.png" width="16">[icon]</media> +<app>UberWriter</app> Help + + +

Help Topics for UberWriter:

+ + +
+ +Contents +
+ +
diff --git a/help/C/pandocs-markdown.page b/help/C/pandocs-markdown.page new file mode 100644 index 0000000..a5c6b9c --- /dev/null +++ b/help/C/pandocs-markdown.page @@ -0,0 +1,128 @@ + + + + + + Wolf Vollprecht + w.vollprecht@gmail.com + 2012 + + Introducing Pandoc's Markdown + + +Pandoc's Markdown +

Markdown Tutorial for UberWriter

+

I will try to give a short impressions on how I use markdown/pandocs capabilities to greatly reduce the time spent on formatting anything – from websites to PDF Documents.

+

You can find a much more exhaustive documentation for all features pandoc offers on pandoc’s help page: Link

+

Headers

+

There are two styles for headers. One looks like this:

+

Header Level One

+

Header Level Two

+
        ...
+
Header Level Six
+

And another one, that has only »two« levels:

+

Header One

+

Header Two

+

You can use both styles, whichever you prefer. Additionally, pandoc requires you to have a blank line before a header.

+

Paragraphs

+

A paragraph is one or more lines of text followed by one or more blank line. Newlines are treated as spaces. If you need a hard line break, put two or more spaces at the end of a line, or type a backslash at the end of a line.

+

Block quotations

+

Block quotations in markdown use the same convention as in emails. A generic block quote looks like this:

+
+

This is a block quote. This paragraph has two lines.

+
+

And block quotes can be nested, as well.

+
+
+

Note the empty line you need to leave before the second level blockquote.

+

Code blocks

+

There are two ways of creating a code block. You can indent your code four spaces or one tab.

+
Code
+

Or use a fenced code block:

+
a = function() {
+    return 0;
+}
+

Which works as well. You can identify the language of your code block to add syntax highlighting to the resulting document.

+

Short code examples can be surrounded by backticks to make them appear verbatim: this.code() == true.

+

Lists

+

Bullet List:

+
    +
  • one
  • +
  • two
  • +
  • three
  • +
+

Nested Lists:

+
    +
  • fruits +
      +
    • pears
    • +
    • peaches
    • +
  • +
  • vegetables +
      +
    • broccoli
    • +
    • ubuntu +
        +
      • mint
      • +
      • lubuntu
      • +
      • kubuntu
      • +
    • +
  • +
+

Numbered Lists:

+
    +
  1. Item 1
  2. +
  3. Item 2
  4. +
  5. Item 3
  6. +
+

Title blocks

+

To give your document some meta-information and a nice title, you can use title blocks at the top of your document:

+
% title
+% author(s) (separated by semicolons)
+% date
+

Inline formatting

+

Emphasizing some text is done by surrounding it with *s:

+

This is emphasized with asterisks, and this will be a bold text. And even more krass. And if you want to erase something: completely gone (sorrounded by ~)

+

Horizontal Rules

+

Horizontal rules are easily created by putting three or more *** or --- on a line:

+
+

Super- and subscripts

+

Superscripts may be written by surrounding the superscripted text by ^ characters; subscripts may be written by surrounding the subscripted text by ~ characters. Thus, for example,

+

H2O is a liquid. 210 is 1024.

+

Math

+

There are two ways to generate math type setting in pandoc: Inline math looks like this:

+

This is inline 1 + 2 = 3 math.

+

Note that there are no spaces allowed next to the dollar signs.

+

And there is also another format:

+

This is a beautiful equation:
∣∑ i = 1nxii2 ≤ ∑ j = 1nxj2∑ k = 1nyk2
And it stands on it’s own.

+ +

Enclosing an URL in pointy brackets transforms them into links:

+

http://johnmacfarlane.net/pandoc

+ +

This is an inline link, and here’s one with a title.

+

Images

+
+This is the caption

This is the caption

+
+

Footnotes

+

An example for footnotes (you can place the referenced footnote wherever you want, e.g. at the bottom of your document):

+

Here is a footnote reference,1 and another.2

+

There is also a different format for inline footnotes, that are easier to write:

+

Here is an inline note.3

+
+
+
    +
  1. Here is the footnote.

  2. +
  3. Here’s one with multiple blocks. Subsequent paragraphs are indented to show that they belong to the previous footnote. The whole paragraph can be indented, or just the first line. In this way, multi-paragraph footnotes work like multi-paragraph list items.

  4. +
  5. Inlines notes are easier to write, since you don’t have to pick an identifier and move down to type the note.

  6. +
+
+ +
diff --git a/help/C/preview.page b/help/C/preview.page new file mode 100644 index 0000000..beb7711 --- /dev/null +++ b/help/C/preview.page @@ -0,0 +1,34 @@ + + + + + + Wolf Vollprecht + w.vollprecht@gmail.com + 2012 + + UberWriters preview functionalities + + +UberWriter Preview +

There are 2 different ways to preview your MarkDown files in UberWriter and +quickly check, what you have written. +

+
+ Inline Preview +

+ If you have e.g. math, you can open the context menu with a right click + on your formula and will get a quick preview of your equation inside the context menu. + This will work not only for math, but also for links, footnotes and + images. +

+
+
+Complete Preview +

If you want a complete Preview of your document, you just need to hit the + preview Button on the statusbar at the bottom of the UberWriter window. + It will render the complete HTML Output of your MarkDown file.

+
+
diff --git a/help/stump/help.md b/help/stump/help.md new file mode 100644 index 0000000..c63bf5b --- /dev/null +++ b/help/stump/help.md @@ -0,0 +1,1208 @@ +% Pandoc User's Guide +% John MacFarlane +% January 27, 2012 + +## Pandoc's markdown + +Pandoc understands an extended and slightly revised version of +John Gruber's [markdown] syntax. This document explains the syntax, noting differences from standard markdown. + +### Philosophy + +Markdown is designed to be easy to write, and, even more importantly, easy to read: + +> A Markdown-formatted document should be publishable as-is, as plain text, without looking like it's been marked up with tags or formatting instructions. +> -- [John Gruber](http://daringfireball.net/projects/markdown/syntax#philosophy) + +This principle has guided pandoc's decisions in finding syntax for +tables, footnotes, and other extensions. + +### Paragraphs + +A paragraph is one or more lines of text followed by one or more blank line. Newlines are treated as spaces, so you can reflow your paragraphs as you like. If you need a hard line break, put two or more spaces at the end of a line. + +**Extension: `escaped_line_breaks`** + +A backslash followed by a newline is also a hard line break. + +### Headers + +An header consists of one to six `#` signs and a line of text, optionally followed by any number of `#` signs. +The number of `#` signs at the beginning of the line is the header level: + + ## A level-two header + + ### A level-three header ### + +As with setext-style headers, the header text can contain formatting: + + # A level-one header with a [link](/url) and *emphasis* + +**Extension: `blank_before_header`** + +Standard markdown syntax does not require a blank line before a header. Pandoc does require this (except, of course, at the beginning of the document). The reason for the requirement is that it is all too easy for a `#` to end up at the beginning of a line by accident (perhaps through line wrapping). Consider, for example: + + I like several of their flavors of ice cream: + #22, for example, and #5. + + +### Header identifiers in HTML, LaTeX, and ConTeXt + +**Extension** + +Each header element in pandoc's HTML and ConTeXt output is given a +unique identifier. This identifier is based on the text of the header. +To derive the identifier from the header + + - Remove all formatting, links, etc. + - Remove all punctuation, except underscores, hyphens, and periods. + - Replace all spaces and newlines with hyphens. + - Convert all alphabetic characters to lowercase. + - Remove everything up to the first letter (identifiers may + not begin with a number or punctuation mark). + - If nothing is left after this, use the identifier `section`. + +Thus, for example, + + Header Identifier + ------------------------------- ---------------------------- + Header identifiers in HTML `header-identifiers-in-html` + *Dogs*?--in *my* house? `dogs--in-my-house` + [HTML], [S5], or [RTF]? `html-s5-or-rtf` + 3. Applications `applications` + 33 `section` + +These rules should, in most cases, allow one to determine the identifier from the header text. The exception is when several headers have the same text; in this case, the first will get an identifier as described above; the second will get the same identifier with `-1` appended; the third with `-2`; and so on. + +These identifiers are used to provide link targets in the table of +contents generated by the `--toc|--table-of-contents` option. They +also make it easy to provide links from one section of a document to another. A link to this section, for example, might look like this: + + See the section on + [header identifiers](#header-identifiers-in-html). + +Note, however, that this method of providing links to sections works only in HTML, LaTeX, and ConTeXt formats. + +If the `--section-divs` option is specified, then each section will be wrapped in a `div` (or a `section`, if `--html5` was specified), and the identifier will be attached to the enclosing `
` (or `
`) tag rather than the header itself. This allows entire sections to be manipulated using javascript or treated differently in CSS. + +### Block quotations + +Markdown uses email conventions for quoting blocks of text. +A block quotation is one or more paragraphs or other block elements (such as lists or headers), with each line preceded by a `>` character and a space. + +> This is a block quote. This paragraph does indeed have more than one line. +> +> 1. This is a list inside a block quote. +> 2. Second item. + +Among the block elements that can be contained in a block quote are other block quotes. That is, block quotes can be nested: + +> This is a block quote. +> +>> A block quote within a block quote. + +**Extension: `blank_line_before_blockquote`** + +Standard markdown syntax does not require a blank line before a block quote. Pandoc does require this (except, of course, at the beginning of the document). The reason for the requirement is that it is all too easy for a `>` to end up at the beginning of a line by accident (perhaps through line wrapping). So, unless `--strict` is used, the following does not produce a nested block quote in pandoc: + +> This is a block quote. +>> Nested. + + +### Verbatim (code) blocks + +#### Indented code blocks + +A block of text indented four spaces (or one tab) is treated as verbatim text: that is, special characters do not trigger special formatting, and all spaces and line breaks are preserved. For example, + + if (a > 3) { + moveShip(5 * gravity, DOWN); + } + +The initial (four space or one tab) indentation is not considered part of the verbatim text, and is removed in the output. + +Note: blank lines in the verbatim text need not begin with four spaces. + +#### Delimited code blocks + +**Extension: `delimited_code_blocks`** + +In addition to standard indented code blocks, Pandoc supports +*delimited* code blocks. These begin with a row of three or more +tildes (`~`) or backticks (`` ` ``) and end with a row of tildes or backticks that must be at least as long as the starting row. Everything between these lines is treated as code. No indentation is necessary: + + ~~~~~~~ + if (a > 3) { + moveShip(5 * gravity, DOWN); + } + ~~~~~~~ + +Like regular code blocks, delimited code blocks must be separated +from surrounding text by blank lines. + +If the code itself contains a row of tildes or backticks, just use a longer row of tildes or backticks at the start and end: + + ~~~~~~~~~~~~~~~~ + ~~~~~~~~~~ + code including tildes + ~~~~~~~~~~ + ~~~~~~~~~~~~~~~~ + +Optionally, you may attach attributes to the code block using +this syntax: + + ~~~~ {#mycode .haskell .numberLines startFrom="100"} + qsort [] = [] + qsort (x:xs) = qsort (filter (< x) xs) ++ [x] ++ + qsort (filter (>= x) xs) + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +Here `mycode` is an identifier, `haskell` and `numberLines` are classes, and `startFrom` is an attribute with value `100`. Some output formats can use this information to do syntax highlighting. Currently, the only output formats that uses this information are HTML and LaTeX. If highlighting is supported +for your output format and language, then the code block above will appear highlighted, with numbered lines. (To see which languages are supported, do `pandoc --version`.) Otherwise, the code block above will appear as follows: + +
+      
+      ...
+      
+    
+ +A shortcut form can also be used for specifying the language of +the code block: + + ```haskell + qsort [] = [] + ``` + +This is equivalent to: + + ``` {.haskell} + qsort [] = [] + ``` + +### Lists +#### Bullet lists + +A bullet list is a list of bulleted list items. A bulleted list +item begins with a bullet (`*`, `+`, or `-`). Here is a simple +example: + +* one +* two +* three + +This will produce a "compact" list. If you want a "loose" list, in which each item is formatted as a paragraph, put spaces between the items: + +* one + +* two + +* three + +### The four-space rule + +A list item may contain multiple paragraphs and other block-level +content. However, subsequent paragraphs must be preceded by a blank line and indented four spaces or a tab. The list will look better if the first paragraph is aligned with the rest: + +* First paragraph. + +Continued. + +* Second paragraph. With a code block, which must be indented +eight spaces: + + { code } + +List items may include other lists. In this case the preceding blank line is optional. The nested list must be indented one tab: + +* fruits + + apples + - macintosh + - red delicious + + pears + + peaches +* vegetables + + brocolli + + chard + +The [markdown syntax guide] is not explicit whether the four-space +rule applies to *all* block-level content in a list item; it only +mentions paragraphs and code blocks. But it implies that the rule +applies to all block-level content (including nested lists), and +pandoc interprets it that way. + + [markdown syntax guide]: + http://daringfireball.net/projects/markdown/syntax#list + +### Ordered lists + +Ordered lists work just like bulleted lists, except that the items begin with enumerators rather than bullets. + +In standard markdown, enumerators are decimal numbers followed by a period and a space. The numbers themselves are ignored, so there is no difference between this list: + +1. one +2. two +3. three + +and this one: + +5. one +7. two +1. three + +**Extension: `fancy_lists`** + +Unlike standard markdown, Pandoc allows ordered list items to be marked with uppercase and lowercase letters and roman numerals, in addition to arabic numerals. List markers may be enclosed in parentheses or followed by a single right-parentheses or period. They must be separated from the text that follows by at least one space, and, if the list marker is a capital letter with a period, by at least two spaces.[^2] + +[^2]: The point of this rule is to ensure that normal paragraphs starting with people's initials, like + + B. Russell was an English philosopher. + + do not get treated as list items. + + This rule will not prevent + + (C) 2007 Joe Smith + + from being interpreted as a list item. In this case, a backslash escape can be used: + + (C\) 2007 Joe Smith + +**Extension: `startnum`** + +Pandoc also pays attention to the type of list marker used, and to the starting number, and both of these are preserved where possible in the output format. Thus, the following yields a list with numbers followed by a single parenthesis, starting with 9, and a sublist with lowercase roman numerals: + +9) Ninth +10) Tenth +11) Eleventh + i. subone + ii. subtwo + iii. subthree + +Pandoc will start a new list each time a different type of list marker is used. So, the following will create three lists: + +2) Two +5) Three +1. Four +* Five + +If default list markers are desired, use `#.`: + +#. one +#. two +#. three + + +### Definition lists + +**Extension: `definition_lists`** + +Pandoc supports definition lists, using a syntax inspired by +[PHP Markdown Extra] and [reStructuredText]:[^3] + + Term 1 + + : Definition 1 + + Term 2 with *inline markup* + + : Definition 2 + + { some code, part of Definition 2 } + + Third paragraph of definition 2. + +Each term must fit on one line, which may optionally be followed by a blank line, and must be followed by one or more definitions. +A definition begins with a colon or tilde, which may be indented one or two spaces. The body of the definition (including the first line, aside from the colon or tilde) should be indented four spaces. A term may have multiple definitions, and each definition may consist of one or more block elements (paragraph, code block, list, etc.), each indented four spaces or one tab stop. + +If you leave space after the definition (as in the example above), +the blocks of the definitions will be considered paragraphs. In some output formats, this will mean greater spacing between term/definition pairs. For a compact definition list, do not leave space between the definition and the next term: + + Term 1 + ~ Definition 1 + Term 2 + ~ Definition 2a + ~ Definition 2b + +[^3]: I have also been influenced by the suggestions of [David Wheeler](http://www.justatheory.com/computers/markup/modest-markdown-proposal.html). + +[PHP Markdown Extra]: http://www.michelf.com/projects/php-markdown/extra/ + + +### Numbered example lists + +**Extension: `example_lists`** + +The special list marker `@` can be used for sequentially numbered +examples. The first list item with a `@` marker will be numbered '1', the next '2', and so on, throughout the document. The numbered examples need not occur in a single list; each new list using `@` will take up where the last stopped. So, for example: + + (@) My first example will be numbered (1). + (@) My second example will be numbered (2). + + Explanation of examples. + + (@) My third example will be numbered (3). + +Numbered examples can be labeled and referred to elsewhere in the +document: + + (@good) This is a good example. + + As (@good) illustrates, ... + +The label can be any string of alphanumeric characters, underscores, or hyphens. + +### Compact and loose lists + +Pandoc behaves differently from `Markdown.pl` on some "edge +cases" involving lists. Consider this source: + + + First + + Second: + - Fee + - Fie + - Foe + + + Third + +Pandoc transforms this into a "compact list" (with no `

` tags around "First", "Second", or "Third"), while markdown puts `

` tags around "Second" and "Third" (but not "First"), because of the blank space around "Third". Pandoc follows a simple rule: if the text is followed by a blank line, it is treated as a paragraph. Since "Second" is followed by a list, and not a blank line, it isn't treated as a paragraph. The fact that the list is followed by a blank line is irrelevant. + + +### Ending a list + +What if you want to put an indented code block after a list? + + - item one + - item two + + { my code block } + +Trouble! Here pandoc (like other markdown implementations) will treat `{ my code block }` as the second paragraph of item two, and not as a code block. + +To "cut off" the list after item two, you can insert some non-indented content, like an HTML comment, which won't produce visible output in any format: + + - item one + - item two + + + + { my code block } + +You can use the same trick if you want two consecutive lists instead of one big list: + + 1. one + 2. two + 3. three + + + + 1. uno + 2. dos + 3. tres + +### Horizontal rules + +A line containing a row of three or more `*`, `-`, or `_` characters +(optionally separated by spaces) produces a horizontal rule: + +* * * + + +### Tables + +Four kinds of tables may be used. The first three kinds presuppose the use of a fixed-width font, such as Courier. The fourth kind can be used with proportionally spaced fonts, as it does not require lining up columns. + +#### Simple tables + +Simple tables look like this: + + Right Left Center Default + ------- ------ ---------- ------- + 12 12 12 12 + 123 123 123 123 + 1 1 1 1 + + Table: Demonstration of simple table syntax. + +The headers and table rows must each fit on one line. Column +alignments are determined by the position of the header text relative to the dashed line below it: + +- If the dashed line is flush with the header text on the right side but extends beyond it on the left, the column is right-aligned. +- If the dashed line is flush with the header text on the left side but extends beyond it on the right, the column is left-aligned. +- If the dashed line extends beyond the header text on both sides, the column is centered. +- If the dashed line is flush with the header text on both sides, the default alignment is used (in most cases, this will be left). + +The table must end with a blank line, or a line of dashes followed by a blank line. A caption may optionally be provided (as illustrated in the example above). A caption is a paragraph beginning with the string `Table:` (or just `:`), which will be stripped off. It may appear either before or after the table. + +The column headers may be omitted, provided a dashed line is used +to end the table. For example: + + ------- ------ ---------- ------- + 12 12 12 12 + 123 123 123 123 + 1 1 1 1 + ------- ------ ---------- ------- + +When headers are omitted, column alignments are determined on the basis of the first line of the table body. So, in the tables above, the columns would be right, left, center, and right aligned, respectively. + +#### Multiline tables + +Multiline tables allow headers and table rows to span multiple lines of text (but cells that span multiple columns or rows of the table are not supported). +Here is an example: + + ------------------------------------------------------------- + Centered Default Right Left + Header Aligned Aligned Aligned + ----------- ------- --------------- ------------------------- + First row 12.0 Example of a row that + spans multiple lines. + + Second row 5.0 Here's another one. Note + the blank line between + rows. + ------------------------------------------------------------- + + Table: Here's the caption. + +These work like simple tables, but with the following differences: + + - They must begin with a row of dashes, before the header text + (unless the headers are omitted). + - They must end with a row of dashes, then a blank line. + - The rows must be separated by blank lines. + +In multiline tables, the table parser pays attention to the widths of the columns, and the writers try to reproduce these relative widths in the output. So, if you find that one of the columns is too narrow in the output, try widening it in the markdown source. + +Headers may be omitted in multiline tables as well as simple tables: + + ----------- ------- --------------- ------------------------- + First row 12.0 Example of a row that + spans multiple lines. + + Second row 5.0 Here's another one. Note + the blank line between + rows. + ------------------------------------------------------------- + +It is possible for a multiline table to have just one row, but the row should be followed by a blank line (and then the row of dashes that ends the table), or the table may be interpreted as a simple table. + +#### Grid tables + +Grid tables look like this: + + +---------------+---------------+--------------------+ + | Fruit | Price | Advantages | + +===============+===============+====================+ + | Bananas | $1.34 | - built-in wrapper | + | | | - bright color | + +---------------+---------------+--------------------+ + | Oranges | $2.10 | - cures scurvy | + | | | - tasty | + +---------------+---------------+--------------------+ + +The row of `=`s separates the header from the table body, and can be omitted for a headerless table. The cells of grid tables may contain arbitrary block elements (multiple paragraphs, code blocks, lists, etc.). Alignments are not supported, nor are cells that span multiple columns or rows. Grid tables can be created easily using [Emacs table mode]. + +#### Pipe tables + +Pipe tables look like this: + + | Right | Left | Default | Center | + |------:|:-----|---------|:------:| + | 12 | 12 | 12 | 12 | + | 123 | 123 | 123 | 123 | + | 1 | 1 | 1 | 1 | + +The syntax is the same as in PHP Markdown Extra. The beginning and ending pipe characters are optional, but pipes are required between all columns. The colons indicate column alignment as shown. The header can be omitted, but the horizontal line must still be included, as it defines column alignments. + +Since the pipes indicate column boundaries, columns need not be vertically aligned, as they are in the above example. So, this is a perfectly legal (though ugly) pipe table: + + fruit| price + -----|-----: + apple|2.05 + pear|1.37 + orange|3.09 + +The cells of pipe tables cannot contain block elements like paragraphs and lists, and cannot span multiple lines. + +Title block +----------- + +**Extension: `pandoc_title_blocks`** + +If the file begins with a title block + + % title + % author(s) (separated by semicolons) + % date + +it will be parsed as bibliographic information, not regular text. (It will be used, for example, in the title of standalone LaTeX or HTML output.) The block may contain just a title, a title and an author, or all three elements. If you want to include an author but no title, or a title and a date but no author, you need a blank line: + + % + % Author + + % My title + % + % June 15, 2006 + +The title may occupy multiple lines, but continuation lines must +begin with leading space, thus: + + % My title + on multiple lines + +If a document has multiple authors, the authors may be put on +separate lines with leading space, or separated by semicolons, or +both. So, all of the following are equivalent: + + % Author One + Author Two + + % Author One; Author Two + + % Author One; + Author Two + +The date must fit on one line. + +All three metadata fields may contain standard inline formatting +(italics, links, footnotes, etc.). + +Backslash escapes +----------------- + +**Extension: `all_symbols_escapable`** + +Except inside a code block or inline code, any punctuation or space character preceded by a backslash will be treated literally, even if it would normally indicate formatting. Thus, for example, if one writes + + *\*hello\** + +one will get + + *hello* + +instead of + + hello + +This rule is easier to remember than standard markdown's rule, which allows only the following characters to be backslash-escaped: + + \`*_{}[]()>#+-.! + +A backslash-escaped space is parsed as a nonbreaking space. It will appear in TeX output as `~` and in HTML and XML as `\ ` or `\ `. + +A backslash-escaped newline (i.e. a backslash occurring at the end of a line) is parsed as a hard line break. It will appear in TeX output as `\\` and in HTML as `
`. This is a nice alternative to markdown's "invisible" way of indicating hard line breaks using two trailing spaces on a line. + +Backslash escapes do not work in verbatim contexts. + +### Smart punctuation + +Pandoc will produce typographically correct output, converting straight quotes to curly quotes, `---` to em-dashes, `--` to en-dashes, and `...` to ellipses. Nonbreaking spaces are inserted after certain abbreviations, such as "Mr." + +Note: if your LaTeX template uses the `csquotes` package, pandoc will detect automatically this and use `\enquote{...}` for quoted text. + +### Inline formatting + +To *emphasize* some text, surround it with `*`s or `_`, like this: + + This text is _emphasized with underscores_, and this + is *emphasized with asterisks*. + +Double `*` or `_` produces **strong emphasis**: + + This is **strong emphasis** and __with underscores__. + +A `*` or `_` character surrounded by spaces, or backslash-escaped, +will not trigger emphasis: + + This is * not emphasized *, and \*neither is this\*. + +Because `_` is sometimes used inside words and identifiers, pandoc does not interpret a `_` surrounded by alphanumeric characters as an emphasis marker. If you want to emphasize just part of a word, use `*`: + + feas*ible*, not feas*able*. + +#### Strikeout + +To strikeout a section of text with a horizontal line, begin and end it with `~~`. Thus, for example, + + This ~~is deleted text.~~ + +#### Superscripts and subscripts + +Superscripts may be written by surrounding the superscripted text by `^` characters; subscripts may be written by surrounding the subscripted text by `~` characters. + +Thus, for example, + + H~2~O is a liquid. 2^10^ is 1024. + +If the superscripted or subscripted text contains spaces, these spaces must be escaped with backslashes. (This is to prevent accidental superscripting and subscripting through the ordinary use of `~` and `^`.) + +Thus, if you want the letter P with 'a cat' in subscripts, use +`P~a\ cat~`, not `P~a cat~`. + +#### Verbatim + +To make a short span of text verbatim, put it inside backticks: + + What is the difference between `>>=` and `>>`? + +If the verbatim text includes a backtick, use double backticks: + + Here is a literal backtick `` ` ``. + +(The spaces after the opening backticks and before the closing backticks will be ignored.) + +The general rule is that a verbatim span starts with a string of consecutive backticks (optionally followed by a space) and ends with a string of the same number of backticks (optionally preceded by a space). + +Note that backslash-escapes (and other markdown constructs) do not work in verbatim contexts: + + This is a backslash followed by an asterisk: `\*`. + +**Extension: `inline_code_attributes`** + +Attributes can be attached to verbatim text, just as with +[delimited code blocks](#delimited-code-blocks): + + `<$>`{.haskell} + +### Math + +Anything between two `$` characters will be treated as TeX math. The opening `$` must have a character immediately to its right, while the closing `$` must have a character immediately to its left. Thus, `$20,000 and $30,000` won't parse as math. If for some reason you need to enclose text in literal `$` characters, backslash-escape them and they won't be treated as math delimiters. + +TeX math will be printed in all output formats. How it is rendered depends on the output format: + +* HTML: with (mathjax)[http://www.mathjax.org/] +* Latex: with Latex + +### Raw HTML + +Markdown allows you to insert raw HTML (or DocBook) anywhere in a document (except verbatim contexts, where `<`, `>`, and `&` are interpreted literally). + +Standard markdown allows you to include HTML "blocks": blocks +of HTML between balanced tags that are separated from the surrounding text with blank lines, and start and end at the left margin. + +Within these blocks, everything is interpreted as HTML, not markdown; so (for example), `*` does not signify emphasis. + +Pandoc interprets material between HTML block tags as markdown. +Thus, for example, Pandoc will turn + + + + + + +
*one*[a link](http://google.com)
+ +into + + + + + + +
onea link
+ + + +There is one exception to this rule: text between `