././@PaxHeader 0000000 0000000 0000000 00000000034 00000000000 010212 x ustar 00 28 mtime=1643920524.1925159
ReText-7.2.3/ 0000755 0001750 0001750 00000000000 00000000000 012341 5 ustar 00dmitry dmitry ././@PaxHeader 0000000 0000000 0000000 00000000026 00000000000 010213 x ustar 00 22 mtime=1630777591.0
ReText-7.2.3/LICENSE_GPL 0000644 0001750 0001750 00000105757 00000000000 014067 0 ustar 00dmitry dmitry 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
.
././@PaxHeader 0000000 0000000 0000000 00000000026 00000000000 010213 x ustar 00 22 mtime=1642949280.0
ReText-7.2.3/MANIFEST.in 0000644 0001750 0001750 00000000356 00000000000 014103 0 ustar 00dmitry dmitry include LICENSE_GPL
include README.md
include changelog.md
include configuration.md
include data/retext-kde5.png
recursive-include tests *.py *.md *.rst
recursive-include locale retext_*.ts retext_*.qm
recursive-include icons *.png *.svg
././@PaxHeader 0000000 0000000 0000000 00000000034 00000000000 010212 x ustar 00 28 mtime=1643920524.1925159
ReText-7.2.3/PKG-INFO 0000644 0001750 0001750 00000002263 00000000000 013441 0 ustar 00dmitry dmitry Metadata-Version: 2.1
Name: ReText
Version: 7.2.3
Summary: Simple editor for Markdown and reStructuredText
Home-page: https://github.com/retext-project/retext
Author: Dmitry Shachnev
Author-email: mitya57@gmail.com
License: GPL 2+
Platform: UNKNOWN
Classifier: Development Status :: 5 - Production/Stable
Classifier: Environment :: X11 Applications :: Qt
Classifier: License :: OSI Approved :: GNU General Public License v2 or later (GPLv2+)
Classifier: Programming Language :: Python :: 3 :: Only
Classifier: Topic :: Text Editors
Classifier: Topic :: Text Processing :: Markup
Requires: docutils
Requires: Markdown
Requires: Markups(>=2.0)
Requires: pyenchant
Requires: Pygments
Requires: PyQt5(>=5.11)
Requires-Python: >=3.6
Provides-Extra: spellcheck
License-File: LICENSE_GPL
ReText is simple text editor that supports Markdown and reStructuredText
markup languages. It is written in Python using PyQt libraries.
It supports live preview, tabs, math formulas, export to various formats
including PDF and HTML.
For more details, please go to the `home page`_ or to the `wiki`_.
.. _`home page`: https://github.com/retext-project/retext
.. _`wiki`: https://github.com/retext-project/retext/wiki
././@PaxHeader 0000000 0000000 0000000 00000000026 00000000000 010213 x ustar 00 22 mtime=1642949574.0
ReText-7.2.3/README.md 0000644 0001750 0001750 00000004554 00000000000 013630 0 ustar 00dmitry dmitry Welcome to ReText!
==================
[![GitHub Actions status][GitHub Actions SVG]][GitHub Actions]
ReText is a simple but powerful editor for Markdown and reStructuredText markup
languages. One can also add support for [custom markups] using Python modules.

To install ReText, make sure that you have [Python] (3.6 or later) installed,
and run `pip3 install ReText`. By default it installs system wide, pass
`--user` for installing into the user’s home directory. You can also manually
download the tarball from [PyPI].
ReText requires the following Python modules to run (`pip` will install them
automatically):
* [PyQt5](https://riverbankcomputing.com/software/pyqt/intro) (5.11 or later)
* [Markups](https://pypi.org/project/Markups/) (2.0 or later)
We also recommend having these packages installed:
* [Markdown](https://pypi.org/project/Markdown/) — for Markdown support
* [docutils](https://pypi.org/project/docutils/) — for reStructuredText support
* [pyenchant](https://pypi.org/project/pyenchant/) — for spell checking support
* [PyQtWebEngine](https://pypi.org/project/PyQtWebEngine/) — a more powerful
preview engine with JavaScript support
Translation files are already compiled for release tarballs and will be
automatically loaded. For development snapshots, compile translations using
`lrelease locale/*.ts` command (on Debian-based systems, `lrelease` is
available in `qttools5-dev-tools` package). Translation files can also be
loaded from `/usr/share/retext/` directory.
You can translate ReText into your language on [Transifex].
ReText is Copyright 2011–2021 [Dmitry Shachnev](https://mitya57.me),
2011–2017 [Maurice van der Pot](mailto:griffon26@kfk4ever.com), and is
licensed under GNU GPL (v2+) license, the current version is available in
`LICENSE_GPL` file.
ReText icon is based on `accessories-text-editor` icon from the Faenza theme.
You can read more about ReText in the [wiki].
[wiki]: https://github.com/retext-project/retext/wiki
[PyPI]: https://pypi.org/project/ReText/
[Transifex]: https://www.transifex.com/mitya57/ReText/
[GitHub Actions]: https://github.com/retext-project/retext/actions
[GitHub Actions SVG]: https://github.com/retext-project/retext/workflows/tests/badge.svg
[custom markups]: https://pymarkups.readthedocs.io/en/latest/custom_markups.html
[Python]: https://www.python.org/
././@PaxHeader 0000000 0000000 0000000 00000000034 00000000000 010212 x ustar 00 28 mtime=1643920524.1765156
ReText-7.2.3/ReText/ 0000755 0001750 0001750 00000000000 00000000000 013554 5 ustar 00dmitry dmitry ././@PaxHeader 0000000 0000000 0000000 00000000026 00000000000 010213 x ustar 00 22 mtime=1643919566.0
ReText-7.2.3/ReText/__init__.py 0000644 0001750 0001750 00000012553 00000000000 015673 0 ustar 00dmitry dmitry # vim: ts=8:sts=8:sw=8:noexpandtab
# This file is part of ReText
# Copyright: 2012-2021 Dmitry Shachnev
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see .
import sys
import markups
import markups.common
from os.path import dirname, exists, join, expanduser
from PyQt5.QtCore import QByteArray, QLocale, QSettings, QStandardPaths
from PyQt5.QtGui import QFont, QFontDatabase
app_version = "7.2.3"
settings = QSettings('ReText project', 'ReText')
if not str(settings.fileName()).endswith('.conf'):
# We are on Windows probably
settings = QSettings(QSettings.Format.IniFormat, QSettings.Scope.UserScope,
'ReText project', 'ReText')
datadirs = []
def initializeDataDirs():
assert not datadirs
try:
datadirs.append(dirname(dirname(__file__)))
except NameError:
pass
dataLocations = QStandardPaths.standardLocations(QStandardPaths.StandardLocation.GenericDataLocation)
datadirs.extend(join(d, 'retext') for d in dataLocations)
if sys.platform == "win32":
# Windows compatibility: Add "PythonXXX\share\" path
datadirs.append(join(dirname(sys.executable), 'share', 'retext'))
# For virtualenvs
datadirs.append(join(dirname(dirname(sys.executable)), 'share', 'retext'))
_iconPath = None
def getBundledIcon(iconName):
global _iconPath
if _iconPath is None:
for dir in ['icons'] + datadirs:
_iconPath = join(dir, 'icons')
if exists(_iconPath):
break
return join(_iconPath, iconName + '.png')
configOptions = {
'appStyleSheet': '',
'autoSave': False,
'defaultCodec': '',
'defaultMarkup': markups.MarkdownMarkup.name,
'defaultPreviewState': 'editor',
'detectEncoding': True,
'directoryPath': expanduser("~"),
'documentStatsEnabled': False,
'editorFont': QFont(),
'font': QFont(),
'handleWebLinks': False,
'hideToolBar': False,
'highlightCurrentLine': 'disabled',
'iconTheme': '',
'lastTabIndex': 0,
'lineNumbersEnabled': False,
'markdownDefaultFileExtension': '.mkd',
'openFilesInExistingWindow': True,
'openLastFilesOnStartup': False,
'orderedListMode': 'increment',
'paperSize': '',
'pygmentsStyle': 'default',
'recentDocumentsCount': 10,
'relativeLineNumbers': False,
'restDefaultFileExtension': '.rst',
'rightMargin': 0,
'rightMarginWrap': False,
'saveWindowGeometry': False,
'showDirectoryTree': False,
'spellCheck': False,
'spellCheckLocale': '',
'styleSheet': '',
'syncScroll': True,
'tabBarAutoHide': False,
'tabInsertsSpaces': True,
'tabWidth': 4,
'uiLanguage': QLocale.system().name(),
'useFakeVim': False,
'useWebEngine': False,
'useWebKit': False,
'wideCursor': False,
'windowGeometry': QByteArray(),
'windowTitleFullPath': False,
}
def readFromSettings(key, keytype, settings=settings, default=None):
if isinstance(default, QFont):
family = readFromSettings(key, str, settings, default.family())
size = readFromSettings(key + 'Size', int, settings, 0)
return QFont(family, size)
if not settings.contains(key):
return default
try:
value = settings.value(key, type=keytype)
if isinstance(value, keytype):
return value
return keytype(value)
except TypeError as error:
# Type mismatch
print('Warning: '+str(error))
# Return an instance of keytype
return default if (default is not None) else keytype()
def readListFromSettings(key, settings=settings):
if not settings.contains(key):
return []
value = settings.value(key)
if isinstance(value, str):
return [value]
else:
return value
def writeToSettings(key, value, default, settings=settings):
if isinstance(value, QFont):
writeToSettings(key, value.family(), '', settings)
writeToSettings(key + 'Size', max(value.pointSize(), 0), 0, settings)
elif value == default:
settings.remove(key)
else:
settings.setValue(key, value)
def writeListToSettings(key, value, settings=settings):
if len(value) > 1:
settings.setValue(key, value)
elif len(value) == 1:
settings.setValue(key, value[0])
else:
settings.remove(key)
def getSettingsFilePath(settings=settings):
return settings.fileName()
class ReTextSettings(object):
def __init__(self):
for option in configOptions:
value = configOptions[option]
object.__setattr__(self, option, readFromSettings(
option, type(value), default=value))
def __setattr__(self, option, value):
if not option in configOptions:
raise AttributeError('Unknown attribute')
object.__setattr__(self, option, value)
writeToSettings(option, value, configOptions[option])
def __getattribute__(self, option):
value = object.__getattribute__(self, option)
# Choose a font just-in-time, because when the settings are
# loaded it is too early to work.
if option == 'font' and not value.family():
value = QFont()
if option == 'editorFont' and not value.family():
value = QFontDatabase.systemFont(QFontDatabase.SystemFont.FixedFont)
return value
globalSettings = ReTextSettings()
markups.common.PYGMENTS_STYLE = globalSettings.pygmentsStyle
././@PaxHeader 0000000 0000000 0000000 00000000026 00000000000 010213 x ustar 00 22 mtime=1643655647.0
ReText-7.2.3/ReText/__main__.py 0000755 0001750 0001750 00000012511 00000000000 015651 0 ustar 00dmitry dmitry #!/usr/bin/env python3
# vim: ts=8:sts=8:sw=8:noexpandtab
# ReText
# Copyright 2011-2021 Dmitry Shachnev
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see .
import ctypes
import multiprocessing
import sys
import signal
import markups
from os import devnull
from os.path import join
from ReText import datadirs, settings, globalSettings, app_version
from ReText import initializeDataDirs
from ReText.window import ReTextWindow
from PyQt5.QtCore import QCommandLineOption, QCommandLineParser, QFile, \
QFileInfo, QIODevice, QLibraryInfo, QTextStream, QTranslator, Qt
from PyQt5.QtWidgets import QApplication
from PyQt5.QtNetwork import QNetworkProxyFactory
from PyQt5.QtDBus import QDBusConnection, QDBusInterface
def canonicalize(option):
if option == '-':
return option
return QFileInfo(option).canonicalFilePath()
def main():
multiprocessing.set_start_method('spawn')
if markups.__version_tuple__ < (2, ):
sys.exit('Error: ReText needs PyMarkups 2.0 or newer to run.')
# If we're running on Windows without a console, then discard stdout
# and save stderr to a file to facilitate debugging in case of crashes.
if sys.executable.endswith('pythonw.exe'):
sys.stdout = open(devnull, 'w')
sys.stderr = open('stderr.log', 'w')
try:
# See https://github.com/retext-project/retext/issues/399
# and https://launchpad.net/bugs/941826
ctypes.CDLL('libGL.so.1', ctypes.RTLD_GLOBAL)
except OSError:
pass
# Needed for Qt WebEngine on Windows
QApplication.setAttribute(Qt.ApplicationAttribute.AA_ShareOpenGLContexts)
QApplication.setAttribute(Qt.ApplicationAttribute.AA_UseHighDpiPixmaps)
app = QApplication(sys.argv)
app.setOrganizationName("ReText project")
app.setApplicationName("ReText")
app.setApplicationDisplayName("ReText")
app.setApplicationVersion(app_version)
app.setOrganizationDomain('mitya57.me')
app.setDesktopFileName('me.mitya57.ReText.desktop')
QNetworkProxyFactory.setUseSystemConfiguration(True)
initializeDataDirs()
RtTranslator = QTranslator()
for path in datadirs:
if RtTranslator.load('retext_' + globalSettings.uiLanguage,
join(path, 'locale')):
break
QtTranslator = QTranslator()
QtTranslator.load("qtbase_" + globalSettings.uiLanguage,
QLibraryInfo.location(QLibraryInfo.LibraryLocation.TranslationsPath))
app.installTranslator(RtTranslator)
app.installTranslator(QtTranslator)
parser = QCommandLineParser()
parser.addHelpOption()
parser.addVersionOption()
previewOption = QCommandLineOption('preview',
QApplication.translate('main', 'Open the files in preview mode'))
newWindowOption = QCommandLineOption('new-window',
QApplication.translate('main', 'Create a new window even if there is an existing one'))
parser.addOption(previewOption)
parser.addOption(newWindowOption)
parser.addPositionalArgument('files',
QApplication.translate('main', 'List of files to open'),
'[files...]')
parser.process(app)
filesToOpen = parser.positionalArguments()
print('Using configuration file:', settings.fileName())
if globalSettings.appStyleSheet:
sheetfile = QFile(globalSettings.appStyleSheet)
sheetfile.open(QIODevice.OpenModeFlag.ReadOnly)
app.setStyleSheet(QTextStream(sheetfile).readAll())
sheetfile.close()
window = ReTextWindow()
openInExistingWindow = (globalSettings.openFilesInExistingWindow
and not parser.isSet(newWindowOption))
connection = QDBusConnection.sessionBus()
if connection.isConnected() and openInExistingWindow:
connection.registerObject('/', window, QDBusConnection.RegisterOption.ExportAllSlots)
serviceName = 'me.mitya57.ReText'
if not connection.registerService(serviceName) and filesToOpen:
print('Opening the file(s) in the existing window of ReText.')
iface = QDBusInterface(serviceName, '/', '', connection)
for fileName in filesToOpen:
iface.call('openFileWrapper', fileName)
qWidgetIface = QDBusInterface(serviceName, '/', 'org.qtproject.Qt.QWidget', connection)
qWidgetIface.call('raise')
sys.exit(0)
window.show()
# ReText can change directory when loading files, so we
# need to have a list of canonical names before loading
fileNames = list(map(canonicalize, filesToOpen))
readStdIn = False
if globalSettings.openLastFilesOnStartup:
window.restoreLastOpenedFiles()
for fileName in fileNames:
if QFile.exists(fileName):
window.openFileWrapper(fileName)
if parser.isSet(previewOption):
window.actionPreview.setChecked(True)
window.preview(True)
elif fileName == '-':
readStdIn = True
inputData = ''
if readStdIn and sys.stdin is not None:
if sys.stdin.isatty():
print('Reading stdin, press ^D to end...')
inputData = sys.stdin.read()
if inputData or not window.tabWidget.count():
window.createNew(inputData)
signal.signal(signal.SIGINT, lambda sig, frame: window.close())
sys.exit(app.exec())
if __name__ == '__main__':
main()
././@PaxHeader 0000000 0000000 0000000 00000000026 00000000000 010213 x ustar 00 22 mtime=1642949280.0
ReText-7.2.3/ReText/config.py 0000644 0001750 0001750 00000026074 00000000000 015404 0 ustar 00dmitry dmitry # This file is part of ReText
# Copyright: 2013-2021 Dmitry Shachnev
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see .
import sys
from ReText import globalSettings, getBundledIcon, getSettingsFilePath
from ReText.icontheme import get_icon_theme
from markups.common import CONFIGURATION_DIR
from os.path import join
from PyQt5.QtCore import pyqtSignal, QFile, QFileInfo, QUrl, Qt
from PyQt5.QtGui import QDesktopServices, QIcon
from PyQt5.QtWidgets import QCheckBox, QDialog, QDialogButtonBox, \
QFileDialog, QGridLayout, QLabel, QLineEdit, QPushButton, QSpinBox, \
QComboBox, QTabWidget, QVBoxLayout, QWidget
MKD_EXTS_FILE = join(CONFIGURATION_DIR, 'markdown-extensions.txt')
class FileDialogButton(QPushButton):
def __init__(self, parent, fileName):
QPushButton.__init__(self, parent)
self.fileName = fileName
self.defaultText = self.tr('(none)')
self.updateButtonText()
self.clicked.connect(self.processClick)
def processClick(self):
pass
def updateButtonText(self):
if self.fileName:
self.setText(QFileInfo(self.fileName).fileName())
else:
self.setText(self.defaultText)
class FileSelectButton(FileDialogButton):
def processClick(self):
startDir = (QFileInfo(self.fileName).absolutePath()
if self.fileName else '')
self.fileName = QFileDialog.getOpenFileName(
self, self.tr('Select file to open'), startDir)[0]
self.updateButtonText()
class DirectorySelectButton(FileDialogButton):
def processClick(self):
startDir = (QFileInfo(self.fileName).absolutePath()
if self.fileName else '')
self.fileName = QFileDialog.getExistingDirectory(
self, self.tr('Select directory to open'), startDir)
self.updateButtonText()
class ClickableLabel(QLabel):
clicked = pyqtSignal()
def mousePressEvent(self, event):
self.clicked.emit()
super().mousePressEvent(event)
def setIconThemeFromSettings():
QIcon.setThemeName(globalSettings.iconTheme)
if QIcon.themeName() in ('hicolor', ''):
if not QFile.exists(getBundledIcon('document-new')):
QIcon.setThemeName(get_icon_theme())
if QIcon.themeName() == 'Yaru' and not QIcon.hasThemeIcon('document-new'):
# Old Yaru does not have non-symbolic action icons, so all
# document-* icons fall back to mimetypes/document.png.
# See https://github.com/ubuntu/yaru/issues/1294
QIcon.setThemeName('Humanity')
class ConfigDialog(QDialog):
def __init__(self, parent):
QDialog.__init__(self, parent)
self.parent = parent
self.initConfigOptions()
self.layout = QVBoxLayout(self)
path = getSettingsFilePath()
pathLabel = QLabel(self.tr('Using configuration file at:') +
' %(path)s' % {'path': path}, self)
pathLabel.linkActivated.connect(self.openLink)
self.layout.addWidget(pathLabel)
self.tabWidget = QTabWidget(self)
self.layout.addWidget(self.tabWidget)
buttonBox = QDialogButtonBox(self)
buttonBox.setStandardButtons(QDialogButtonBox.StandardButton.Ok |
QDialogButtonBox.StandardButton.Apply | QDialogButtonBox.StandardButton.Cancel)
buttonBox.accepted.connect(self.acceptSettings)
buttonBox.button(QDialogButtonBox.StandardButton.Apply).clicked.connect(self.saveSettings)
buttonBox.rejected.connect(self.close)
self.initWidgets()
self.configurators['rightMargin'].valueChanged.connect(self.handleRightMarginSet)
self.configurators['rightMarginWrap'].stateChanged.connect(self.handleRightMarginWrapSet)
self.layout.addWidget(buttonBox)
def initConfigOptions(self):
self.tabs = (
(self.tr('Behavior'), (
(self.tr('Automatically save documents'), 'autoSave'),
(self.tr('Automatically open last documents on startup'), 'openLastFilesOnStartup'),
(self.tr('Number of recent documents'), 'recentDocumentsCount'),
(self.tr('Restore window geometry'), 'saveWindowGeometry'),
(self.tr('Default preview state'), 'defaultPreviewState'),
(self.tr('Open external links in ReText window'), 'handleWebLinks'),
(self.tr('Markdown syntax extensions (comma-separated)'), 'markdownExtensions'),
(None, 'markdownExtensions'),
(self.tr('Enable synchronized scrolling for Markdown'), 'syncScroll'),
# (self.tr('Default Markdown file extension'), 'markdownDefaultFileExtension'),
# (self.tr('Default reStructuredText file extension'), 'restDefaultFileExtension'),
)),
(self.tr('Editor'), (
(self.tr('Highlight current line'), 'highlightCurrentLine'),
(self.tr('Show line numbers'), 'lineNumbersEnabled'),
(self.tr('Line numbers are relative to current line'), 'relativeLineNumbers'),
(self.tr('Tab key inserts spaces'), 'tabInsertsSpaces'),
(self.tr('Tabulation width'), 'tabWidth'),
(self.tr('Draw vertical line at column'), 'rightMargin'),
(self.tr('Enable soft wrap'), 'rightMarginWrap'),
(self.tr('Show document stats'), 'documentStatsEnabled'),
(self.tr('Ordered list mode'), 'orderedListMode'),
)),
(self.tr('Interface'), (
(self.tr('Hide toolbar'), 'hideToolBar'),
(self.tr('Icon theme name'), 'iconTheme'),
(self.tr('Stylesheet file'), 'styleSheet', True),
(self.tr('Hide tabs bar when there is only one tab'), 'tabBarAutoHide'),
(self.tr('Show full path in window title'), 'windowTitleFullPath'),
(self.tr('Show directory tree'), 'showDirectoryTree', False),
(self.tr('Working directory'), 'directoryPath', True),
))
)
def initWidgets(self):
self.configurators = {}
for tabTitle, options in self.tabs:
page = self.getPageWidget(options)
self.tabWidget.addTab(page, tabTitle)
def getPageWidget(self, options):
page = QWidget(self)
layout = QGridLayout(page)
for index, option in enumerate(options):
displayname, name = option[:2]
fileselector = option[2] if len(option) > 2 else False
if name is None:
header = QLabel('
%s
' % displayname, self)
layout.addWidget(header, index, 0, 1, 2, Qt.AlignmentFlag.AlignHCenter)
continue
if displayname:
label = ClickableLabel(displayname + ':', self)
if name == 'markdownExtensions':
if displayname:
url = QUrl('https://github.com/retext-project/retext/wiki/Markdown-extensions')
helpButton = QPushButton(self.tr('Help'), self)
helpButton.clicked.connect(lambda: QDesktopServices.openUrl(url))
layout.addWidget(label, index, 0)
layout.addWidget(helpButton, index, 1)
continue
try:
extsFile = open(MKD_EXTS_FILE)
value = extsFile.read().rstrip().replace(extsFile.newlines, ', ')
extsFile.close()
except Exception:
value = ''
self.configurators[name] = QLineEdit(self)
self.configurators[name].setText(value)
layout.addWidget(self.configurators[name], index, 0, 1, 2)
continue
value = getattr(globalSettings, name)
if name == 'defaultPreviewState':
self.configurators[name] = QComboBox(self)
self.configurators[name].addItem(self.tr('Editor'), 'editor')
self.configurators[name].addItem(self.tr('Live preview'), 'live-preview')
self.configurators[name].addItem(self.tr('Normal preview'), 'normal-preview')
comboBoxIndex = self.configurators[name].findData(value)
self.configurators[name].setCurrentIndex(comboBoxIndex)
elif name == 'highlightCurrentLine':
self.configurators[name] = QComboBox(self)
self.configurators[name].addItem(self.tr('Disabled'), 'disabled')
self.configurators[name].addItem(self.tr('Cursor Line'), 'cursor-line')
self.configurators[name].addItem(self.tr('Wrapped Line'), 'wrapped-line')
comboBoxIndex = self.configurators[name].findData(value)
self.configurators[name].setCurrentIndex(comboBoxIndex)
elif name == 'orderedListMode':
self.configurators[name] = QComboBox(self)
self.configurators[name].addItem(self.tr('Increment'), 'increment')
self.configurators[name].addItem(self.tr('Repeat'), 'repeat')
comboBoxIndex = self.configurators[name].findData(value)
self.configurators[name].setCurrentIndex(comboBoxIndex)
elif name == 'directoryPath':
self.configurators[name] = DirectorySelectButton(self, value)
elif isinstance(value, bool):
self.configurators[name] = QCheckBox(self)
self.configurators[name].setChecked(value)
label.clicked.connect(self.configurators[name].nextCheckState)
elif isinstance(value, int):
self.configurators[name] = QSpinBox(self)
if name == 'tabWidth':
self.configurators[name].setRange(1, 10)
elif name == 'recentDocumentsCount':
self.configurators[name].setRange(5, 20)
else:
self.configurators[name].setMaximum(200)
self.configurators[name].setValue(value)
elif isinstance(value, str) and fileselector:
self.configurators[name] = FileSelectButton(self, value)
elif isinstance(value, str):
self.configurators[name] = QLineEdit(self)
self.configurators[name].setText(value)
layout.addWidget(label, index, 0)
layout.addWidget(self.configurators[name], index, 1, Qt.AlignmentFlag.AlignRight)
return page
def handleRightMarginSet(self, value):
if value < 10:
self.configurators['rightMarginWrap'].setChecked(False)
def handleRightMarginWrapSet(self, state):
if state == Qt.CheckState.Checked and self.configurators['rightMargin'].value() < 10:
self.configurators['rightMargin'].setValue(80)
def saveSettings(self):
for name, configurator in self.configurators.items():
if name == 'markdownExtensions':
continue
if isinstance(configurator, QCheckBox):
value = configurator.isChecked()
elif isinstance(configurator, QSpinBox):
value = configurator.value()
elif isinstance(configurator, QLineEdit):
value = configurator.text()
elif isinstance(configurator, QComboBox):
value = configurator.currentData()
elif isinstance(configurator, FileDialogButton):
value = configurator.fileName
setattr(globalSettings, name, value)
self.applySettings()
def applySettings(self):
setIconThemeFromSettings()
try:
extsFile = open(MKD_EXTS_FILE, 'w')
for ext in self.configurators['markdownExtensions'].text().split(','):
if ext.strip():
extsFile.write(ext.strip() + '\n')
extsFile.close()
except Exception as e:
print(e, file=sys.stderr)
for tab in self.parent.iterateTabs():
tab.editBox.updateFont()
tab.editBox.setWrapModeAndWidth()
tab.editBox.viewport().update()
self.parent.updateStyleSheet()
self.parent.tabWidget.setTabBarAutoHide(globalSettings.tabBarAutoHide)
self.parent.toolBar.setVisible(not globalSettings.hideToolBar)
self.parent.editBar.setVisible(not globalSettings.hideToolBar)
self.parent.initDirectoryTree(globalSettings.showDirectoryTree, globalSettings.directoryPath)
def acceptSettings(self):
self.saveSettings()
self.close()
def openLink(self, link):
QDesktopServices.openUrl(QUrl.fromLocalFile(link))
././@PaxHeader 0000000 0000000 0000000 00000000026 00000000000 010213 x ustar 00 22 mtime=1642949280.0
ReText-7.2.3/ReText/converterprocess.py 0000644 0001750 0001750 00000015450 00000000000 017541 0 ustar 00dmitry dmitry # This file is part of ReText
# Copyright: 2016 Maurice van der Pot
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see .
import markups
import multiprocessing as mp
import os
import pickle
import signal
from socket import socketpair
import struct
import traceback
import weakref
from PyQt5.QtCore import pyqtSignal, QObject, QSocketNotifier
def recvall(sock, remaining):
alldata = bytearray()
while remaining > 0:
data = sock.recv(remaining)
if len(data) == 0:
raise EOFError('Received 0 bytes from socket while more bytes were expected. Did the sender process exit unexpectedly?')
alldata.extend(data)
remaining -= len(data)
return alldata
def receiveObject(sock):
sizeBuf = recvall(sock, 4)
size = struct.unpack('I', sizeBuf)[0]
message = recvall(sock, size)
obj = pickle.loads(message)
return obj
def sendObject(sock, obj):
message = pickle.dumps(obj)
sizeBuf = struct.pack('I', len(message))
sock.sendall(sizeBuf)
sock.sendall(message)
class ConversionError(Exception):
pass
class MarkupNotAvailableError(Exception):
pass
def _indent(text, prefix):
return ''.join(('%s%s\n' % (prefix, line) for line in text.splitlines()))
def _converter_process_func(conn_parent, conn_child):
conn_parent.close()
# Ignore ctrl-C. The main application will also receive the signal and
# determine if the application should be stopped or not.
signal.signal(signal.SIGINT, signal.SIG_IGN)
current_markup = None
while True:
job = receiveObject(conn_child)
if job['command'] == 'quit':
break
elif job['command'] == 'convert':
try:
os.chdir(job['current_dir'])
if (not current_markup or
current_markup.name != job['markup_name'] or
current_markup.filename != job['filename']):
markup_class = markups.find_markup_class_by_name(job['markup_name'])
if not markup_class.available():
raise MarkupNotAvailableError('The specified markup was not available')
current_markup = markup_class(job['filename'])
current_markup.requested_extensions = job['requested_extensions']
converted = current_markup.convert(job['text'])
result = ('ok', converted)
except MarkupNotAvailableError as e:
result = ('markupnotavailableerror', e.args)
except Exception:
result = ('conversionerror',
'The background markup conversion process received this exception:\n%s' %
_indent(traceback.format_exc(), ' '))
try:
sendObject(conn_child, result)
except BrokenPipeError:
# Continue despite the broken pipe because we expect that a
# 'quit' command will have been sent. If it has been then we
# should terminate without any error messages. If no command
# was queued we will get an EOFError from the read, giving us a
# second chance to show that something went wrong by exiting
# with a traceback.
continue
class ConverterProcess(QObject):
conversionDone = pyqtSignal()
def __init__(self):
super().__init__()
conn_parent, conn_child = socketpair()
# TODO: figure out which of the two sockets should be set to
# inheritable and which should be passed to the child
if hasattr(conn_child, 'set_inheritable'):
conn_child.set_inheritable(True)
# Use a local variable for child so that we can talk to the child in
# on_finalize without needing a reference to self
child = mp.Process(target=_converter_process_func, args=(conn_parent, conn_child))
child.daemon = True
child.start()
self.child = child
conn_child.close()
self.conn = conn_parent
self.busy = False
self.notificationPending = False
self.conversionNotifier = QSocketNotifier(self.conn.fileno(),
QSocketNotifier.Type.Read)
self.conversionNotifier.activated.connect(self._conversionNotifierActivated)
def on_finalize(conn):
sendObject(conn_parent, {'command':'quit'})
conn_parent.close()
child.join()
weakref.finalize(self, on_finalize, conn_parent)
def _conversionNotifierActivated(self):
# The ready-for-read signal on the socket may be triggered multiple
# times, but we only send a single notification to the client as soon
# as the results of the conversion are starting to come in. This makes
# it easy for clients to avoid multiple calls to get_result for the
# same conversion.
if self.notificationPending:
self.notificationPending = False
# Set the socket to blocking before waking up any interested parties,
# because it has been set to unblocking by QSocketNotifier
self.conn.setblocking(True)
self.conversionDone.emit()
def start_conversion(self, markup_name, filename, requested_extensions, text, current_dir):
if self.busy:
raise RuntimeError('Already converting')
sendObject(self.conn, {'command': 'convert',
'markup_name' : markup_name,
'filename' : filename,
'current_dir': current_dir,
'requested_extensions' : requested_extensions,
'text' : text})
self.busy = True
self.notificationPending = True
def get_result(self):
if not self.busy:
raise RuntimeError('No ongoing conversion')
self.busy = False
status, result = receiveObject(self.conn)
if status == 'markupnotavailableerror':
raise MarkupNotAvailableError(result)
elif status == 'conversionerror':
raise ConversionError(result)
return result
def stop(self):
sendObject(self.conn, {'command': 'quit'})
self.conn.close()
././@PaxHeader 0000000 0000000 0000000 00000000026 00000000000 010213 x ustar 00 22 mtime=1642949280.0
ReText-7.2.3/ReText/dialogs.py 0000644 0001750 0001750 00000004344 00000000000 015555 0 ustar 00dmitry dmitry # This file is part of ReText
# Copyright: 2012-2021 Dmitry Shachnev
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see .
from ReText import globalSettings
from ReText.highlighter import ReTextHighlighter
from PyQt5.QtWidgets import QCheckBox, QDialog, QDialogButtonBox, \
QLabel, QLineEdit, QTextEdit, QVBoxLayout
class HtmlDialog(QDialog):
def __init__(self, parent=None):
QDialog.__init__(self, parent)
self.resize(700, 600)
verticalLayout = QVBoxLayout(self)
self.textEdit = QTextEdit(self)
self.textEdit.setReadOnly(True)
self.textEdit.setFont(globalSettings.editorFont)
self.hl = ReTextHighlighter(self.textEdit.document())
self.hl.docType = 'html'
verticalLayout.addWidget(self.textEdit)
buttonBox = QDialogButtonBox(self)
buttonBox.setStandardButtons(QDialogButtonBox.StandardButton.Close)
buttonBox.rejected.connect(self.close)
verticalLayout.addWidget(buttonBox)
class LocaleDialog(QDialog):
def __init__(self, parent, defaultText=None):
QDialog.__init__(self, parent)
verticalLayout = QVBoxLayout(self)
self.label = QLabel(self)
self.label.setText(self.tr('Enter locale name (example: en_US)'))
verticalLayout.addWidget(self.label)
self.localeEdit = QLineEdit(self)
if defaultText:
self.localeEdit.setText(defaultText)
verticalLayout.addWidget(self.localeEdit)
self.checkBox = QCheckBox(self.tr('Set as default'), self)
verticalLayout.addWidget(self.checkBox)
buttonBox = QDialogButtonBox(self)
buttonBox.setStandardButtons(QDialogButtonBox.StandardButton.Cancel | QDialogButtonBox.StandardButton.Ok)
verticalLayout.addWidget(buttonBox)
buttonBox.accepted.connect(self.accept)
buttonBox.rejected.connect(self.reject)
././@PaxHeader 0000000 0000000 0000000 00000000026 00000000000 010213 x ustar 00 22 mtime=1642949280.0
ReText-7.2.3/ReText/editor.py 0000644 0001750 0001750 00000055204 00000000000 015422 0 ustar 00dmitry dmitry # vim: ts=8:sts=8:sw=8:noexpandtab
#
# This file is part of ReText
# Copyright: 2012-2021 Dmitry Shachnev
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see .
import os
import re
import weakref
from markups import MarkdownMarkup, ReStructuredTextMarkup, TextileMarkup
from ReText import globalSettings, settings, tablemode
from PyQt5.QtCore import pyqtSignal, QFileInfo, QPoint, QRect, QSize, Qt
from PyQt5.QtGui import QColor, QImage, QKeyEvent, QMouseEvent, QPainter, \
QPalette, QTextCursor, QTextFormat, QWheelEvent, QGuiApplication
from PyQt5.QtWidgets import QAction, QApplication, QFileDialog, QLabel, QTextEdit, QWidget
try:
from ReText.fakevimeditor import ReTextFakeVimHandler
except ImportError:
ReTextFakeVimHandler = None
colors = {
# Editor
'marginLine': {'light': '#dcd2dc', 'dark': '#3daee9'},
'currentLineHighlight': {'light': '#ffffc8', 'dark': '#31363b'},
'infoArea': {'light': '#aaaaff55', 'dark': '#aa557f2a'},
'statsArea': {'light': '#aaffaa55', 'dark': '#aa7f552a'},
'lineNumberArea': {'light': '#00ffff', 'dark': '#31363b'},
'lineNumberAreaText': {'light': '#008080', 'dark': '#bdc3c7'},
# Highlighter
'htmlTags': {'light': '#800080', 'dark': '#d070d0'},
'htmlSymbols': {'light': '#008080', 'dark': '#70d0a0'},
'htmlStrings': {'light': '#808000', 'dark': '#d0d070'},
'htmlComments': {'light': '#a0a0a4', 'dark': '#b0b0aa'},
'codeSpans': {'light': '#505050', 'dark': '#afafaf'},
'markdownLinks': {'light': '#000090', 'dark': '#8080ff'},
'blockquotes': {'light': '#808080', 'dark': '#b0b0b0'},
'restDirectives': {'light': '#800080', 'dark': '#d070d0'},
'restRoles': {'light': '#800000', 'dark': '#d07070'},
'whitespaceOnEnd': {'light': '#80e1e1a5', 'dark': '#8096966e'},
}
colorValues = {}
def updateColorScheme(settings=settings):
palette = QApplication.palette()
windowColor = palette.color(QPalette.ColorRole.Window)
themeVariant = 'light' if windowColor.lightness() > 150 else 'dark'
settings.beginGroup('ColorScheme')
for key in colors:
if settings.contains(key):
colorValues[key] = settings.value(key, type=QColor)
else:
colorValues[key] = QColor(colors[key][themeVariant])
settings.endGroup()
def getColor(colorName):
if not colorValues:
updateColorScheme()
return colorValues[colorName]
def documentIndentMore(document, cursor, globalSettings=globalSettings):
if cursor.hasSelection():
block = document.findBlock(cursor.selectionStart())
end = document.findBlock(cursor.selectionEnd()).next()
cursor.beginEditBlock()
while block != end:
cursor.setPosition(block.position())
if globalSettings.tabInsertsSpaces:
cursor.insertText(' ' * globalSettings.tabWidth)
else:
cursor.insertText('\t')
block = block.next()
cursor.endEditBlock()
else:
indent = globalSettings.tabWidth - (cursor.positionInBlock()
% globalSettings.tabWidth)
if globalSettings.tabInsertsSpaces:
cursor.insertText(' ' * indent)
else:
cursor.insertText('\t')
def documentIndentLess(document, cursor, globalSettings=globalSettings):
if cursor.hasSelection():
block = document.findBlock(cursor.selectionStart())
end = document.findBlock(cursor.selectionEnd()).next()
else:
block = document.findBlock(cursor.position())
end = block.next()
cursor.beginEditBlock()
while block != end:
cursor.setPosition(block.position())
if document.characterAt(cursor.position()) == '\t':
cursor.deleteChar()
else:
pos = 0
while document.characterAt(cursor.position()) == ' ' \
and pos < globalSettings.tabWidth:
pos += 1
cursor.deleteChar()
block = block.next()
cursor.endEditBlock()
class ReTextEdit(QTextEdit):
resized = pyqtSignal(QRect)
scrollLimitReached = pyqtSignal(QWheelEvent)
returnBlockPattern = re.compile("^[\\s]*([*>-]|\\d+\\.) ")
orderedListPattern = re.compile("^([\\s]*)(\\d+)\\. $")
wordPattern = re.compile(r"\w+")
nonAlphaNumPattern = re.compile(r"\W")
surroundKeysSelfClose = [
Qt.Key.Key_Underscore,
Qt.Key.Key_Asterisk,
Qt.Key.Key_QuoteDbl,
Qt.Key.Key_Apostrophe
]
surroundKeysOtherClose = {
Qt.Key.Key_ParenLeft: ')',
Qt.Key.Key_BracketLeft: ']'
}
def __init__(self, parent, settings=globalSettings):
QTextEdit.__init__(self)
self.tab = weakref.proxy(parent)
self.parent = parent.p
self.undoRedoActive = False
self.tableModeEnabled = False
self.setAcceptRichText(False)
self.lineNumberArea = LineNumberArea(self)
self.infoArea = LineInfoArea(self)
self.statistics = (0, 0, 0)
self.statsArea = TextInfoArea(self)
self.updateFont()
self.setWrapModeAndWidth()
self.document().blockCountChanged.connect(self.updateLineNumberAreaWidth)
self.cursorPositionChanged.connect(self.highlightCurrentLine)
self.document().contentsChange.connect(self.contentsChange)
self.settings = settings
if globalSettings.useFakeVim:
self.installFakeVimHandler()
def setWrapModeAndWidth(self):
if globalSettings.rightMarginWrap and (self.rect().topRight().x() > self.marginx):
self.setLineWrapMode(QTextEdit.LineWrapMode.FixedPixelWidth)
self.setLineWrapColumnOrWidth(self.marginx)
else:
self.setLineWrapMode(QTextEdit.LineWrapMode.WidgetWidth)
def updateFont(self):
self.setFont(globalSettings.editorFont)
metrics = self.fontMetrics()
self.marginx = (int(self.document().documentMargin())
+ metrics.horizontalAdvance(' ' * globalSettings.rightMargin))
self.setTabStopDistance(globalSettings.tabWidth * metrics.horizontalAdvance(' '))
self.updateLineNumberAreaWidth()
self.infoArea.updateTextAndGeometry()
self.updateTextStatistics()
self.statsArea.updateTextAndGeometry()
if globalSettings.wideCursor:
self.setCursorWidth(metrics.averageCharWidth())
def paintEvent(self, event):
if not globalSettings.rightMargin:
return super().paintEvent(event)
painter = QPainter(self.viewport())
painter.setPen(getColor('marginLine'))
y1 = self.rect().topLeft().y()
y2 = self.rect().bottomLeft().y()
painter.drawLine(self.marginx, y1, self.marginx, y2)
super().paintEvent(event)
def wheelEvent(self, event):
modifiers = QGuiApplication.keyboardModifiers()
if modifiers == Qt.KeyboardModifier.ControlModifier:
font = globalSettings.editorFont
size = font.pointSize()
scroll = event.angleDelta().y()
if scroll > 0:
size += 1
elif scroll < 0:
size -= 1
else:
return
font.setPointSize(size)
self.parent.setEditorFont(font)
else:
super().wheelEvent(event)
if event.angleDelta().y() < 0:
scrollBarLimit = self.verticalScrollBar().maximum()
else:
scrollBarLimit = self.verticalScrollBar().minimum()
if self.verticalScrollBar().value() == scrollBarLimit:
self.scrollLimitReached.emit(event)
def scrollContentsBy(self, dx, dy):
super().scrollContentsBy(dx, dy)
self.lineNumberArea.update()
def contextMenuEvent(self, event):
# Create base menu
menu = self.createStandardContextMenu()
if self.parent.actionPasteImage.isEnabled():
actions = menu.actions()
actionPaste = menu.findChild(QAction, "edit-paste")
actionNextAfterPaste = actions[actions.index(actionPaste) + 1]
menu.insertAction(actionNextAfterPaste, self.parent.actionPasteImage)
text = self.toPlainText()
if not text:
menu.exec(event.globalPos())
return
# Check word under the cursor
oldcursor = self.textCursor()
cursor = self.cursorForPosition(event.pos())
curchar = self.document().characterAt(cursor.position())
isalpha = curchar.isalpha()
dictionary = self.tab.highlighter.dictionary
word = None
if isalpha and not (oldcursor.hasSelection() and oldcursor.selectedText() != cursor.selectedText()):
cursor.select(QTextCursor.SelectionType.WordUnderCursor)
word = cursor.selectedText()
if word is not None and dictionary and not dictionary.check(word):
self.setTextCursor(cursor)
suggestions = dictionary.suggest(word)
actions = [self.parent.act(sug, trig=self.fixWord(sug)) for sug in suggestions]
menu.insertSeparator(menu.actions()[0])
for action in actions[::-1]:
menu.insertAction(menu.actions()[0], action)
menu.insertSeparator(menu.actions()[0])
menu.insertAction(menu.actions()[0], self.parent.act(self.tr('Add to dictionary'), trig=self.learnWord(word)))
menu.addSeparator()
menu.addAction(self.parent.actionMoveUp)
menu.addAction(self.parent.actionMoveDown)
menu.exec(event.globalPos())
def fixWord(self, correctword):
return lambda: self.insertPlainText(correctword)
def learnWord(self, newword):
return lambda: self.addNewWord(newword)
def addNewWord(self, newword):
cursor = self.textCursor()
block = cursor.block()
cursor.clearSelection()
self.setTextCursor(cursor)
dictionary = self.tab.highlighter.dictionary
if (dictionary is None) or not newword:
return
dictionary.add(newword)
self.tab.highlighter.rehighlightBlock(block)
def isSurroundKey(self, key):
return key in self.surroundKeysSelfClose or key in self.surroundKeysOtherClose
def getCloseKey(self, event, key):
if key in self.surroundKeysSelfClose:
return event.text()
if key in self.surroundKeysOtherClose:
return self.surroundKeysOtherClose[key]
def surroundText(self, cursor, event, key):
text = cursor.selectedText()
keyStr = event.text()
keyClose = self.getCloseKey(event, key)
cursor.insertText(keyStr + text + keyClose)
def keyPressEvent(self, event):
key = event.key()
cursor = self.textCursor()
if key == Qt.Key.Key_Backspace and event.modifiers() & Qt.KeyboardModifier.GroupSwitchModifier:
# Workaround for https://bugreports.qt.io/browse/QTBUG-49771
event = QKeyEvent(event.type(), event.key(),
event.modifiers() ^ Qt.KeyboardModifier.GroupSwitchModifier)
if key == Qt.Key.Key_Tab:
documentIndentMore(self.document(), cursor)
elif key == Qt.Key.Key_Backtab:
documentIndentLess(self.document(), cursor)
elif key == Qt.Key.Key_Return:
markupClass = self.tab.getActiveMarkupClass()
if event.modifiers() & Qt.KeyboardModifier.ControlModifier:
cursor.insertText('\n')
self.ensureCursorVisible()
elif self.tableModeEnabled and tablemode.handleReturn(cursor, markupClass,
newRow=(event.modifiers() & Qt.KeyboardModifier.ShiftModifier)):
self.setTextCursor(cursor)
self.ensureCursorVisible()
else:
if event.modifiers() & Qt.KeyboardModifier.ShiftModifier and markupClass == MarkdownMarkup:
# Insert Markdown-style line break
cursor.insertText(' ')
self.handleReturn(cursor)
elif cursor.selectedText() and self.isSurroundKey(key):
self.surroundText(cursor, event, key)
else:
if event.text() and self.tableModeEnabled:
cursor.beginEditBlock()
super().keyPressEvent(event)
if event.text() and self.tableModeEnabled:
cursor.endEditBlock()
def handleReturn(self, cursor):
# Select text between the cursor and the line start
cursor.movePosition(QTextCursor.MoveOperation.StartOfBlock, QTextCursor.MoveMode.KeepAnchor)
text = cursor.selectedText()
length = len(text)
match = self.returnBlockPattern.search(text)
if match is not None:
matchedText = match.group(0)
if len(matchedText) == length:
cursor.removeSelectedText()
matchedText = ''
else:
matchOL = self.orderedListPattern.match(matchedText)
if matchOL is not None:
matchedPrefix = matchOL.group(1)
matchedNumber = int(matchOL.group(2))
nextNumber = matchedNumber if self.settings.orderedListMode == 'repeat' else matchedNumber + 1
matchedText = matchedPrefix + str(nextNumber) + ". "
else:
matchedText = ''
# Reset the cursor
cursor = self.textCursor()
cursor.insertText('\n' + matchedText)
self.ensureCursorVisible()
def moveLineUp(self):
self.moveLine(QTextCursor.MoveOperation.PreviousBlock)
def moveLineDown(self):
self.moveLine(QTextCursor.MoveOperation.NextBlock)
def moveLine(self, direction):
cursor = self.textCursor()
# Select the current block
cursor.movePosition(QTextCursor.MoveOperation.StartOfBlock, QTextCursor.MoveMode.MoveAnchor)
cursor.movePosition(QTextCursor.MoveOperation.NextBlock, QTextCursor.MoveMode.KeepAnchor)
text = cursor.selectedText()
# Remove it
cursor.removeSelectedText()
# Move to the wanted block
cursor.movePosition(direction, QTextCursor.MoveMode.MoveAnchor)
# Paste the line
cursor.insertText(text)
# Move to the pasted block
cursor.movePosition(QTextCursor.MoveOperation.PreviousBlock, QTextCursor.MoveMode.MoveAnchor)
# Update cursor
self.setTextCursor(cursor)
def lineNumberAreaWidth(self):
if not globalSettings.lineNumbersEnabled:
return 0
cursor = QTextCursor(self.document())
cursor.movePosition(QTextCursor.MoveOperation.End)
if globalSettings.relativeLineNumbers:
digits = len(str(cursor.blockNumber())) + 1
else:
digits = len(str(cursor.blockNumber() + 1))
return 5 + self.fontMetrics().horizontalAdvance('9') * digits
def updateLineNumberAreaWidth(self, blockcount=0):
self.setViewportMargins(self.lineNumberAreaWidth(), 0, 0, 0)
def resizeEvent(self, event):
super().resizeEvent(event)
rect = self.contentsRect()
self.resized.emit(rect)
self.lineNumberArea.setGeometry(rect.left(), rect.top(),
self.lineNumberAreaWidth(), rect.height())
self.infoArea.updateTextAndGeometry()
self.statsArea.updateTextAndGeometry()
self.setWrapModeAndWidth()
self.ensureCursorVisible()
def highlightCurrentLine(self):
if globalSettings.relativeLineNumbers:
self.lineNumberArea.update()
if globalSettings.highlightCurrentLine == 'disabled':
return self.setExtraSelections([])
selection = QTextEdit.ExtraSelection()
selection.format.setBackground(getColor('currentLineHighlight'))
selection.format.setProperty(QTextFormat.Property.FullWidthSelection, True)
selection.cursor = self.textCursor()
selection.cursor.clearSelection()
selections = [selection]
if globalSettings.highlightCurrentLine == 'wrapped-line':
selections.append(QTextEdit.ExtraSelection())
selections[0].cursor.movePosition(QTextCursor.MoveOperation.StartOfBlock)
selections[0].cursor.movePosition(QTextCursor.MoveOperation.EndOfBlock, QTextCursor.MoveMode.KeepAnchor)
selections[1].format.setBackground(getColor('currentLineHighlight'))
selections[1].format.setProperty(QTextFormat.Property.FullWidthSelection, True)
selections[1].cursor = self.textCursor()
selections[1].cursor.movePosition(QTextCursor.MoveOperation.EndOfBlock)
elif selection.cursor.block().textDirection() == Qt.LayoutDirection.RightToLeft:
# FullWidthSelection does not work correctly for RTL direction
selection.cursor.movePosition(QTextCursor.MoveOperation.StartOfLine)
selection.cursor.movePosition(QTextCursor.MoveOperation.EndOfLine, QTextCursor.MoveMode.KeepAnchor)
self.setExtraSelections(selections)
def enableTableMode(self, enable):
self.tableModeEnabled = enable
def backupCursorPositionOnLine(self):
return self.textCursor().positionInBlock()
def restoreCursorPositionOnLine(self, positionOnLine):
cursor = self.textCursor()
cursor.setPosition(cursor.block().position() + positionOnLine)
self.setTextCursor(cursor)
def contentsChange(self, pos, removed, added):
if self.tableModeEnabled:
markupClass = self.tab.getActiveMarkupClass()
cursorPosition = self.backupCursorPositionOnLine()
tablemode.adjustTableToChanges(self.document(), pos, added - removed, markupClass)
self.restoreCursorPositionOnLine(cursorPosition)
self.lineNumberArea.update()
self.updateTextStatistics()
def findNextImageName(self, filenames):
highestNumber = 0
for filename in filenames:
m = re.match(r'image(\d+).png', filename, re.IGNORECASE)
if m:
number = int(m.group(1))
highestNumber = max(number, highestNumber)
return 'image%04d.png' % (highestNumber + 1)
def getImageFilename(self):
if self.tab.fileName:
saveDir = os.path.dirname(self.tab.fileName)
else:
saveDir = os.getcwd()
imageFileName = self.findNextImageName(os.listdir(saveDir))
return QFileDialog.getSaveFileName(self,
self.tr('Save image'),
os.path.join(saveDir, imageFileName),
self.tr('Images (*.png *.jpg)'))[0]
def makeFileNameRelative(self, fileName):
"""Tries to make the given fileName relative. If the document is
not saved, or the fileName is on a different root, returns the
original fileName.
"""
if self.tab.fileName:
currentDir = os.path.dirname(self.tab.fileName)
try:
return os.path.relpath(fileName, currentDir)
except ValueError: # different roots
return fileName
return fileName
def getImageMarkup(self, fileName):
"""Returns markup for image in the current markup language.
This method is also accessed in ReTextWindow.insertImage.
"""
link = self.makeFileNameRelative(fileName)
markupClass = self.tab.getActiveMarkupClass()
if markupClass == MarkdownMarkup:
return '' % (QFileInfo(link).baseName(), link)
elif markupClass == ReStructuredTextMarkup:
return '.. image:: %s' % link
elif markupClass == TextileMarkup:
return '!%s!' % link
def pasteImage(self):
mimeData = QApplication.instance().clipboard().mimeData()
fileName = self.getImageFilename()
if not fileName or not mimeData.hasImage():
return
image = QImage(mimeData.imageData())
image.save(fileName)
imageText = self.getImageMarkup(fileName)
self.textCursor().insertText(imageText)
def installFakeVimHandler(self):
if ReTextFakeVimHandler:
fakeVimEditor = ReTextFakeVimHandler(self, self.parent)
fakeVimEditor.setSaveAction(self.parent.actionSave)
fakeVimEditor.setQuitAction(self.parent.actionQuit)
self.parent.actionFakeVimMode.triggered.connect(fakeVimEditor.remove)
def updateTextStatistics(self):
if not globalSettings.documentStatsEnabled:
return
text = self.toPlainText()
wordCount = len(self.wordPattern.findall(text))
alphaNums = self.nonAlphaNumPattern.sub('', text)
alphaNumCount = len(alphaNums)
characterCount = len(text)
self.statistics = (wordCount, alphaNumCount, characterCount)
class LineNumberArea(QWidget):
def __init__(self, editor):
QWidget.__init__(self, editor)
self.editor = editor
def sizeHint(self):
return QSize(self.editor.lineNumberAreaWidth(), 0)
def paintEvent(self, event):
if not globalSettings.lineNumbersEnabled:
return super().paintEvent(event)
painter = QPainter(self)
painter.fillRect(event.rect(), getColor('lineNumberArea'))
painter.setPen(getColor('lineNumberAreaText'))
cursor = self.editor.cursorForPosition(QPoint(0, 0))
atEnd = False
fontHeight = self.fontMetrics().height()
height = self.editor.height()
if globalSettings.relativeLineNumbers:
relativeTo = self.editor.textCursor().blockNumber()
else:
relativeTo = -1
while not atEnd:
rect = self.editor.cursorRect(cursor)
if rect.top() >= height:
break
number = str(cursor.blockNumber() - relativeTo).replace('-', '−')
painter.drawText(0, rect.top(), self.width() - 2,
fontHeight, Qt.AlignmentFlag.AlignRight, number)
cursor.movePosition(QTextCursor.MoveOperation.EndOfBlock)
atEnd = cursor.atEnd()
if not atEnd:
cursor.movePosition(QTextCursor.MoveOperation.NextBlock)
class InfoArea(QLabel):
def __init__(self, editor, baseColor):
QWidget.__init__(self, editor)
self.editor = editor
self.editor.cursorPositionChanged.connect(self.updateTextAndGeometry)
self.updateTextAndGeometry()
self.setAutoFillBackground(True)
self.baseColor = baseColor
palette = self.palette()
palette.setColor(QPalette.ColorRole.Window, self.baseColor)
self.setPalette(palette)
self.setCursor(Qt.CursorShape.IBeamCursor)
def updateTextAndGeometry(self):
text = self.getText()
(w, h) = self.getAreaSize(text)
(x, y) = self.getAreaPosition(w, h)
self.setText(text)
self.resize(w, h)
self.move(x, y)
self.setVisible(not globalSettings.useFakeVim)
def getAreaSize(self, text):
metrics = self.fontMetrics()
width = metrics.horizontalAdvance(text)
height = metrics.height()
return width, height
def getAreaPosition(self, width, height):
return 0, 0
def getText(self):
return ""
def enterEvent(self, event):
palette = self.palette()
windowColor = QColor(self.baseColor)
windowColor.setAlpha(0x20)
palette.setColor(QPalette.ColorRole.Window, windowColor)
textColor = palette.color(QPalette.ColorRole.WindowText)
textColor.setAlpha(0x20)
palette.setColor(QPalette.ColorRole.WindowText, textColor)
self.setPalette(palette)
def leaveEvent(self, event):
palette = self.palette()
palette.setColor(QPalette.ColorRole.Window, self.baseColor)
palette.setColor(QPalette.ColorRole.WindowText,
self.editor.palette().color(QPalette.ColorRole.WindowText))
self.setPalette(palette)
def mousePressEvent(self, event):
pos = self.mapToParent(event.pos())
pos.setX(pos.x() - self.editor.lineNumberAreaWidth())
newEvent = QMouseEvent(event.type(), pos,
event.button(), event.buttons(),
event.modifiers())
self.editor.mousePressEvent(newEvent)
mouseReleaseEvent = mousePressEvent
mouseDoubleClickEvent = mousePressEvent
mouseMoveEvent = mousePressEvent
class LineInfoArea(InfoArea):
def __init__(self, editor):
InfoArea.__init__(self, editor, getColor('infoArea'))
def getAreaPosition(self, width, height):
viewport = self.editor.viewport()
rightSide = viewport.width() + self.editor.lineNumberAreaWidth()
if globalSettings.documentStatsEnabled:
return rightSide - width, viewport.height() - (2 * height)
else:
return rightSide - width, viewport.height() - height
def getText(self):
template = '%d : %d'
cursor = self.editor.textCursor()
block = cursor.blockNumber() + 1
position = cursor.positionInBlock()
return template % (block, position)
class TextInfoArea(InfoArea):
def __init__(self, editor):
InfoArea.__init__(self, editor, getColor('statsArea'))
def getAreaPosition(self, width, height):
viewport = self.editor.viewport()
rightSide = viewport.width() + self.editor.lineNumberAreaWidth()
return rightSide - width, viewport.height() - height
def getText(self):
if not globalSettings.documentStatsEnabled:
return
template = self.tr('%d w | %d a | %d c',
'count of words, alphanumeric characters, all characters')
words, alphaNums, characters = self.editor.statistics
return template % (words, alphaNums, characters)
././@PaxHeader 0000000 0000000 0000000 00000000026 00000000000 010213 x ustar 00 22 mtime=1633978476.0
ReText-7.2.3/ReText/fakevimeditor.py 0000644 0001750 0001750 00000021261 00000000000 016761 0 ustar 00dmitry dmitry # This file is part of ReText
# Copyright: 2014 Lukas Holecek
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see .
from FakeVim import FakeVimProxy, FakeVimHandler, FAKEVIM_PYQT_VERSION, \
MessageError
if FAKEVIM_PYQT_VERSION != 5:
raise ImportError("FakeVim must be compiled with Qt 5")
from PyQt5.QtCore import QDir, QRegExp, QObject, Qt
from PyQt5.QtGui import QPainter, QPen, QTextCursor
from PyQt5.QtWidgets import QWidget, QLabel, QLineEdit, \
QMessageBox, QStatusBar, QTextEdit
class FakeVimMode:
@staticmethod
def init(window):
window.setStatusBar(StatusBar())
@staticmethod
def exit(window):
window.statusBar().deleteLater()
class Proxy (FakeVimProxy):
""" Used by FakeVim to modify or retrieve editor state. """
def __init__(self, window, editor, handler):
super(Proxy, self).__init__(handler.handler())
self.__handler = handler
self.__window = window
self.__editor = editor
self.__statusMessage = ""
self.__statusData = ""
self.__cursorPosition = -1
self.__cursorAnchor = -1
self.__eventFilter = None
self.__lastSavePath = ""
def showMessage(self, messageLevel, message):
self.__handler.handler().showMessage(messageLevel, message)
def needSave(self):
return self.__editor.document().isModified()
def maybeCloseEditor(self):
if self.needSave():
self.showMessage( MessageError,
self.tr("No write since last change (add ! to override)") )
self.__updateStatusBar()
return False
return True
def commandQuit(self):
self.__handler.quit()
def commandWrite(self):
self.__handler.save()
return not self.needSave()
def handleExCommand(self, cmd):
if cmd.matches("q", "quit"):
if cmd.hasBang or self.maybeCloseEditor():
self.commandQuit()
elif cmd.matches("w", "write"):
self.commandWrite()
elif cmd.cmd == "wq":
self.commandWrite() and self.commandQuit()
else:
return False
return True
def enableBlockSelection(self, cursor):
self.__handler.setBlockSelection(True)
self.__editor.setTextCursor(cursor)
def disableBlockSelection(self):
self.__handler.setBlockSelection(False)
def blockSelection(self):
self.__handler.setBlockSelection(True)
return self.__editor.textCursor()
def hasBlockSelection(self):
return self.__handler.hasBlockSelection()
def commandBufferChanged(self, msg, cursorPosition, cursorAnchor, messageLevel, eventFilter):
# Give focus back to editor if closing command line.
if self.__cursorPosition != -1 and cursorPosition == -1:
self.__editor.setFocus()
self.__cursorPosition = cursorPosition
self.__cursorAnchor = cursorAnchor
self.__statusMessage = msg
self.__updateStatusBar();
self.__eventFilter = eventFilter
def statusDataChanged(self, msg):
self.__statusData = msg
self.__updateStatusBar()
def extraInformationChanged(self, msg):
QMessageBox.information(self.__window, self.tr("Information"), msg)
def highlightMatches(self, pattern):
self.__handler.highlightMatches(pattern)
def __updateStatusBar(self):
self.__window.statusBar().setStatus(
self.__statusMessage, self.__statusData,
self.__cursorPosition, self.__cursorAnchor, self.__eventFilter)
class BlockSelection (QWidget):
def __init__(self, editor):
super(BlockSelection, self).__init__(editor.viewport())
self.__editor = editor
self.__lineWidth = 4
def updateSelection(self, tc):
# block selection rectagle
rect = self.__editor.cursorRect(tc)
w = rect.width()
tc2 = QTextCursor(tc)
tc2.setPosition(tc.anchor())
rect = rect.united( self.__editor.cursorRect(tc2) )
x = self.__lineWidth / 2
rect.adjust(-x, -x, x - w, x)
self.setGeometry(rect)
def paintEvent(self, paintEvent):
painter = QPainter(self)
painter.setClipRect(paintEvent.rect())
color = self.__editor.palette().text()
painter.setPen(QPen(color, self.__lineWidth))
painter.drawRect(self.rect())
class ReTextFakeVimHandler (QObject):
""" Editor widget driven by FakeVim. """
def __init__(self, editor, window):
super(ReTextFakeVimHandler, self).__init__(window)
self.__window = window
self.__editor = editor
self.__blockSelection = BlockSelection(self.__editor)
self.__blockSelection.hide()
self.__searchSelections = []
fm = self.__editor.fontMetrics()
self.__cursorWidth = fm.averageCharWidth()
self.__oldCursorWidth = self.__editor.cursorWidth()
self.__editor.setCursorWidth(self.__cursorWidth)
self.__handler = FakeVimHandler(self.__editor, self)
self.__proxy = Proxy(self.__window, self.__editor, self)
self.__handler.installEventFilter()
self.__handler.setupWidget()
self.__handler.handleCommand(
'source {home}/.vimrc'.format(home = QDir.homePath()))
self.__saveAction = None
self.__quitAction = None
# Update selections if cursor changes because of current line can be highlighted.
self.__editor.cursorPositionChanged.connect(self.__updateSelections)
def remove(self):
self.__editor.setOverwriteMode(False)
self.__editor.setCursorWidth(self.__oldCursorWidth)
self.__blockSelection.deleteLater()
self.__updateSelections([])
self.deleteLater()
def handler(self):
return self.__handler
def setBlockSelection(self, enabled):
self.__editor.setCursorWidth(self.__cursorWidth)
self.__blockSelection.setVisible(enabled)
if enabled:
self.__blockSelection.updateSelection(self.__editor.textCursor())
# Shift text cursor into the block selection.
tc = self.__editor.textCursor()
if self.__columnForPosition(tc.anchor()) < self.__columnForPosition(tc.position()):
self.__editor.setCursorWidth(-self.__cursorWidth)
def setSaveAction(self, saveAction):
self.__saveAction = saveAction
def setQuitAction(self, quitAction):
self.__quitAction = quitAction
def save(self):
if self.__saveAction:
self.__saveAction.trigger()
def quit(self):
if self.__quitAction:
self.__quitAction.trigger()
def hasBlockSelection(self):
return self.__blockSelection.isVisible()
def highlightMatches(self, pattern):
cur = self.__editor.textCursor()
re = QRegExp(pattern)
cur = self.__editor.document().find(re)
a = cur.position()
searchSelections = []
while not cur.isNull():
if cur.hasSelection():
selection = QTextEdit.ExtraSelection()
selection.format.setBackground(Qt.GlobalColor.yellow)
selection.format.setForeground(Qt.GlobalColor.black)
selection.cursor = cur
searchSelections.append(selection)
else:
cur.movePosition(QTextCursor.MoveOperation.NextCharacter)
cur = self.__editor.document().find(re, cur)
b = cur.position()
if a == b:
cur.movePosition(QTextCursor.MoveOperation.NextCharacter)
cur = self.__editor.document().find(re, cur)
b = cur.position()
if (a == b):
break
a = b
self.__updateSelections(searchSelections)
def __updateSelections(self, searchSelections = None):
oldSelections = self.__editor.extraSelections()
for selection in self.__searchSelections:
for i in range(len(oldSelections) - 1, 0, -1):
if selection.cursor == oldSelections[i].cursor:
oldSelections.pop(i)
break
if searchSelections != None:
self.__searchSelections = searchSelections
self.__editor.setExtraSelections(oldSelections + self.__searchSelections)
def __columnForPosition(self, position):
return position - self.__editor.document().findBlock(position).position()
class StatusBar (QStatusBar):
def __init__(self):
super(StatusBar, self).__init__()
self.__statusMessageLabel = QLabel(self)
self.__statusDataLabel = QLabel(self)
self.__commandLine = QLineEdit(self)
self.addPermanentWidget(self.__statusMessageLabel, 1)
self.addPermanentWidget(self.__commandLine, 1)
self.addPermanentWidget(self.__statusDataLabel)
self.__commandLine.hide()
def setStatus(self, statusMessage, statusData, cursorPosition, cursorAnchor, eventFilter):
commandMode = cursorPosition != -1
self.__commandLine.setVisible(commandMode)
self.__statusMessageLabel.setVisible(not commandMode)
if commandMode:
self.__commandLine.installEventFilter(eventFilter)
self.__commandLine.setFocus()
self.__commandLine.setText(statusMessage)
self.__commandLine.setSelection(cursorPosition, cursorAnchor - cursorPosition)
else:
self.__statusMessageLabel.setText(statusMessage)
self.__statusDataLabel.setText(statusData)
././@PaxHeader 0000000 0000000 0000000 00000000026 00000000000 010213 x ustar 00 22 mtime=1642949280.0
ReText-7.2.3/ReText/highlighter.py 0000644 0001750 0001750 00000016250 00000000000 016430 0 ustar 00dmitry dmitry # This file is part of ReText
# Copyright: 2012-2021 Dmitry Shachnev
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see .
from ReText.editor import getColor
from enum import IntFlag, auto
import re
from PyQt5.QtCore import Qt
from PyQt5.QtGui import QFont, QSyntaxHighlighter, QTextCharFormat
reHtmlTags = re.compile('<[^<>@]*>')
reHtmlSymbols = re.compile(r'?\w+;')
reHtmlStrings = re.compile('"[^"<]*"(?=[^<]*>)')
reHtmlComments = re.compile('')
reAsterisks = re.compile(r'(?.+')
reReSTDirects = re.compile(r'\.\. [a-z]+::')
reReSTRoles = re.compile('(:[a-z-]+:)(`.+?`)')
reReSTLinks = re.compile('(`.+?<)(.+?)(>`__?)')
reReSTLinkRefs = re.compile(r'\.\. _`?(.*?)`?: (.*)')
reReSTFldLists = re.compile('^ *:(.*?):')
reTextileHdrs = re.compile(r'^h[1-6][()<>=]*\.\s.+')
reTextileQuot = re.compile(r'^bq\.\s.+')
reMkdCodeSpans = re.compile('`[^`]*`')
reMkdMathSpans = re.compile(r'\\[\(\[].*?\\[\)\]]')
reReSTCodeSpan = re.compile('``.+?``')
reWords = re.compile('[^_\\W]+')
reSpacesOnEnd = re.compile(r'\s+$')
class Formatter:
def __init__(self, funcs=None):
self._funcs = funcs or []
def __or__(self, other):
result = Formatter(self._funcs.copy())
if isinstance(other, Formatter):
result._funcs.extend(other._funcs)
elif isinstance(other, QFont.Weight):
result._funcs.append(lambda f: f.setFontWeight(other))
return result
def format(self, charFormat):
for func in self._funcs:
func(charFormat)
NF = Formatter()
ITAL = Formatter([lambda f: f.setFontItalic(True)])
UNDL = Formatter([lambda f: f.setFontUnderline(True)])
def FG(colorName):
func = lambda f: f.setForeground(getColor(colorName))
return Formatter([func])
def QString_length(text):
# In QString, surrogate pairs are represented using multiple QChars,
# so the length of QString is not always equal to the number of graphemes
# in it (which is the case with Python strings).
return sum(2 if ord(char) > 65535 else 1 for char in text)
class Markup(IntFlag):
Mkd = auto()
ReST = auto()
Textile = auto()
HTML = auto()
# Special value which means that no other markup is allowed inside this pattern
CodeSpan = auto()
docTypesMapping = {
'Markdown': Markup.Mkd,
'reStructuredText': Markup.ReST,
'Textile': Markup.Textile,
'html': Markup.HTML,
}
class ReTextHighlighter(QSyntaxHighlighter):
dictionary = None
docType = None
patterns = (
# regex, color, markups
(reMkdCodeSpans, FG('codeSpans'), Markup.Mkd | Markup.CodeSpan),
(reMkdMathSpans, FG('codeSpans'), Markup.Mkd | Markup.CodeSpan),
(reReSTCodeSpan, FG('codeSpans'), Markup.ReST | Markup.CodeSpan),
(reHtmlTags, FG('htmlTags') | QFont.Weight.Bold, Markup.Mkd | Markup.Textile | Markup.HTML),
(reHtmlSymbols, FG('htmlSymbols') | QFont.Weight.Bold, Markup.Mkd | Markup.HTML),
(reHtmlStrings, FG('htmlStrings') | QFont.Weight.Bold, Markup.Mkd | Markup.HTML),
(reHtmlComments, FG('htmlComments'), Markup.Mkd | Markup.HTML),
(reAsterisks, ITAL, Markup.Mkd | Markup.ReST),
(reUnderline, ITAL, Markup.Mkd | Markup.Textile),
(reDblAsterisks, NF | QFont.Weight.Bold, Markup.Mkd | Markup.ReST | Markup.Textile),
(reDblUnderline, NF | QFont.Weight.Bold, Markup.Mkd),
(reTrpAsterisks, ITAL | QFont.Weight.Bold, Markup.Mkd),
(reTrpUnderline, ITAL | QFont.Weight.Bold, Markup.Mkd),
(reMkdHeaders, NF | QFont.Weight.Black, Markup.Mkd),
(reMkdLinksImgs, FG('markdownLinks'), Markup.Mkd),
(reMkdLinkRefs, ITAL | UNDL, Markup.Mkd),
(reBlockQuotes, FG('blockquotes'), Markup.Mkd),
(reReSTDirects, FG('restDirectives') | QFont.Weight.Bold, Markup.ReST),
(reReSTRoles, NF, FG('restRoles') | QFont.Weight.Bold, FG('htmlStrings'), Markup.ReST),
(reTextileHdrs, NF | QFont.Weight.Black, Markup.Textile),
(reTextileQuot, FG('blockquotes'), Markup.Textile),
(reAsterisks, NF | QFont.Weight.Bold, Markup.Textile),
(reDblUnderline, ITAL, Markup.Textile),
(reReSTLinks, NF, NF, ITAL | UNDL, NF, Markup.ReST),
(reReSTLinkRefs, NF, FG('markdownLinks'), ITAL | UNDL, Markup.ReST),
(reReSTFldLists, NF, FG('restDirectives'), Markup.ReST),
)
def highlightBlock(self, text):
# Syntax highlighter
codeSpans = set()
if self.docType in docTypesMapping:
markup = docTypesMapping[self.docType]
for pattern, *formatters, markups in self.patterns:
if not (markup & markups):
continue
for match in pattern.finditer(text):
start, end = match.start(), match.end()
if markups & Markup.CodeSpan:
codeSpans.add((start, end))
elif any(start < codeEnd and end > codeStart
for codeStart, codeEnd in codeSpans):
# Ignore any syntax if its match intersects with code spans.
# See https://github.com/retext-project/retext/issues/529
continue
for i, formatter in enumerate(formatters):
charFormat = QTextCharFormat()
formatter.format(charFormat)
self.setFormat(QString_length(text[:match.start(i)]),
QString_length(match.group(i)),
charFormat)
for match in reSpacesOnEnd.finditer(text):
charFormat = QTextCharFormat()
charFormat.setBackground(getColor('whitespaceOnEnd'))
self.setFormat(QString_length(text[:match.start()]),
QString_length(match.group(0)),
charFormat)
# Spell checker
if self.dictionary:
charFormat = QTextCharFormat()
charFormat.setUnderlineColor(Qt.GlobalColor.red)
charFormat.setUnderlineStyle(QTextCharFormat.UnderlineStyle.SpellCheckUnderline)
for match in reWords.finditer(text):
finalFormat = QTextCharFormat()
finalFormat.merge(charFormat)
finalFormat.merge(self.format(match.start()))
if not self.dictionary.check(match.group(0)):
self.setFormat(QString_length(text[:match.start()]),
QString_length(match.group(0)),
finalFormat)
././@PaxHeader 0000000 0000000 0000000 00000000026 00000000000 010213 x ustar 00 22 mtime=1630777591.0
ReText-7.2.3/ReText/icontheme.py 0000644 0001750 0001750 00000003212 00000000000 016077 0 ustar 00dmitry dmitry # This file is part of ReText
# Copyright: 2015-2016 Dmitry Shachnev
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see .
def get_from_xsettings():
from ReText.xsettings import get_xsettings, XSettingsError
try:
xsettings = get_xsettings()
except XSettingsError:
return
if b'Net/IconThemeName' in xsettings:
return xsettings[b'Net/IconThemeName'].decode()
if b'Net/FallbackIconTheme' in xsettings:
return xsettings[b'Net/FallbackIconTheme'].decode()
def get_from_gsettings():
try:
from gi.repository import Gio
except ImportError:
return
schema = 'org.gnome.desktop.interface'
if schema in Gio.Settings.list_schemas():
settings = Gio.Settings.new(schema)
return settings.get_string('icon-theme')
def get_from_gtk():
try:
from gi import require_version
require_version('Gtk', '3.0')
from gi.repository import Gtk
except (ImportError, ValueError):
return
settings = Gtk.Settings.get_default()
return settings.get_property('gtk-icon-theme-name')
def get_icon_theme():
return (get_from_xsettings()
or get_from_gsettings()
or get_from_gtk())
././@PaxHeader 0000000 0000000 0000000 00000000026 00000000000 010213 x ustar 00 22 mtime=1630777591.0
ReText-7.2.3/ReText/mdx_posmap.py 0000644 0001750 0001750 00000010423 00000000000 016275 0 ustar 00dmitry dmitry '''
Position Map Extension for Python-Markdown
==========================================
This extension adds data-posmap attributes to the generated HTML elements that
can be used to relate HTML elements to the corresponding lines in the markdown
input file.
Note: the line number stored in the data-posmap attribute corresponds to the
empty line *after* the markdown block that the HTML was generated from.
Copyright 2016 [Maurice van der Pot](griffon26@kfk4ever.com)
License: [BSD](http://www.opensource.org/licenses/bsd-license.php)
'''
from __future__ import unicode_literals
import re
from xml.etree.ElementTree import SubElement
from markdown.blockprocessors import BlockProcessor
from markdown.extensions import Extension
from markdown.extensions.codehilite import CodeHilite
from markdown.preprocessors import Preprocessor
from markdown.util import HTML_PLACEHOLDER_RE
try:
from pymdownx.highlight import Highlight
except ImportError:
Highlight = None
POSMAP_MARKER_RE = re.compile(r'__posmapmarker__\d+\n\n')
class PosMapExtension(Extension):
""" Position Map Extension for Python-Markdown. """
def extendMarkdown(self, md):
""" Insert the PosMapExtension blockprocessor before any other
extensions to make sure our own markers, inserted by the
preprocessor, are removed before any other extensions get confused
by them.
"""
md.preprocessors.register(PosMapMarkPreprocessor(md), 'posmap_mark', 50)
md.preprocessors.register(PosMapCleanPreprocessor(md), 'posmap_clean', 5)
md.parser.blockprocessors.register(PosMapBlockProcessor(md.parser), 'posmap', 150)
# Monkey patch CodeHilite constructor to remove the posmap markers from
# text before highlighting it
orig_codehilite_init = CodeHilite.__init__
def new_codehilite_init(self, src=None, *args, **kwargs):
src = POSMAP_MARKER_RE.sub('', src)
orig_codehilite_init(self, src=src, *args, **kwargs)
CodeHilite.__init__ = new_codehilite_init
# Same for PyMdown Extensions if it is available
if Highlight is not None:
orig_highlight_highlight = Highlight.highlight
def new_highlight_highlight(self, src, *args, **kwargs):
src = POSMAP_MARKER_RE.sub('', src)
return orig_highlight_highlight(self, src, *args, **kwargs)
Highlight.highlight = new_highlight_highlight
class PosMapMarkPreprocessor(Preprocessor):
""" PosMapMarkPreprocessor - insert __posmapmarker__linenr entries at each empty line """
def run(self, lines):
new_text = []
for i, line in enumerate(lines):
new_text.append(line)
if line == '':
new_text.append('__posmapmarker__%d' % i)
new_text.append('')
return new_text
class PosMapCleanPreprocessor(Preprocessor):
""" PosMapCleanPreprocessor - remove __posmapmarker__linenr entries that
accidentally ended up in the htmlStash. This could have happened
because they were inside html tags or a fenced code block.
"""
def run(self, lines):
for i in range(self.md.htmlStash.html_counter):
block = self.md.htmlStash.rawHtmlBlocks[i]
block = re.sub(POSMAP_MARKER_RE, '', block)
self.md.htmlStash.rawHtmlBlocks[i] = block
return lines
class PosMapBlockProcessor(BlockProcessor):
""" PosMapBlockProcessor - remove each marker and add a data-posmap
attribute to the previous HTML element
"""
def test(self, parent, block):
return block.startswith('__posmapmarker__')
def run(self, parent, blocks):
block = blocks.pop(0)
line_nr = block.split('__')[2]
last_child = self.lastChild(parent)
if last_child != None:
# Avoid setting the attribute on HTML placeholders, because it
# would interfere with later replacement with literal HTML
# fragments. In this case just add an empty
with the attribute.
if last_child.text and re.match(HTML_PLACEHOLDER_RE, last_child.text):
last_child = SubElement(parent, 'p')
last_child.set('data-posmap', line_nr)
def makeExtension(*args, **kwargs):
return PosMapExtension(*args, **kwargs)
././@PaxHeader 0000000 0000000 0000000 00000000026 00000000000 010213 x ustar 00 22 mtime=1642949280.0
ReText-7.2.3/ReText/preview.py 0000644 0001750 0001750 00000011053 00000000000 015607 0 ustar 00dmitry dmitry # vim: ts=8:sts=8:sw=8:noexpandtab
#
# This file is part of ReText
# Copyright: 2017-2021 Dmitry Shachnev
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see .
from os.path import exists
import time
from PyQt5.QtCore import QDir, QUrl, Qt
from PyQt5.QtGui import QDesktopServices, QGuiApplication, QTextCursor, QTextDocument
from PyQt5.QtWidgets import QTextBrowser
from ReText import globalSettings
class ReTextPreview(QTextBrowser):
def __init__(self, tab):
QTextBrowser.__init__(self)
self.tab = tab
# if set to True, links to other files will unsuccessfully be opened as anchors
self.setOpenLinks(False)
self.anchorClicked.connect(self.openInternal)
self.lastRenderTime = 0
self.distToBottom = None
self.verticalScrollBar().rangeChanged.connect(self.updateScrollPosition)
def disconnectExternalSignals(self):
pass
def openInternal(self, link):
url = link.url()
if url.startswith('#'):
self.scrollToAnchor(url[1:])
return
elif link.isRelative():
fileToOpen = QDir.current().filePath(url)
else:
fileToOpen = link.toLocalFile() if link.isLocalFile() else None
if fileToOpen is not None:
if exists(fileToOpen):
link = QUrl.fromLocalFile(fileToOpen)
if globalSettings.handleWebLinks and fileToOpen.endswith('.html'):
self.setSource(link)
return
# This is outside the "if exists" block because we can prompt for
# creating the file
if self.tab.openSourceFile(fileToOpen):
return
QDesktopServices.openUrl(link)
def findText(self, text, flags, wrap=False):
cursor = self.textCursor()
if wrap and flags & QTextDocument.FindFlag.FindBackward:
cursor.movePosition(QTextCursor.MoveOperation.End)
elif wrap:
cursor.movePosition(QTextCursor.MoveOperation.Start)
newCursor = self.document().find(text, cursor, flags)
if not newCursor.isNull():
self.setTextCursor(newCursor)
return True
if not wrap:
return self.findText(text, flags, wrap=True)
return False
def updateScrollPosition(self, minimum, maximum):
"""Called when vertical scroll bar range changes.
If this happened during preview rendering (less than 0.5s since it
was started), set the position such that distance to bottom is the
same as before refresh.
"""
timeSinceRender = time.time() - self.lastRenderTime
if timeSinceRender < 0.5 and self.distToBottom is not None and maximum:
newValue = maximum - self.distToBottom
if newValue >= minimum:
self.verticalScrollBar().setValue(newValue)
class ReTextWebPreview:
"""This is a common class shared between WebKit and WebEngine
based previews."""
def __init__(self, editBox):
self.editBox = editBox
self.settings().setDefaultTextEncoding('utf-8')
# Events relevant to sync scrolling
self.editBox.cursorPositionChanged.connect(self._handleCursorPositionChanged)
self.editBox.verticalScrollBar().valueChanged.connect(self.syncscroll.handleEditorScrolled)
self.editBox.resized.connect(self._handleEditorResized)
# Scroll the preview when the mouse wheel is used to scroll
# beyond the beginning/end of the editor
self.editBox.scrollLimitReached.connect(self._handleWheelEvent)
def disconnectExternalSignals(self):
self.editBox.cursorPositionChanged.disconnect(self._handleCursorPositionChanged)
self.editBox.verticalScrollBar().valueChanged.disconnect(self.syncscroll.handleEditorScrolled)
self.editBox.resized.disconnect(self._handleEditorResized)
self.editBox.scrollLimitReached.disconnect(self._handleWheelEvent)
def _handleCursorPositionChanged(self):
editorCursorPosition = self.editBox.verticalScrollBar().value() + \
self.editBox.cursorRect().top()
self.syncscroll.handleCursorPositionChanged(editorCursorPosition)
def _handleEditorResized(self, rect):
self.syncscroll.handleEditorResized(rect.height())
def wheelEvent(self, event):
if QGuiApplication.keyboardModifiers() == Qt.KeyboardModifier.ControlModifier:
zoomFactor = self.zoomFactor()
zoomFactor *= 1.001 ** event.angleDelta().y()
self.setZoomFactor(zoomFactor)
return super().wheelEvent(event)
././@PaxHeader 0000000 0000000 0000000 00000000026 00000000000 010213 x ustar 00 22 mtime=1642950213.0
ReText-7.2.3/ReText/syncscroll.py 0000644 0001750 0001750 00000015523 00000000000 016327 0 ustar 00dmitry dmitry # This file is part of ReText
# Copyright: 2016 Maurice van der Pot
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see .
from PyQt5.QtCore import QPoint
class SyncScroll:
def __init__(self, previewFrame,
editorPositionToSourceLineFunc,
sourceLineToEditorPositionFunc):
self.posmap = {}
self.frame = previewFrame
self.editorPositionToSourceLine = editorPositionToSourceLineFunc
self.sourceLineToEditorPosition = sourceLineToEditorPositionFunc
self.previewPositionBeforeLoad = QPoint()
self.contentIsLoading = False
self.editorViewportHeight = 0
self.editorViewportOffset = 0
self.editorCursorPosition = 0
self.frame.contentsSizeChanged.connect(self._handlePreviewResized)
self.frame.loadStarted.connect(self._handleLoadStarted)
self.frame.loadFinished.connect(self._handleLoadFinished)
def isActive(self):
return bool(self.posmap)
def handleEditorResized(self, editorViewportHeight):
self.editorViewportHeight = editorViewportHeight
self._updatePreviewScrollPosition()
def handleEditorScrolled(self, editorViewportOffset):
self.editorViewportOffset = editorViewportOffset
return self._updatePreviewScrollPosition()
def handleCursorPositionChanged(self, editorCursorPosition):
self.editorCursorPosition = editorCursorPosition
return self._updatePreviewScrollPosition()
def _handleLoadStarted(self):
# Store the current scroll position so it can be restored when the new
# content is presented
self.previewPositionBeforeLoad = self.frame.scrollPosition()
self.contentIsLoading = True
def _handleLoadFinished(self):
self.frame.setScrollPosition(self.previewPositionBeforeLoad)
self.contentIsLoading = False
self._recalculatePositionMap()
def _handlePreviewResized(self):
self._recalculatePositionMap()
self._updatePreviewScrollPosition()
if not self.posmap and self.frame.scrollPosition().y() == 0:
self.frame.setScrollPosition(self.previewPositionBeforeLoad)
def _linearScale(self, fromValue, fromMin, fromMax, toMin, toMax):
fromRange = fromMax - fromMin
toRange = toMax - toMin
toValue = toMin
if fromRange:
toValue += ((fromValue - fromMin) * toRange) / float(fromRange)
return toValue
def _updatePreviewScrollPosition(self):
if not self.posmap:
# Loading new content resets the scroll position to the top. If we
# don't have a posmap to calculate the new best position, then
# restore the position stored at the beginning of the load.
if self.contentIsLoading:
self.frame.setScrollPosition(self.previewPositionBeforeLoad)
return
textedit_pixel_to_scroll_to = self.editorCursorPosition
if textedit_pixel_to_scroll_to < self.editorViewportOffset:
textedit_pixel_to_scroll_to = self.editorViewportOffset
last_viewport_pixel = self.editorViewportOffset + self.editorViewportHeight
if textedit_pixel_to_scroll_to > last_viewport_pixel:
textedit_pixel_to_scroll_to = last_viewport_pixel
line_to_scroll_to = self.editorPositionToSourceLine(textedit_pixel_to_scroll_to)
# Do a binary search through the posmap to find the nearest line above
# and below the line to scroll to for which the rendered position is
# known.
posmap_lines = [0] + sorted(self.posmap.keys())
min_index = 0
max_index = len(posmap_lines) - 1
while max_index - min_index > 1:
current_index = int((min_index + max_index) / 2)
if posmap_lines[current_index] > line_to_scroll_to:
max_index = current_index
else:
min_index = current_index
# number of nearest line above and below for which we have a position
min_line = posmap_lines[min_index]
max_line = posmap_lines[max_index]
min_textedit_pos = self.sourceLineToEditorPosition(min_line)
max_textedit_pos = self.sourceLineToEditorPosition(max_line)
# rendered pixel position of nearest line above and below
min_preview_pos = self.posmap[min_line]
max_preview_pos = self.posmap[max_line]
# calculate rendered pixel position of line corresponding to cursor
# (0 == top of document)
preview_pixel_to_scroll_to = self._linearScale(textedit_pixel_to_scroll_to,
min_textedit_pos, max_textedit_pos,
min_preview_pos, max_preview_pos)
distance_to_top_of_viewport = textedit_pixel_to_scroll_to - self.editorViewportOffset
preview_scroll_offset = preview_pixel_to_scroll_to - distance_to_top_of_viewport
pos = self.frame.scrollPosition()
# scrollPosition() returns QPoint for WebKit and QPointF for WebEngine
if isinstance(pos, QPoint):
preview_scroll_offset = int(preview_scroll_offset)
pos.setY(preview_scroll_offset)
self.frame.setScrollPosition(pos)
def _setPositionMap(self, posmap):
self.posmap = posmap
if posmap:
self.posmap[0] = 0
def _recalculatePositionMap(self):
if hasattr(self.frame, 'getPositionMap'):
# For WebEngine the update has to be asynchronous
self.frame.getPositionMap(self._setPositionMap)
return
# Create a list of input line positions mapped to vertical pixel positions in the preview
self.posmap = {}
elements = self.frame.findAllElements('[data-posmap]')
if elements:
# If there are posmap attributes, then build a posmap
# dictionary from them that will be used whenever the
# cursor is moved.
for el in elements:
value = el.attribute('data-posmap', 'invalid')
bottom = el.geometry().bottom()
# Ignore data-posmap entries that do not have integer values
try:
self.posmap[int(value)] = bottom
except ValueError:
pass
self.posmap[0] = 0
././@PaxHeader 0000000 0000000 0000000 00000000026 00000000000 010213 x ustar 00 22 mtime=1642949280.0
ReText-7.2.3/ReText/tab.py 0000644 0001750 0001750 00000047061 00000000000 014704 0 ustar 00dmitry dmitry # vim: ts=8:sts=8:sw=8:noexpandtab
#
# This file is part of ReText
# Copyright: 2015-2021 Dmitry Shachnev
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see .
from os.path import exists, splitext
import time
from markups import get_markup_for_file_name, find_markup_class_by_name
from markups.common import MODULE_HOME_PAGE
from ReText import app_version, globalSettings, converterprocess
from ReText.editor import ReTextEdit
from ReText.highlighter import ReTextHighlighter
from ReText.preview import ReTextPreview
try:
import enchant
except ImportError:
enchant = None
from PyQt5.QtCore import pyqtSignal, Qt, QDir, QFile, QFileInfo, QPoint, QTextStream, QTimer, QUrl
from PyQt5.QtGui import QPalette, QTextCursor, QTextDocument
from PyQt5.QtWidgets import QApplication, QTextEdit, QSplitter, QMessageBox
try:
from ReText.webkitpreview import ReTextWebKitPreview
except ImportError:
ReTextWebKitPreview = None
try:
from ReText.webenginepreview import ReTextWebEnginePreview
except ImportError:
ReTextWebEnginePreview = None
PreviewDisabled, PreviewLive, PreviewNormal = range(3)
class ReTextTab(QSplitter):
fileNameChanged = pyqtSignal()
modificationStateChanged = pyqtSignal()
activeMarkupChanged = pyqtSignal()
# Make _fileName a read-only property to make sure that any
# modification happens through the proper functions. These functions
# will make sure that the fileNameChanged signal is emitted when
# applicable.
@property
def fileName(self):
return self._fileName
def __init__(self, parent, fileName, previewState=PreviewDisabled):
super().__init__(Qt.Orientation.Horizontal, parent=parent)
self.p = parent
self._fileName = fileName
self.editBox = ReTextEdit(self)
self.previewBox = self.createPreviewBox(self.editBox)
self.activeMarkupClass = None
self.markup = None
self.converted = None
self.previewState = previewState
self.previewOutdated = False
self.conversionPending = False
self.cssFileExists = False
self.converterProcess = converterprocess.ConverterProcess()
self.converterProcess.conversionDone.connect(self.updatePreviewBox)
textDocument = self.editBox.document()
self.highlighter = ReTextHighlighter(textDocument)
if enchant is not None and parent.actionEnableSC.isChecked():
self.highlighter.dictionary = enchant.Dict(parent.sl or None)
# Rehighlighting is tied to the change in markup class that
# happens at the end of this function
self.editBox.textChanged.connect(self.triggerPreviewUpdate)
self.editBox.undoAvailable.connect(parent.actionUndo.setEnabled)
self.editBox.redoAvailable.connect(parent.actionRedo.setEnabled)
self.editBox.copyAvailable.connect(parent.enableCopy)
# Give both boxes a minimum size so the minimumSizeHint will be
# ignored when splitter.setSizes is called below
for widget in self.editBox, self.previewBox:
widget.setMinimumWidth(125)
self.addWidget(widget)
self.setSizes((50, 50))
self.setChildrenCollapsible(False)
textDocument.modificationChanged.connect(self.handleModificationChanged)
self.updateActiveMarkupClass()
def handleModificationChanged(self):
self.modificationStateChanged.emit()
def createPreviewBox(self, editBox):
# Use closures to avoid a hard reference from ReTextWebKitPreview
# to self, which would keep the tab and its resources alive
# even after other references to it have disappeared.
def editorPositionToSourceLine(editorPosition):
viewportPosition = editorPosition - editBox.verticalScrollBar().value()
sourceLine = editBox.cursorForPosition(QPoint(0,viewportPosition)).blockNumber()
return sourceLine
def sourceLineToEditorPosition(sourceLine):
doc = editBox.document()
block = doc.findBlockByNumber(sourceLine)
rect = doc.documentLayout().blockBoundingRect(block)
return rect.top()
if ReTextWebKitPreview and globalSettings.useWebKit:
preview = ReTextWebKitPreview(self,
editorPositionToSourceLine,
sourceLineToEditorPosition)
elif ReTextWebEnginePreview and globalSettings.useWebEngine:
preview = ReTextWebEnginePreview(self,
editorPositionToSourceLine,
sourceLineToEditorPosition)
else:
preview = ReTextPreview(self)
return preview
def getActiveMarkupClass(self):
'''
Return the currently active markup class for this tab.
No objects should be created of this class, it should
only be used to retrieve markup class specific information.
'''
return self.activeMarkupClass
def updateActiveMarkupClass(self):
'''
Update the active markup class based on the default class and
the current filename. If the active markup class changes, the
highlighter is rerun on the input text, the markup object of
this tab is replaced with one of the new class and the
activeMarkupChanged signal is emitted.
'''
previousMarkupClass = self.activeMarkupClass
self.activeMarkupClass = find_markup_class_by_name(globalSettings.defaultMarkup)
if self._fileName:
markupClass = get_markup_for_file_name(
self._fileName, return_class=True)
if markupClass:
self.activeMarkupClass = markupClass
if self.activeMarkupClass != previousMarkupClass:
self.highlighter.docType = self.activeMarkupClass.name if self.activeMarkupClass else None
self.highlighter.rehighlight()
self.activeMarkupChanged.emit()
self.triggerPreviewUpdate()
def getDocumentTitleFromConverted(self, converted):
if converted:
try:
return converted.get_document_title()
except Exception:
self.p.printError()
return self.getBaseName()
def getBaseName(self):
if self._fileName:
fileinfo = QFileInfo(self._fileName)
basename = fileinfo.completeBaseName()
return (basename if basename else fileinfo.fileName())
return self.tr("New document")
def getHtmlFromConverted(self, converted, includeStyleSheet=True, webenv=False):
if converted is None:
markupClass = self.getActiveMarkupClass()
errMsg = self.tr('Could not parse file contents, check if '
'you have the necessary module '
'installed!')
try:
errMsg %= markupClass.attributes[MODULE_HOME_PAGE]
except (AttributeError, KeyError):
# Remove the link if markupClass doesn't have the needed attribute
errMsg = errMsg.replace('', '').replace('', '')
return '
%s
' % errMsg
headers = ''
if includeStyleSheet and self.p.ss is not None:
headers += '\n'
elif includeStyleSheet:
style = 'td, th { border: 1px solid #c3c3c3; padding: 0 3px 0 3px; }\n'
style += 'table { border-collapse: collapse; }\n'
style += 'img { max-width: 100%; }\n'
# QTextDocument seems to use media=screen even for printing
if not isinstance(self.previewBox, QTextEdit) and not webenv:
# https://github.com/retext-project/retext/pull/187
palette = QApplication.palette()
fgColor = palette.color(QPalette.ColorRole.Text).name()
bgColor = palette.color(QPalette.ColorRole.Base).name()
linkColor = palette.color(QPalette.ColorRole.Link).name()
visitedLinkColor = palette.color(QPalette.ColorRole.LinkVisited).name()
style += ('@media screen {\n'
f' html {{ color: {fgColor}; background-color: {bgColor}; }}\n'
f' a, a * {{ color: {linkColor}; }}\n'
f' a:visited, a:visited * {{ color: {visitedLinkColor}; }}\n'
'}\n')
# https://github.com/retext-project/retext/issues/408
style += '@media print { html { background-color: white; } }\n'
headers += '\n'
baseName = self.getBaseName()
if self.cssFileExists:
headers += ('\n'
% baseName)
headers += ('\n' % app_version)
return converted.get_whole_html(
custom_headers=headers, include_stylesheet=includeStyleSheet,
fallback_title=baseName, webenv=webenv)
def getDocumentForExport(self, includeStyleSheet=True, webenv=False):
markupClass = self.getActiveMarkupClass()
if markupClass and markupClass.available():
exportMarkup = markupClass(filename=self._fileName)
text = self.editBox.toPlainText()
converted = exportMarkup.convert(text)
else:
converted = None
return (self.getDocumentTitleFromConverted(converted),
self.getHtmlFromConverted(converted, includeStyleSheet=includeStyleSheet, webenv=webenv),
self.previewBox)
def updatePreviewBox(self):
self.conversionPending = False
try:
self.converted = self.converterProcess.get_result()
except converterprocess.MarkupNotAvailableError:
self.converted = None
except converterprocess.ConversionError:
return self.p.printError()
if isinstance(self.previewBox, QTextEdit):
scrollbar = self.previewBox.verticalScrollBar()
scrollbarValue = scrollbar.value()
# If scrollbar was not on top, save its distance to bottom so that
# it will be restored in previewBox.updateScrollPosition() later.
if scrollbarValue:
self.previewBox.distToBottom = scrollbar.maximum() - scrollbarValue
else:
self.previewBox.distToBottom = None
try:
html = self.getHtmlFromConverted(self.converted)
except Exception:
return self.p.printError()
if isinstance(self.previewBox, QTextEdit):
self.previewBox.lastRenderTime = time.time()
self.previewBox.setHtml(html)
self.previewBox.document().setDefaultFont(globalSettings.font)
self.previewBox.updateScrollPosition(scrollbar.minimum(),
scrollbar.maximum())
else:
self.previewBox.updateFontSettings()
# Always provide a baseUrl otherwise QWebView will
# refuse to show images or other external objects
if self._fileName:
baseUrl = QUrl.fromLocalFile(self._fileName)
else:
baseUrl = QUrl.fromLocalFile(QDir.currentPath())
self.previewBox.setHtml(html, baseUrl)
if self.previewOutdated:
self.triggerPreviewUpdate()
def triggerPreviewUpdate(self):
self.previewOutdated = True
if self.previewState == PreviewDisabled:
return
if not self.conversionPending:
self.conversionPending = True
QTimer.singleShot(500, self.startPendingConversion)
def startPendingConversion(self):
self.previewOutdated = False
requested_extensions = ['ReText.mdx_posmap'] if globalSettings.syncScroll else []
self.converterProcess.start_conversion(self.getActiveMarkupClass().name,
self.fileName,
requested_extensions,
self.editBox.toPlainText(),
QDir.currentPath())
def updateBoxesVisibility(self):
self.editBox.setVisible(self.previewState < PreviewNormal)
self.previewBox.setVisible(self.previewState > PreviewDisabled)
def rebuildPreviewBox(self):
self.previewBox.disconnectExternalSignals()
self.previewBox.setParent(None)
self.previewBox.deleteLater()
self.previewBox = self.createPreviewBox(self.editBox)
self.previewBox.setMinimumWidth(125)
self.addWidget(self.previewBox)
self.setSizes((50, 50))
self.triggerPreviewUpdate()
self.updateBoxesVisibility()
def detectFileEncoding(self, fileName):
'''
Detect content encoding of specific file.
It will return None if it can't determine the encoding.
'''
try:
import chardet
except ImportError:
return
with open(fileName, 'rb') as inputFile:
raw = inputFile.read(2048)
result = chardet.detect(raw)
if result['confidence'] > 0.9:
if result['encoding'].lower() in ('ascii', 'utf-8-sig'):
# UTF-8 files can be falsely detected as ASCII files if they
# don't contain non-ASCII characters in first 2048 bytes.
# We map ASCII to UTF-8 to avoid such situations.
# Also map UTF-8-SIG to UTF-8 because Qt does not understand it.
return 'utf-8'
return result['encoding']
def readTextFromFile(self, fileName=None, encoding=None):
previousFileName = self._fileName
if fileName:
self._fileName = fileName
# Only try to detect encoding if it is not specified
if encoding is None and globalSettings.detectEncoding:
encoding = self.detectFileEncoding(self._fileName)
# TODO: why do we open the file twice: for detecting encoding
# and for actual read? Can we open it just once?
openfile = QFile(self._fileName)
openfile.open(QFile.OpenModeFlag.ReadOnly)
stream = QTextStream(openfile)
encoding = encoding or globalSettings.defaultCodec
if encoding:
stream.setCodec(encoding)
# If encoding is specified or detected, we should save the file with
# the same encoding
self.editBox.document().setProperty("encoding", encoding)
text = stream.readAll()
openfile.close()
if previousFileName != self._fileName:
self.updateActiveMarkupClass()
self.editBox.setPlainText(text)
self.editBox.document().setModified(False)
self.handleModificationChanged()
cssFileName = self.getBaseName() + '.css'
self.cssFileExists = QFile.exists(cssFileName)
if previousFileName != self._fileName:
self.fileNameChanged.emit()
def writeTextToFile(self, fileName=None):
# Just writes the text to file, without any changes to tab object
# Used directly for e.g. export extensions
# Get text from the cursor to avoid tweaking special characters,
# see https://bugreports.qt.io/browse/QTBUG-57552 and
# https://github.com/retext-project/retext/issues/216
cursor = self.editBox.textCursor()
cursor.select(QTextCursor.SelectionType.Document)
text = cursor.selectedText().replace('\u2029', '\n')
savefile = QFile(fileName or self._fileName)
result = savefile.open(QFile.OpenModeFlag.WriteOnly)
if result:
savestream = QTextStream(savefile)
# Save the file with original encoding
encoding = self.editBox.document().property("encoding")
encoding = encoding or globalSettings.defaultCodec
if encoding is not None:
savestream.setCodec(encoding)
savestream << text
savefile.close()
return result
def saveTextToFile(self, fileName=None):
# Sets fileName as tab fileName and writes the text to that file
if self._fileName:
self.p.fileSystemWatcher.removePath(self._fileName)
result = self.writeTextToFile(fileName)
if result:
self.editBox.document().setModified(False)
self.p.fileSystemWatcher.addPath(fileName or self._fileName)
if fileName and self._fileName != fileName:
self._fileName = fileName
self.updateActiveMarkupClass()
self.fileNameChanged.emit()
return result
def goToLine(self,line):
block = self.editBox.document().findBlockByLineNumber(line)
if block.isValid():
newCursor = QTextCursor(block)
self.editBox.setTextCursor(newCursor)
def find(self, text, flags, replaceText=None, wrap=False):
if self.previewState == PreviewNormal and replaceText is None:
return self.previewBox.findText(text, flags)
cursor = self.editBox.textCursor()
if wrap and flags & QTextDocument.FindFlag.FindBackward:
cursor.movePosition(QTextCursor.MoveOperation.End)
elif wrap:
cursor.movePosition(QTextCursor.MoveOperation.Start)
if replaceText is not None and cursor.selectedText() == text:
newCursor = cursor
else:
newCursor = self.editBox.document().find(text, cursor, flags)
if not newCursor.isNull():
if replaceText is not None:
newCursor.insertText(replaceText)
newCursor.movePosition(QTextCursor.MoveOperation.Left, QTextCursor.MoveMode.MoveAnchor, len(replaceText))
newCursor.movePosition(QTextCursor.MoveOperation.Right, QTextCursor.MoveMode.KeepAnchor, len(replaceText))
self.editBox.setTextCursor(newCursor)
if self.editBox.cursorRect().bottom() >= self.editBox.height() - 3:
scrollValue = self.editBox.verticalScrollBar().value()
areaHeight = self.editBox.fontMetrics().height()
self.editBox.verticalScrollBar().setValue(scrollValue + areaHeight)
return True
if not wrap:
return self.find(text, flags, replaceText, True)
return False
def replaceAll(self, text, replaceText):
cursor = self.editBox.textCursor()
cursor.beginEditBlock()
cursor.movePosition(QTextCursor.MoveOperation.Start)
flags = QTextDocument.FindFlags()
cursor = lastCursor = self.editBox.document().find(text, cursor, flags)
while not cursor.isNull():
cursor.insertText(replaceText)
lastCursor = cursor
cursor = self.editBox.document().find(text, cursor, flags)
if not lastCursor.isNull():
lastCursor.movePosition(QTextCursor.MoveOperation.Left, QTextCursor.MoveMode.MoveAnchor, len(replaceText))
lastCursor.movePosition(QTextCursor.MoveOperation.Right, QTextCursor.MoveMode.KeepAnchor, len(replaceText))
self.editBox.setTextCursor(lastCursor)
self.editBox.textCursor().endEditBlock()
return not lastCursor.isNull()
def openSourceFile(self, linkPath):
"""Finds and opens the source file for link target fileToOpen.
When links like [test](test) are clicked, the file test.md is opened.
It has to be located next to the current opened file.
Relative paths like [test](../test) or [test](folder/test) are also possible.
"""
fileToOpen = self.resolveSourceFile(linkPath)
if exists(fileToOpen) and get_markup_for_file_name(fileToOpen, return_class=True):
self.p.openFileWrapper(fileToOpen)
return fileToOpen
if get_markup_for_file_name(fileToOpen, return_class=True):
if not QFile.exists(fileToOpen) and QFileInfo(fileToOpen).dir().exists():
if self.promptFileCreation(fileToOpen):
self.p.openFileWrapper(fileToOpen)
return fileToOpen
def promptFileCreation(self, fileToCreate):
"""
Prompt user if a file should be created for the clicked link,
and try to create it. Return True on success.
"""
buttonReply = QMessageBox.question(self, self.tr('Create missing file?'),
self.tr("The file '%s' does not exist.\n\nDo you want to create it?") % fileToCreate,
QMessageBox.StandardButton.Yes | QMessageBox.StandardButton.No,
QMessageBox.StandardButton.No)
if buttonReply == QMessageBox.StandardButton.Yes:
return self.createFile(fileToCreate)
elif buttonReply == QMessageBox.StandardButton.No:
return False
def resolveSourceFile(self, linkPath):
"""
Finds the actual path of the file to open in a new tab.
When the link has no extension, eg: [Test](test), the extension of the current file is assumed
(eg test.md for a markdown file).
When the link is an html file eg: [Test](test.html), the extension of the current file is assumed
(eg test.md for a markdown file).
Relative paths like [test](../test) or [test](folder/test) are also possible.
"""
basename, ext = splitext(linkPath)
if self.fileName:
currentExt = splitext(self.fileName)[1]
if ext in ('.html', '') and (exists(basename+currentExt) or not exists(linkPath)):
ext = currentExt
return basename+ext
def createFile(self, fileToCreate):
"""Try to create file, return True if successful"""
try:
# Create file:
open(fileToCreate, 'x').close()
return True
except OSError as err:
QMessageBox.warning(self, self.tr("File could not be created"),
self.tr("Could not create file '%s': %s") % (fileToCreate, err))
return False
././@PaxHeader 0000000 0000000 0000000 00000000026 00000000000 010213 x ustar 00 22 mtime=1633978476.0
ReText-7.2.3/ReText/tabledialog.py 0000644 0001750 0001750 00000006277 00000000000 016411 0 ustar 00dmitry dmitry # This file is part of ReText
# Copyright: 2018 Changhee Kim, 2018-2021 Dmitry Shachnev
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see .
from markups import ReStructuredTextMarkup
from PyQt5.QtCore import Qt
from PyQt5.QtWidgets import QDialog, QDialogButtonBox, QGridLayout, QLabel, \
QSpinBox
class InsertTableDialog(QDialog):
def __init__(self, parent):
QDialog.__init__(self, parent)
self.parent = parent
self.setWindowTitle(self.tr('Insert table'))
buttonBox = QDialogButtonBox(self)
buttonBox.setStandardButtons(QDialogButtonBox.StandardButton.Ok |
QDialogButtonBox.StandardButton.Cancel)
buttonBox.accepted.connect(self.makeTable)
buttonBox.rejected.connect(self.close)
layout = QGridLayout(self)
rowsLabel = QLabel(self.tr('Number of rows') + ':', self)
columnsLabel = QLabel(self.tr('Number of columns') + ':', self)
self.rowsSpinBox = QSpinBox(self)
self.columnsSpinBox = QSpinBox(self)
self.rowsSpinBox.setRange(1, 10)
self.columnsSpinBox.setRange(1, 10)
self.rowsSpinBox.setValue(3)
self.columnsSpinBox.setValue(3)
layout.addWidget(rowsLabel, 0, 0)
layout.addWidget(self.rowsSpinBox, 0, 1, Qt.AlignmentFlag.AlignRight)
layout.addWidget(columnsLabel, 1, 0)
layout.addWidget(self.columnsSpinBox, 1, 1, Qt.AlignmentFlag.AlignRight)
layout.addWidget(buttonBox, 2, 0, 1, 2)
def makeTable(self):
rowsCount = self.rowsSpinBox.value()
columnsCount = self.columnsSpinBox.value() + 1
tab = self.parent.currentTab
cursor = tab.editBox.textCursor()
tableCode = '' if cursor.atBlockStart() else '\n\n'
if tab.activeMarkupClass == ReStructuredTextMarkup:
# Insert reStructuredText grid table
tableCode += '-----'.join('+' * columnsCount) + '\n'
tableCode += ' '.join('|' * columnsCount) + '\n'
tableCode += '====='.join('+' * columnsCount) + '\n'
tableCode += (' '.join('|' * columnsCount) + '\n' +
'-----'.join('+' * columnsCount) + '\n') * rowsCount
else:
# Insert Markdown table
tableCode += ' '.join('|' * columnsCount) + '\n'
tableCode += '-----'.join('|' * columnsCount) + '\n'
tableCode += (' '.join('|' * columnsCount) + '\n') * rowsCount
cursor.insertText(tableCode)
self.close()
# Activate the Table editing mode
self.parent.actionTableMode.setChecked(True)
tab.editBox.tableModeEnabled = True
././@PaxHeader 0000000 0000000 0000000 00000000026 00000000000 010213 x ustar 00 22 mtime=1633978476.0
ReText-7.2.3/ReText/tablemode.py 0000644 0001750 0001750 00000021665 00000000000 016074 0 ustar 00dmitry dmitry # vim: ts=8:sts=8:sw=8:noexpandtab
#
# This file is part of ReText
# Copyright: 2014, 2017 Maurice van der Pot
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see .
import sys
from markups import MarkdownMarkup, ReStructuredTextMarkup
from PyQt5.QtGui import QTextCursor
LARGER_THAN_ANYTHING = sys.maxsize
class Row:
def __init__(self, block=None, text=None, separatorline=False, paddingchar=' '):
self.block = block
self.text = text
self.separatorline = separatorline
self.paddingchar = paddingchar
def __repr__(self):
return "" % (self.text, self.separatorline, self.paddingchar)
def _getTableLines(doc, pos, markupClass):
startblock = doc.findBlock(pos)
editedlineindex = 0
offset = pos - startblock.position()
rows = [ Row(block = startblock,
text = startblock.text()) ]
block = startblock.previous()
while any(c in block.text() for c in '+|'):
rows.insert(0, Row(block = block,
text = block.text()))
editedlineindex += 1
block = block.previous()
block = startblock.next()
while any(c in block.text() for c in '+|'):
rows.append(Row(block = block,
text = block.text()))
block = block.next()
if markupClass == MarkdownMarkup:
for i, row in enumerate(rows):
if i == 1:
row.separatorline = True
row.paddingchar = '-'
elif markupClass == ReStructuredTextMarkup:
for row in rows:
if row.text.strip().startswith(('+-','+=')):
row.separatorline = True
row.paddingchar = row.text.strip()[1]
row.text = row.text.replace('+', '|')
return rows, editedlineindex, offset
# Modify the edited line to put the table borders after the edition in their original positions.
# It does not matter that this function changes the position of table borders before the edition,
# because table editing mode only ever changes the table to the right of the cursor position.
def _sortaUndoEdit(rows, editedlineindex, offset, editsize):
aftertext = rows[editedlineindex].text
if editsize < 0:
beforetext = ' ' * -editsize + aftertext
else:
beforetext = aftertext[:offset] + aftertext[offset + editsize:]
rows[editedlineindex].text = beforetext
# Given text and the position of the n-th edge, returns n - 1
def _getEdgeIndex(text, edge):
return text[:edge].count('|')
def _determineRoomInCell(row, edge, edgeIndex, shrinking, startposition=0):
if len(row.text) > edge and row.text[edge] == '|' and \
(not edgeIndex or _getEdgeIndex(row.text, edge) == edgeIndex):
clearance = 0
cellwidth = 0
afterContent = True
for i in range(edge - 1, startposition - 1, -1):
if row.text[i] == '|':
break
else:
if row.text[i] == row.paddingchar and afterContent:
clearance += 1
else:
afterContent = False
cellwidth += 1
if row.separatorline:
if shrinking:
# do not shrink separator cells below 3
room = max(0, cellwidth - 3)
else:
# start expanding the cell if only the space for a right-align marker is left
room = max(0, cellwidth - 1)
else:
room = clearance
else:
room = LARGER_THAN_ANYTHING
return room
# Add an edit for a row to match the specified shift if it has an edge on the
# specified position
def _performShift(row, rowShift, edge, edgeIndex, shift):
editlist = []
# Any row that has an edge on the specified position and that doesn't
# already have edits that shift it 'shift' positions, will get an
# additional edit
if len(row.text) > edge and row.text[edge] == '|' and rowShift != shift and \
(not edgeIndex or _getEdgeIndex(row.text, edge) == edgeIndex):
editsize = -(rowShift - shift)
rowShift = shift
# Insert one position further to the left on separator lines, because
# there may be a space (for esthetical reasons) or an alignment marker
# on the last position before the edge and that should stay next to the
# edge.
if row.separatorline:
edge -= 1
editlist.append((edge, editsize))
return editlist, rowShift
# Finds the next edge position starting at offset in any row that is shifting.
# Rows that are not shifting when we are searching for an edge starting at
# offset, are rows that (upto offset) did not have any edges that aligned with
# shifting edges on other rows.
def _determineNextEdge(rows, rowShifts, offset):
nextedge = None
nextedgerow = None
for row, rowShift in zip(rows, rowShifts):
if rowShift != 0:
edge = row.text.find('|', offset)
if edge != -1 and (nextedge is None or edge < nextedge):
nextedge = edge
nextedgerow = row
return nextedge, _getEdgeIndex(nextedgerow.text, nextedge) if nextedge else None
# Return a list of edits to be made in other lines to adapt the table lines to
# a single edit in the edited line.
def _determineEditLists(rows, editedlineindex, offset, editsize, alignWithAnyEdge):
# rowShift represents how much the characters on a line will shift as a
# result of the already collected edits to be made.
rowShifts = [0 for _ in rows]
rowShifts[editedlineindex] = editsize
editLists = [[] for _ in rows]
# Find the next edge position on the edited row
currentedge, currentedgeindex = _determineNextEdge(rows, rowShifts, offset)
firstEdge = True
while currentedge:
if alignWithAnyEdge:
# Ignore what column the edge belongs to
currentedgeindex = None
if editsize < 0:
# How much an edge shifts to the left depends on how much room
# there is in the cells on any row that shares this edge.
leastLeftShift = min((-rowShift + _determineRoomInCell(row, currentedge, currentedgeindex, True)
for row, rowShift in zip(rows, rowShifts)))
shift = max(editsize, -leastLeftShift)
else:
# When shifting right, determine how much only once based on how
# much the edited cell needs to expand
if firstEdge:
room = _determineRoomInCell(rows[editedlineindex], currentedge, currentedgeindex, False, offset)
shift = max(0, editsize - room)
for i, row in enumerate(rows):
editList, newRowShift = _performShift(row, rowShifts[i], currentedge, currentedgeindex, shift)
rowShifts[i] = newRowShift
editLists[i].extend(editList)
currentedge, currentedgeindex = _determineNextEdge(rows, rowShifts, currentedge + 1)
firstEdge = False
return editLists
def _performEdits(cursor, rows, editLists, linewithoffset, offset):
cursor.joinPreviousEditBlock()
for i, (row, editList) in enumerate(zip(rows, editLists)):
for editpos, editsize in sorted(editList, reverse=True):
if i == linewithoffset:
editpos += offset
cursor.setPosition(row.block.position() + editpos)
if editsize > 0:
cursor.insertText(editsize * row.paddingchar)
else:
for _ in range(-editsize):
cursor.deletePreviousChar()
cursor.endEditBlock()
def adjustTableToChanges(doc, pos, editsize, markupClass):
if markupClass in (MarkdownMarkup, ReStructuredTextMarkup):
# This is needed because in ReSt cells can span multiple columns
# and we can therefore not determine which edges in other rows
# are supposed to be aligned with the edges in the edited row.
alignWithAnyEdge = (markupClass == ReStructuredTextMarkup)
rows, editedlineindex, offset = _getTableLines(doc, pos, markupClass)
_sortaUndoEdit(rows, editedlineindex, offset, editsize)
editLists = _determineEditLists(rows, editedlineindex, offset, editsize, alignWithAnyEdge)
cursor = QTextCursor(doc)
_performEdits(cursor, rows, editLists, editedlineindex, editsize)
def handleReturn(cursor, markupClass, newRow):
if markupClass not in (MarkdownMarkup, ReStructuredTextMarkup):
return False
positionInBlock = cursor.positionInBlock()
cursor.select(QTextCursor.SelectionType.BlockUnderCursor)
oldLine = cursor.selectedText().lstrip('\u2029')
if not ('| ' in oldLine or ' |' in oldLine):
cursor.setPosition(cursor.block().position() + positionInBlock)
return False
indent = 0
while oldLine[indent] in ' \t':
indent += 1
indentChars, oldLine = oldLine[:indent], oldLine[indent:]
newLine = ''.join('|' if c in '+|' else ' ' for c in oldLine).rstrip()
cursor.movePosition(QTextCursor.MoveOperation.EndOfBlock)
if newRow and markupClass == MarkdownMarkup:
sepLine = ''.join(c if c in ' |' else '-' for c in oldLine)
cursor.insertText('\n' + indentChars + sepLine)
elif newRow:
sepLine = ''.join('+' if c in '+|' else '-' for c in oldLine)
cursor.insertText('\n' + indentChars + sepLine)
cursor.insertText('\n' + indentChars + newLine)
positionInBlock = min(positionInBlock, len(indentChars + newLine))
cursor.setPosition(cursor.block().position() + positionInBlock)
return True
././@PaxHeader 0000000 0000000 0000000 00000000026 00000000000 010213 x ustar 00 22 mtime=1642949280.0
ReText-7.2.3/ReText/webenginepreview.py 0000644 0001750 0001750 00000013304 00000000000 017474 0 ustar 00dmitry dmitry # vim: ts=4:sw=4:expandtab
# This file is part of ReText
# Copyright: 2017-2021 Dmitry Shachnev
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see .
from ReText import globalSettings
from ReText.preview import ReTextWebPreview
from ReText.syncscroll import SyncScroll
from PyQt5.QtCore import QEvent, Qt
from PyQt5.QtGui import QDesktopServices, QGuiApplication, QTextDocument
from PyQt5.QtWebEngineCore import QWebEngineUrlRequestInfo, QWebEngineUrlRequestInterceptor
from PyQt5.QtWebEngineWidgets import QWebEnginePage, QWebEngineView, QWebEngineSettings
class ReTextWebEngineUrlRequestInterceptor(QWebEngineUrlRequestInterceptor):
def interceptRequest(self, info):
if (info.resourceType() == QWebEngineUrlRequestInfo.ResourceType.ResourceTypeXhr
and info.requestUrl().isLocalFile()):
# For security reasons, disable XMLHttpRequests to local files
info.block(True)
class ReTextWebEnginePage(QWebEnginePage):
def __init__(self, parent, tab):
QWebEnginePage.__init__(self, parent)
self.tab = tab
self.interceptor = ReTextWebEngineUrlRequestInterceptor(self)
if hasattr(self, 'setUrlRequestInterceptor'): # Available since Qt 5.13
self.setUrlRequestInterceptor(self.interceptor)
else:
self.profile().setRequestInterceptor(self.interceptor)
def setScrollPosition(self, pos):
self.runJavaScript("window.scrollTo(%s, %s);" % (pos.x(), pos.y()))
def getPositionMap(self, callback):
def resultCallback(result):
if result:
return callback({int(a): b for a, b in result.items()})
script = """
var elements = document.querySelectorAll('[data-posmap]');
var result = {};
var bodyTop = document.body.getBoundingClientRect().top;
for (var i = 0; i < elements.length; ++i) {
var element = elements[i];
value = element.getAttribute('data-posmap');
bottom = element.getBoundingClientRect().bottom - bodyTop;
result[value] = bottom;
}
result;
"""
self.runJavaScript(script, resultCallback)
def javaScriptConsoleMessage(self, level, message, lineNumber, sourceId):
print("level=%r message=%r lineNumber=%r sourceId=%r" % (level, message, lineNumber, sourceId))
def acceptNavigationRequest(self, url, type, isMainFrame):
if url.scheme() == "data":
return True
if url.isLocalFile():
localFile = url.toLocalFile()
if localFile == self.tab.fileName:
self.tab.startPendingConversion()
return False
if self.tab.openSourceFile(localFile):
return False
if globalSettings.handleWebLinks:
return True
QDesktopServices.openUrl(url)
return False
class ReTextWebEnginePreview(ReTextWebPreview, QWebEngineView):
def __init__(self, tab,
editorPositionToSourceLineFunc,
sourceLineToEditorPositionFunc):
QWebEngineView.__init__(self, parent=tab)
webPage = ReTextWebEnginePage(self, tab)
self.setPage(webPage)
self.syncscroll = SyncScroll(webPage,
editorPositionToSourceLineFunc,
sourceLineToEditorPositionFunc)
ReTextWebPreview.__init__(self, tab.editBox)
def updateFontSettings(self):
settings = self.settings()
settings.setFontFamily(QWebEngineSettings.FontFamily.StandardFont,
globalSettings.font.family())
settings.setFontSize(QWebEngineSettings.FontSize.DefaultFontSize,
globalSettings.font.pointSize())
def setHtml(self, html, baseUrl):
# A hack to prevent WebEngine from stealing the focus
self.setEnabled(False)
super().setHtml(html, baseUrl)
self.setEnabled(True)
def _handleWheelEvent(self, event):
# Only pass wheelEvents on to the preview if syncscroll is
# controlling the position of the preview
if self.syncscroll.isActive():
QGuiApplication.sendEvent(self.focusProxy(), event)
def event(self, event):
# Work-around https://bugreports.qt.io/browse/QTBUG-43602
if event.type() == QEvent.Type.ChildAdded:
event.child().installEventFilter(self)
elif event.type() == QEvent.Type.ChildRemoved:
event.child().removeEventFilter(self)
return super().event(event)
def eventFilter(self, object, event):
if event.type() == QEvent.Type.Wheel:
if QGuiApplication.keyboardModifiers() == Qt.KeyboardModifier.ControlModifier:
self.wheelEvent(event)
return True
return False
def findText(self, text, flags):
options = QWebEnginePage.FindFlags()
if flags & QTextDocument.FindFlag.FindBackward:
options |= QWebEnginePage.FindFlag.FindBackward
if flags & QTextDocument.FindFlag.FindCaseSensitively:
options |= QWebEnginePage.FindFlag.FindCaseSensitively
super().findText(text, options)
return True
././@PaxHeader 0000000 0000000 0000000 00000000026 00000000000 010213 x ustar 00 22 mtime=1642949280.0
ReText-7.2.3/ReText/webkitpreview.py 0000644 0001750 0001750 00000006354 00000000000 017025 0 ustar 00dmitry dmitry # vim: ts=8:sts=8:sw=8:noexpandtab
#
# This file is part of ReText
# Copyright: 2015-2021 Dmitry Shachnev
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see .
from ReText import globalSettings
from ReText.syncscroll import SyncScroll
from ReText.preview import ReTextWebPreview
from PyQt5.QtCore import QStandardPaths
from PyQt5.QtGui import QDesktopServices, QTextDocument
from PyQt5.QtNetwork import QNetworkDiskCache
from PyQt5.QtWebKit import QWebSettings
from PyQt5.QtWebKitWidgets import QWebPage, QWebView
class ReTextWebKitPreview(ReTextWebPreview, QWebView):
def __init__(self, tab,
editorPositionToSourceLineFunc,
sourceLineToEditorPositionFunc):
QWebView.__init__(self)
self.tab = tab
self.syncscroll = SyncScroll(self.page().mainFrame(),
editorPositionToSourceLineFunc,
sourceLineToEditorPositionFunc)
ReTextWebPreview.__init__(self, tab.editBox)
self.page().setLinkDelegationPolicy(QWebPage.LinkDelegationPolicy.DelegateAllLinks)
self.page().linkClicked.connect(self._handleLinkClicked)
self.settings().setAttribute(QWebSettings.WebAttribute.LocalContentCanAccessFileUrls, False)
# Avoid caching of CSS
self.settings().setObjectCacheCapacities(0,0,0)
self.cache = QNetworkDiskCache()
cacheDirectory = QStandardPaths.writableLocation(QStandardPaths.StandardLocation.CacheLocation)
self.cache.setCacheDirectory(cacheDirectory)
self.page().networkAccessManager().setCache(self.cache)
def updateFontSettings(self):
settings = self.settings()
settings.setFontFamily(QWebSettings.FontFamily.StandardFont,
globalSettings.font.family())
settings.setFontSize(QWebSettings.FontSize.DefaultFontSize,
globalSettings.font.pointSize())
def _handleWheelEvent(self, event):
# Only pass wheelEvents on to the preview if syncscroll is
# controlling the position of the preview
if self.syncscroll.isActive():
self.wheelEvent(event)
def _handleLinkClicked(self, url):
if url.isLocalFile():
localFile = url.toLocalFile()
if localFile == self.tab.fileName and url.hasFragment():
self.page().mainFrame().scrollToAnchor(url.fragment())
return
if self.tab.openSourceFile(localFile):
return
if globalSettings.handleWebLinks:
self.load(url)
else:
QDesktopServices.openUrl(url)
def findText(self, text, flags):
options = QWebPage.FindFlag.FindWrapsAroundDocument
if flags & QTextDocument.FindFlag.FindBackward:
options |= QWebPage.FindFlag.FindBackward
if flags & QTextDocument.FindFlag.FindCaseSensitively:
options |= QWebPage.FindFlag.FindCaseSensitively
return super().findText(text, options)
././@PaxHeader 0000000 0000000 0000000 00000000026 00000000000 010213 x ustar 00 22 mtime=1643919520.0
ReText-7.2.3/ReText/window.py 0000644 0001750 0001750 00000144265 00000000000 015451 0 ustar 00dmitry dmitry # vim: ts=8:sts=8:sw=8:noexpandtab
#
# This file is part of ReText
# Copyright: 2012-2021 Dmitry Shachnev
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see .
import markups
import sys
import os
from subprocess import Popen
import warnings
from ReText import (getBundledIcon, app_version, globalSettings,
readListFromSettings, writeListToSettings, datadirs)
from ReText.tab import (ReTextTab, ReTextWebKitPreview, ReTextWebEnginePreview,
PreviewDisabled, PreviewNormal, PreviewLive)
from ReText.dialogs import HtmlDialog, LocaleDialog
from ReText.config import ConfigDialog, setIconThemeFromSettings
from ReText.tabledialog import InsertTableDialog
try:
from ReText.fakevimeditor import ReTextFakeVimHandler, FakeVimMode
except ImportError:
ReTextFakeVimHandler = None
try:
import enchant
except ImportError:
enchant = None
from PyQt5.QtCore import QDir, QFile, QFileInfo, QFileSystemWatcher, \
QIODevice, QLocale, QMarginsF, QTextCodec, QTextStream, QTimer, QUrl, Qt, pyqtSlot
from PyQt5.QtGui import QColor, QDesktopServices, QIcon, \
QKeySequence, QPageLayout, QPageSize, QPagedPaintDevice, QPalette, \
QTextDocument, QTextDocumentWriter
from PyQt5.QtWidgets import QAction, QActionGroup, QApplication, QCheckBox, \
QComboBox, QDialog, QFileDialog, QFileSystemModel, QFontDialog, \
QInputDialog, QLineEdit, QMainWindow, QMenu, QMessageBox, QSplitter, QTabWidget, \
QToolBar, QToolButton, QTreeView
from PyQt5.QtPrintSupport import QPrintDialog, QPrintPreviewDialog, QPrinter
class ReTextWindow(QMainWindow):
def __init__(self, parent=None):
QMainWindow.__init__(self, parent)
self.resize(950, 700)
qApp = QApplication.instance()
if hasattr(self, 'screen'): # Available since Qt 5.14
screenRect = self.screen().geometry()
else:
screenRect = qApp.desktop().screenGeometry()
if globalSettings.windowGeometry:
self.restoreGeometry(globalSettings.windowGeometry)
else:
self.move((screenRect.width() - self.width()) // 2,
(screenRect.height() - self.height()) // 2)
if not screenRect.contains(self.geometry()):
self.showMaximized()
if sys.platform.startswith('darwin'):
# https://github.com/retext-project/retext/issues/198
searchPaths = QIcon.themeSearchPaths()
searchPaths.append('/opt/local/share/icons')
searchPaths.append('/usr/local/share/icons')
QIcon.setThemeSearchPaths(searchPaths)
setIconThemeFromSettings()
if QFile.exists(getBundledIcon('retext')):
self.setWindowIcon(QIcon(getBundledIcon('retext')))
elif QFile.exists('/usr/share/pixmaps/retext.png'):
self.setWindowIcon(QIcon('/usr/share/pixmaps/retext.png'))
else:
self.setWindowIcon(QIcon.fromTheme('retext',
QIcon.fromTheme('accessories-text-editor')))
self.splitter = QSplitter(self)
self.treeView = QTreeView(self.splitter)
self.treeView.doubleClicked.connect(self.treeItemSelected)
self.tabWidget = QTabWidget(self.splitter)
self.initTabWidget()
self.splitter.setSizes([self.width() // 5, self.width() * 4 // 5])
self.initDirectoryTree(globalSettings.showDirectoryTree, globalSettings.directoryPath)
self.setCentralWidget(self.splitter)
self.tabWidget.currentChanged.connect(self.changeIndex)
self.tabWidget.tabCloseRequested.connect(self.closeTab)
self.toolBar = QToolBar(self.tr('File toolbar'), self)
self.addToolBar(Qt.ToolBarArea.TopToolBarArea, self.toolBar)
self.editBar = QToolBar(self.tr('Edit toolbar'), self)
self.addToolBar(Qt.ToolBarArea.TopToolBarArea, self.editBar)
self.searchBar = QToolBar(self.tr('Search toolbar'), self)
self.addToolBar(Qt.ToolBarArea.BottomToolBarArea, self.searchBar)
self.toolBar.setVisible(not globalSettings.hideToolBar)
self.editBar.setVisible(not globalSettings.hideToolBar)
self.actionNew = self.act(self.tr('New'), 'document-new',
self.createNew, shct=QKeySequence.StandardKey.New)
self.actionOpen = self.act(self.tr('Open'), 'document-open',
self.openFile, shct=QKeySequence.StandardKey.Open)
self.actionSetEncoding = self.act(self.tr('Set encoding'),
trig=self.showEncodingDialog)
self.actionSetEncoding.setEnabled(False)
self.actionReload = self.act(self.tr('Reload'), 'view-refresh',
lambda: self.currentTab.readTextFromFile())
self.actionReload.setEnabled(False)
self.actionSave = self.act(self.tr('Save'), 'document-save',
self.saveFile, shct=QKeySequence.StandardKey.Save)
self.actionSave.setEnabled(False)
self.actionSaveAs = self.act(self.tr('Save as'), 'document-save-as',
self.saveFileAs, shct=QKeySequence.StandardKey.SaveAs)
self.actionNextTab = self.act(self.tr('Next tab'), 'go-next',
lambda: self.switchTab(1), shct=Qt.Modifier.CTRL+Qt.Key.Key_PageDown)
self.actionPrevTab = self.act(self.tr('Previous tab'), 'go-previous',
lambda: self.switchTab(-1), shct=Qt.Modifier.CTRL+Qt.Key.Key_PageUp)
self.actionCloseCurrentTab = self.act(self.tr('Close tab'), 'window-close',
lambda: self.closeTab(self.ind), shct=QKeySequence.StandardKey.Close)
self.actionPrint = self.act(self.tr('Print'), 'document-print',
self.printFile, shct=QKeySequence.StandardKey.Print)
self.actionPrintPreview = self.act(self.tr('Print preview'), 'document-print-preview',
self.printPreview)
self.actionViewHtml = self.act(self.tr('View HTML code'), 'text-html', self.viewHtml)
self.actionChangeEditorFont = self.act(self.tr('Change editor font'),
trig=self.changeEditorFont)
self.actionChangePreviewFont = self.act(self.tr('Change preview font'),
trig=self.changePreviewFont)
self.actionSearch = self.act(self.tr('Find text'), 'edit-find',
self.search, shct=QKeySequence.StandardKey.Find)
self.actionGoToLine = self.act(self.tr('Go to line'),
trig=self.goToLine, shct=Qt.Modifier.CTRL+Qt.Key.Key_G)
self.searchBar.visibilityChanged.connect(self.searchBarVisibilityChanged)
self.actionPreview = self.act(self.tr('Preview'), shct=Qt.Modifier.CTRL+Qt.Key.Key_E,
trigbool=self.preview)
if QIcon.hasThemeIcon('document-preview'):
self.actionPreview.setIcon(QIcon.fromTheme('document-preview'))
elif QIcon.hasThemeIcon('preview-file'):
self.actionPreview.setIcon(QIcon.fromTheme('preview-file'))
elif QIcon.hasThemeIcon('x-office-document'):
self.actionPreview.setIcon(QIcon.fromTheme('x-office-document'))
else:
self.actionPreview.setIcon(QIcon(getBundledIcon('document-preview')))
self.actionLivePreview = self.act(self.tr('Live preview'), shct=Qt.Modifier.CTRL+Qt.Key.Key_L,
trigbool=self.enableLivePreview)
menuPreview = QMenu()
menuPreview.addAction(self.actionLivePreview)
self.actionInsertTable = self.act(self.tr('Insert table'),
trig=lambda: self.insertFormatting('table'))
self.actionTableMode = self.act(self.tr('Table editing mode'),
shct=Qt.Modifier.CTRL+Qt.Key.Key_T,
trigbool=lambda x: self.currentTab.editBox.enableTableMode(x))
self.actionInsertImages = self.act(self.tr('Insert images by file path'),
trig=lambda: self.insertImages())
if ReTextFakeVimHandler:
self.actionFakeVimMode = self.act(self.tr('FakeVim mode'),
shct=Qt.Modifier.CTRL+Qt.Modifier.ALT+Qt.Key.Key_V, trigbool=self.enableFakeVimMode)
if globalSettings.useFakeVim:
self.actionFakeVimMode.setChecked(True)
self.enableFakeVimMode(True)
self.actionFullScreen = self.act(self.tr('Fullscreen mode'), 'view-fullscreen',
shct=QKeySequence.StandardKey.FullScreen, trigbool=self.enableFullScreen)
self.actionFullScreen.setChecked(self.isFullScreen())
self.actionConfig = self.act(self.tr('Preferences'), icon='preferences-system',
trig=self.openConfigDialog)
self.actionConfig.setMenuRole(QAction.MenuRole.PreferencesRole)
self.actionSaveHtml = self.act('HTML', 'text-html', self.saveFileHtml)
self.actionPdf = self.act('PDF', 'application-pdf', self.savePdf)
self.actionOdf = self.act('ODT', 'x-office-document', self.saveOdf)
self.getExportExtensionsList()
self.actionQuit = self.act(self.tr('Quit'), 'application-exit', shct=QKeySequence.StandardKey.Quit)
self.actionQuit.setMenuRole(QAction.MenuRole.QuitRole)
self.actionQuit.triggered.connect(self.close)
self.actionUndo = self.act(self.tr('Undo'), 'edit-undo',
lambda: self.currentTab.editBox.undo(), shct=QKeySequence.StandardKey.Undo)
self.actionRedo = self.act(self.tr('Redo'), 'edit-redo',
lambda: self.currentTab.editBox.redo(), shct=QKeySequence.StandardKey.Redo)
self.actionCopy = self.act(self.tr('Copy'), 'edit-copy',
lambda: self.currentTab.editBox.copy(), shct=QKeySequence.StandardKey.Copy)
self.actionCut = self.act(self.tr('Cut'), 'edit-cut',
lambda: self.currentTab.editBox.cut(), shct=QKeySequence.StandardKey.Cut)
self.actionPaste = self.act(self.tr('Paste'), 'edit-paste',
lambda: self.currentTab.editBox.paste(), shct=QKeySequence.StandardKey.Paste)
self.actionPasteImage = self.act(self.tr('Paste image'), 'edit-paste',
lambda: self.currentTab.editBox.pasteImage(), shct=Qt.Modifier.CTRL+Qt.Modifier.SHIFT+Qt.Key.Key_V)
self.actionMoveUp = self.act(self.tr('Move line up'), 'go-up',
lambda: self.currentTab.editBox.moveLineUp(), shct=Qt.Modifier.ALT+Qt.Key.Key_Up)
self.actionMoveDown = self.act(self.tr('Move line down'), 'go-down',
lambda: self.currentTab.editBox.moveLineDown(), shct=Qt.Modifier.ALT+Qt.Key.Key_Down)
self.actionUndo.setEnabled(False)
self.actionRedo.setEnabled(False)
self.actionCopy.setEnabled(False)
self.actionCut.setEnabled(False)
qApp.clipboard().dataChanged.connect(self.clipboardDataChanged)
self.clipboardDataChanged()
if enchant is not None:
self.actionEnableSC = self.act(self.tr('Enable'), trigbool=self.enableSpellCheck)
self.actionSetLocale = self.act(self.tr('Set locale'), trig=self.changeLocale)
self.actionWebKit = self.act(self.tr('Use WebKit renderer'), trigbool=self.enableWebKit)
if ReTextWebKitPreview is None:
globalSettings.useWebKit = False
self.actionWebKit.setEnabled(False)
self.actionWebKit.setChecked(globalSettings.useWebKit)
self.actionWebEngine = self.act(self.tr('Use WebEngine (Chromium) renderer'),
trigbool=self.enableWebEngine)
if ReTextWebEnginePreview is None:
globalSettings.useWebEngine = False
self.actionWebEngine.setChecked(globalSettings.useWebEngine)
self.actionShow = self.act(self.tr('Show directory'), 'system-file-manager', self.showInDir)
self.actionFind = self.act(self.tr('Next'), 'go-next', self.find,
shct=QKeySequence.StandardKey.FindNext)
self.actionFindPrev = self.act(self.tr('Previous'), 'go-previous',
lambda: self.find(back=True), shct=QKeySequence.StandardKey.FindPrevious)
self.actionReplace = self.act(self.tr('Replace'), 'edit-find-replace',
lambda: self.find(replace=True))
self.actionReplaceAll = self.act(self.tr('Replace all'), trig=self.replaceAll)
menuReplace = QMenu()
menuReplace.addAction(self.actionReplaceAll)
self.actionCloseSearch = self.act(self.tr('Close'), 'window-close',
lambda: self.searchBar.setVisible(False),
shct=QKeySequence.StandardKey.Cancel)
self.actionCloseSearch.setPriority(QAction.Priority.LowPriority)
self.actionHelp = self.act(self.tr('Get help online'), 'help-contents', self.openHelp)
self.aboutWindowTitle = self.tr('About ReText')
self.actionAbout = self.act(self.aboutWindowTitle, 'help-about', self.aboutDialog)
self.actionAbout.setMenuRole(QAction.MenuRole.AboutRole)
self.actionAboutQt = self.act(self.tr('About Qt'))
self.actionAboutQt.setMenuRole(QAction.MenuRole.AboutQtRole)
self.actionAboutQt.triggered.connect(qApp.aboutQt)
availableMarkups = markups.get_available_markups()
if not availableMarkups:
print('Warning: no markups are available!')
if len(availableMarkups) > 1:
self.chooseGroup = QActionGroup(self)
markupActions = []
for markup in availableMarkups:
markupAction = self.act(markup.name, trigbool=self.markupFunction(markup))
if markup.name == globalSettings.defaultMarkup:
markupAction.setChecked(True)
self.chooseGroup.addAction(markupAction)
markupActions.append(markupAction)
self.actionBold = self.act(self.tr('Bold'), shct=QKeySequence.StandardKey.Bold,
trig=lambda: self.insertFormatting('bold'))
self.actionItalic = self.act(self.tr('Italic'), shct=QKeySequence.StandardKey.Italic,
trig=lambda: self.insertFormatting('italic'))
self.actionUnderline = self.act(self.tr('Underline'), shct=QKeySequence.StandardKey.Underline,
trig=lambda: self.insertFormatting('underline'))
self.usefulTags = ('header', 'italic', 'bold', 'underline', 'numbering',
'bullets', 'image', 'link', 'inline code', 'code block', 'blockquote',
'table')
self.usefulChars = ('deg', 'divide', 'euro', 'hellip', 'laquo', 'larr',
'lsquo', 'mdash', 'middot', 'minus', 'nbsp', 'ndash', 'raquo',
'rarr', 'rsquo', 'times')
self.formattingBox = QComboBox(self.editBar)
self.formattingBox.addItem(self.tr('Formatting'))
self.formattingBox.addItems(self.usefulTags)
if hasattr(self.formattingBox, 'textActivated'): # Available since Qt 5.14
self.formattingBox.textActivated.connect(self.insertFormatting)
else:
self.formattingBox.activated[str].connect(self.insertFormatting)
self.symbolBox = QComboBox(self.editBar)
self.symbolBox.addItem(self.tr('Symbols'))
self.symbolBox.addItems(self.usefulChars)
self.symbolBox.activated.connect(self.insertSymbol)
self.updateStyleSheet()
menubar = self.menuBar()
menuFile = menubar.addMenu(self.tr('&File'))
menuEdit = menubar.addMenu(self.tr('&Edit'))
menuHelp = menubar.addMenu(self.tr('&Help'))
menuFile.addAction(self.actionNew)
menuFile.addAction(self.actionOpen)
self.menuRecentFiles = menuFile.addMenu(self.tr('Open recent'))
self.menuRecentFiles.aboutToShow.connect(self.updateRecentFiles)
menuFile.addAction(self.actionShow)
menuFile.addAction(self.actionSetEncoding)
menuFile.addAction(self.actionReload)
menuFile.addSeparator()
menuFile.addAction(self.actionSave)
menuFile.addAction(self.actionSaveAs)
menuFile.addSeparator()
menuFile.addAction(self.actionNextTab)
menuFile.addAction(self.actionPrevTab)
menuFile.addAction(self.actionCloseCurrentTab)
menuFile.addSeparator()
menuExport = menuFile.addMenu(self.tr('Export'))
menuExport.addAction(self.actionSaveHtml)
menuExport.addAction(self.actionOdf)
menuExport.addAction(self.actionPdf)
if self.extensionActions:
menuExport.addSeparator()
for action, mimetype in self.extensionActions:
menuExport.addAction(action)
menuExport.aboutToShow.connect(self.updateExtensionsVisibility)
menuFile.addAction(self.actionPrint)
menuFile.addAction(self.actionPrintPreview)
menuFile.addSeparator()
menuFile.addAction(self.actionQuit)
menuEdit.addAction(self.actionUndo)
menuEdit.addAction(self.actionRedo)
menuEdit.addSeparator()
menuEdit.addAction(self.actionCut)
menuEdit.addAction(self.actionCopy)
menuEdit.addAction(self.actionPaste)
menuEdit.addAction(self.actionPasteImage)
menuEdit.addSeparator()
menuEdit.addAction(self.actionMoveUp)
menuEdit.addAction(self.actionMoveDown)
menuEdit.addSeparator()
if enchant is not None:
menuSC = menuEdit.addMenu(self.tr('Spell check'))
menuSC.addAction(self.actionEnableSC)
menuSC.addAction(self.actionSetLocale)
menuEdit.addAction(self.actionSearch)
menuEdit.addAction(self.actionGoToLine)
menuEdit.addAction(self.actionChangeEditorFont)
menuEdit.addAction(self.actionChangePreviewFont)
menuEdit.addSeparator()
if len(availableMarkups) > 1:
self.menuMode = menuEdit.addMenu(self.tr('Default markup'))
for markupAction in markupActions:
self.menuMode.addAction(markupAction)
menuFormat = menuEdit.addMenu(self.tr('Formatting'))
menuFormat.addAction(self.actionBold)
menuFormat.addAction(self.actionItalic)
menuFormat.addAction(self.actionUnderline)
if ReTextWebKitPreview is not None or ReTextWebEnginePreview is None:
menuEdit.addAction(self.actionWebKit)
else:
menuEdit.addAction(self.actionWebEngine)
menuEdit.addSeparator()
menuEdit.addAction(self.actionViewHtml)
menuEdit.addAction(self.actionPreview)
menuEdit.addAction(self.actionLivePreview)
menuEdit.addAction(self.actionInsertTable)
menuEdit.addAction(self.actionTableMode)
menuEdit.addAction(self.actionInsertImages)
if ReTextFakeVimHandler:
menuEdit.addAction(self.actionFakeVimMode)
menuEdit.addSeparator()
menuEdit.addAction(self.actionFullScreen)
menuEdit.addAction(self.actionConfig)
menuHelp.addAction(self.actionHelp)
menuHelp.addSeparator()
menuHelp.addAction(self.actionAbout)
menuHelp.addAction(self.actionAboutQt)
self.toolBar.addAction(self.actionNew)
self.toolBar.addSeparator()
self.toolBar.addAction(self.actionOpen)
self.toolBar.addAction(self.actionSave)
self.toolBar.addAction(self.actionPrint)
self.toolBar.addSeparator()
previewButton = QToolButton(self.toolBar)
previewButton.setDefaultAction(self.actionPreview)
previewButton.setToolButtonStyle(Qt.ToolButtonStyle.ToolButtonTextBesideIcon)
previewButton.setPopupMode(QToolButton.ToolButtonPopupMode.MenuButtonPopup)
previewButton.setMenu(menuPreview)
self.toolBar.addWidget(previewButton)
self.toolBar.addAction(self.actionFullScreen)
self.editBar.addAction(self.actionUndo)
self.editBar.addAction(self.actionRedo)
self.editBar.addSeparator()
self.editBar.addAction(self.actionCut)
self.editBar.addAction(self.actionCopy)
self.editBar.addAction(self.actionPaste)
self.editBar.addSeparator()
self.editBar.addWidget(self.formattingBox)
self.editBar.addWidget(self.symbolBox)
self.searchEdit = QLineEdit(self.searchBar)
self.searchEdit.setPlaceholderText(self.tr('Search'))
self.searchEdit.returnPressed.connect(self.find)
self.replaceEdit = QLineEdit(self.searchBar)
self.replaceEdit.setPlaceholderText(self.tr('Replace with'))
self.replaceEdit.returnPressed.connect(self.find)
self.csBox = QCheckBox(self.tr('Case sensitively'), self.searchBar)
self.searchBar.addWidget(self.searchEdit)
self.searchBar.addWidget(self.replaceEdit)
self.searchBar.addSeparator()
self.searchBar.addWidget(self.csBox)
self.searchBar.addAction(self.actionFindPrev)
self.searchBar.addAction(self.actionFind)
replaceButton = QToolButton(self.searchBar)
replaceButton.setDefaultAction(self.actionReplace)
replaceButton.setToolButtonStyle(Qt.ToolButtonStyle.ToolButtonTextBesideIcon)
replaceButton.setPopupMode(QToolButton.ToolButtonPopupMode.MenuButtonPopup)
replaceButton.setMenu(menuReplace)
self.searchBar.addWidget(replaceButton)
self.searchBar.addAction(self.actionCloseSearch)
self.searchBar.setToolButtonStyle(Qt.ToolButtonStyle.ToolButtonTextBesideIcon)
self.searchBar.setVisible(False)
self.autoSaveEnabled = globalSettings.autoSave
if self.autoSaveEnabled:
timer = QTimer(self)
timer.start(60000)
timer.timeout.connect(self.saveAll)
self.ind = None
if enchant is not None:
self.sl = globalSettings.spellCheckLocale
try:
enchant.Dict(self.sl or None)
except enchant.errors.Error as e:
warnings.warn(str(e), RuntimeWarning)
globalSettings.spellCheck = False
if globalSettings.spellCheck:
self.actionEnableSC.setChecked(True)
self.fileSystemWatcher = QFileSystemWatcher()
self.fileSystemWatcher.fileChanged.connect(self.fileChanged)
def restoreLastOpenedFiles(self):
for file in readListFromSettings("lastFileList"):
self.openFileWrapper(file)
# Show the tab of last opened file
lastTabIndex = globalSettings.lastTabIndex
if lastTabIndex >= 0 and lastTabIndex < self.tabWidget.count():
self.tabWidget.setCurrentIndex(lastTabIndex)
def iterateTabs(self):
for i in range(self.tabWidget.count()):
yield self.tabWidget.widget(i)
def updateStyleSheet(self):
self.ss = None
if globalSettings.styleSheet:
sheetfile = QFile(globalSettings.styleSheet)
sheetfile.open(QIODevice.OpenModeFlag.ReadOnly)
self.ss = QTextStream(sheetfile).readAll()
sheetfile.close()
def initTabWidget(self):
def dragEnterEvent(e):
e.acceptProposedAction()
def dropEvent(e):
fn = bytes(e.mimeData().data('text/plain')).decode().rstrip()
if fn.startswith('file:'):
fn = QUrl(fn).toLocalFile()
self.openFileWrapper(fn)
self.tabWidget.setTabsClosable(True)
self.tabWidget.setAcceptDrops(True)
self.tabWidget.setMovable(True)
self.tabWidget.dragEnterEvent = dragEnterEvent
self.tabWidget.dropEvent = dropEvent
self.tabWidget.setTabBarAutoHide(globalSettings.tabBarAutoHide)
def initDirectoryTree(self, visible, path):
if visible:
self.fileSystemModel = QFileSystemModel(self.treeView)
self.fileSystemModel.setRootPath(path)
supportedExtensions = ['.txt']
for markup in markups.get_all_markups():
supportedExtensions += markup.file_extensions
filters = ["*" + s for s in supportedExtensions]
self.fileSystemModel.setNameFilters(filters)
self.fileSystemModel.setNameFilterDisables(False)
self.treeView.setModel(self.fileSystemModel)
self.treeView.setRootIndex(self.fileSystemModel.index(path))
self.treeView.setColumnHidden(1, True)
self.treeView.setColumnHidden(2, True)
self.treeView.setColumnHidden(3, True)
self.treeView.setHeaderHidden(True)
self.treeView.setVisible(visible)
def treeItemSelected(self, signal):
file_path = self.fileSystemModel.filePath(signal)
if os.path.isdir(file_path):
return
self.openFileWrapper(file_path)
def act(self, name, icon=None, trig=None, trigbool=None, shct=None):
if not isinstance(shct, QKeySequence):
shct = QKeySequence(shct)
if icon:
action = QAction(self.actIcon(icon), name, self)
else:
action = QAction(name, self)
if trig:
action.triggered.connect(trig)
elif trigbool:
action.setCheckable(True)
action.triggered[bool].connect(trigbool)
if shct:
action.setShortcut(shct)
return action
def actIcon(self, name):
return QIcon.fromTheme(name, QIcon(getBundledIcon(name)))
def printError(self):
import traceback
print('Exception occurred while parsing document:', file=sys.stderr)
traceback.print_exc()
def updateTabTitle(self, ind, tab):
changed = tab.editBox.document().isModified()
if changed and not self.autoSaveActive(tab):
title = tab.getBaseName() + '*'
else:
title = tab.getBaseName()
self.tabWidget.setTabText(ind, title)
def tabFileNameChanged(self, tab):
'''
Perform all UI state changes that need to be done when the
filename of the current tab has changed.
'''
if tab == self.currentTab:
if tab.fileName:
self.setWindowTitle("")
if globalSettings.windowTitleFullPath:
self.setWindowTitle(tab.fileName + '[*]')
self.setWindowFilePath(tab.fileName)
self.updateTabTitle(self.ind, tab)
self.tabWidget.setTabToolTip(self.ind, tab.fileName)
QDir.setCurrent(QFileInfo(tab.fileName).dir().path())
else:
self.setWindowFilePath('')
self.setWindowTitle(self.tr('New document') + '[*]')
canReload = bool(tab.fileName) and not self.autoSaveActive(tab)
self.actionSetEncoding.setEnabled(canReload)
self.actionReload.setEnabled(canReload)
def tabActiveMarkupChanged(self, tab):
'''
Perform all UI state changes that need to be done when the
active markup class of the current tab has changed.
'''
if tab == self.currentTab:
markupClass = tab.getActiveMarkupClass()
dtMarkdown = (markupClass == markups.MarkdownMarkup)
dtMkdOrReST = dtMarkdown or (markupClass == markups.ReStructuredTextMarkup)
self.formattingBox.setEnabled(dtMarkdown)
self.symbolBox.setEnabled(dtMarkdown)
self.actionUnderline.setEnabled(dtMarkdown)
self.actionBold.setEnabled(dtMkdOrReST)
self.actionItalic.setEnabled(dtMkdOrReST)
def tabModificationStateChanged(self, tab):
'''
Perform all UI state changes that need to be done when the
modification state of the current tab has changed.
'''
if tab == self.currentTab:
changed = tab.editBox.document().isModified()
if self.autoSaveActive(tab):
changed = False
self.actionSave.setEnabled(changed)
self.updateTabTitle(self.ind, tab)
self.setWindowModified(changed)
def createTab(self, fileName):
previewStatesByName = {
'editor': PreviewDisabled,
'normal-preview': PreviewNormal,
'live-preview': PreviewLive,
}
previewState = previewStatesByName.get(globalSettings.defaultPreviewState, PreviewDisabled)
if previewState == PreviewNormal and not fileName:
previewState = PreviewDisabled # Opening empty document in preview mode makes no sense
self.currentTab = ReTextTab(self, fileName, previewState)
self.currentTab.fileNameChanged.connect(lambda: self.tabFileNameChanged(self.currentTab))
self.currentTab.modificationStateChanged.connect(lambda: self.tabModificationStateChanged(self.currentTab))
self.currentTab.activeMarkupChanged.connect(lambda: self.tabActiveMarkupChanged(self.currentTab))
self.tabWidget.addTab(self.currentTab, self.tr("New document"))
self.currentTab.updateBoxesVisibility()
if previewState > 0:
QTimer.singleShot(500, self.currentTab.triggerPreviewUpdate)
def closeTab(self, ind):
if self.maybeSave(ind):
if self.tabWidget.count() == 1:
self.createTab("")
closedTab = self.tabWidget.widget(ind)
if closedTab.fileName:
self.fileSystemWatcher.removePath(closedTab.fileName)
self.tabWidget.removeTab(ind)
closedTab.deleteLater()
def changeIndex(self, ind):
'''
This function is called when a different tab is selected.
It changes the state of the window to mirror the current state
of the newly selected tab. Future changes to this state will be
done in response to signals emitted by the tab, to which the
window was subscribed when the tab was created. The window is
subscribed to all tabs like this, but only the active tab will
logically generate these signals.
Aside from the above this function also calls the handlers for
the other changes that are implied by a tab switch: filename
change, modification state change and active markup change.
'''
self.currentTab = self.tabWidget.currentWidget()
editBox = self.currentTab.editBox
previewState = self.currentTab.previewState
self.actionUndo.setEnabled(editBox.document().isUndoAvailable())
self.actionRedo.setEnabled(editBox.document().isRedoAvailable())
self.actionCopy.setEnabled(editBox.textCursor().hasSelection())
self.actionCut.setEnabled(editBox.textCursor().hasSelection())
self.actionPreview.setChecked(previewState >= PreviewLive)
self.actionLivePreview.setChecked(previewState == PreviewLive)
self.actionTableMode.setChecked(editBox.tableModeEnabled)
self.editBar.setEnabled(previewState < PreviewNormal)
self.ind = ind
editBox.setFocus(Qt.FocusReason.OtherFocusReason)
self.tabFileNameChanged(self.currentTab)
self.tabModificationStateChanged(self.currentTab)
self.tabActiveMarkupChanged(self.currentTab)
def changeEditorFont(self):
font, ok = QFontDialog.getFont(globalSettings.editorFont, self)
if ok:
self.setEditorFont(font)
def setEditorFont(self, font):
globalSettings.editorFont = font
for tab in self.iterateTabs():
tab.editBox.updateFont()
def changePreviewFont(self):
font, ok = QFontDialog.getFont(globalSettings.font, self)
if ok:
self.setPreviewFont(font)
def setPreviewFont(self, font):
globalSettings.font = font
for tab in self.iterateTabs():
tab.triggerPreviewUpdate()
def preview(self, viewmode):
self.currentTab.previewState = viewmode * 2
self.actionLivePreview.setChecked(False)
self.editBar.setDisabled(viewmode)
self.currentTab.updateBoxesVisibility()
self.currentTab.triggerPreviewUpdate()
def enableLivePreview(self, livemode):
self.currentTab.previewState = int(livemode)
self.actionPreview.setChecked(livemode)
self.editBar.setEnabled(True)
self.currentTab.updateBoxesVisibility()
self.currentTab.triggerPreviewUpdate()
def enableWebKit(self, enable):
globalSettings.useWebKit = enable
globalSettings.useWebEngine = False
for tab in self.iterateTabs():
tab.rebuildPreviewBox()
def enableWebEngine(self, enable):
globalSettings.useWebKit = False
globalSettings.useWebEngine = enable
for tab in self.iterateTabs():
tab.rebuildPreviewBox()
def enableCopy(self, copymode):
self.actionCopy.setEnabled(copymode)
self.actionCut.setEnabled(copymode)
def enableFullScreen(self, yes):
if yes:
self.showFullScreen()
else:
self.showNormal()
def openConfigDialog(self):
dlg = ConfigDialog(self)
dlg.setWindowTitle(self.tr('Preferences'))
dlg.show()
def enableFakeVimMode(self, yes):
globalSettings.useFakeVim = yes
if yes:
FakeVimMode.init(self)
for tab in self.iterateTabs():
tab.editBox.installFakeVimHandler()
else:
FakeVimMode.exit(self)
def enableSpellCheck(self, yes):
try:
dict = enchant.Dict(self.sl or None)
except enchant.errors.Error as e:
QMessageBox.warning(self, '', str(e))
self.actionEnableSC.setChecked(False)
yes = False
self.setAllDictionaries(dict if yes else None)
globalSettings.spellCheck = yes
def setAllDictionaries(self, dictionary):
for tab in self.iterateTabs():
hl = tab.highlighter
hl.dictionary = dictionary
hl.rehighlight()
def changeLocale(self):
localedlg = LocaleDialog(self, defaultText=self.sl)
if localedlg.exec() != QDialog.DialogCode.Accepted:
return
sl = localedlg.localeEdit.text()
try:
enchant.Dict(sl or None)
except enchant.errors.Error as e:
QMessageBox.warning(self, '', str(e))
else:
self.sl = sl or None
self.enableSpellCheck(self.actionEnableSC.isChecked())
if localedlg.checkBox.isChecked():
globalSettings.spellCheckLocale = sl
def search(self):
self.searchBar.setVisible(True)
self.searchEdit.setFocus(Qt.FocusReason.ShortcutFocusReason)
def goToLine(self):
line, ok = QInputDialog.getInt(self, self.tr("Go to line"), self.tr("Type the line number"))
if ok:
self.currentTab.goToLine(line-1)
def searchBarVisibilityChanged(self, visible):
if visible:
self.searchEdit.setFocus(Qt.FocusReason.ShortcutFocusReason)
def find(self, back=False, replace=False):
flags = QTextDocument.FindFlags()
if back:
flags |= QTextDocument.FindFlag.FindBackward
if self.csBox.isChecked():
flags |= QTextDocument.FindFlag.FindCaseSensitively
text = self.searchEdit.text()
replaceText = self.replaceEdit.text() if replace else None
found = self.currentTab.find(text, flags, replaceText=replaceText)
self.setSearchEditColor(found)
def replaceAll(self):
text = self.searchEdit.text()
replaceText = self.replaceEdit.text()
found = self.currentTab.replaceAll(text, replaceText)
self.setSearchEditColor(found)
def setSearchEditColor(self, found):
palette = self.searchEdit.palette()
palette.setColor(QPalette.ColorGroup.Active, QPalette.ColorRole.Base,
Qt.GlobalColor.white if found else QColor(255, 102, 102))
self.searchEdit.setPalette(palette)
def showInDir(self):
if self.currentTab.fileName:
path = QFileInfo(self.currentTab.fileName).path()
QDesktopServices.openUrl(QUrl.fromLocalFile(path))
else:
QMessageBox.warning(self, '', self.tr("Please, save the file somewhere."))
def moveToTopOfRecentFileList(self, fileName):
if fileName:
files = readListFromSettings("recentFileList")
if fileName in files:
files.remove(fileName)
files.insert(0, fileName)
recentCount = globalSettings.recentDocumentsCount
if len(files) > recentCount:
del files[recentCount:]
writeListToSettings("recentFileList", files)
def createNew(self, text=None):
self.createTab("")
self.ind = self.tabWidget.count()-1
self.tabWidget.setCurrentIndex(self.ind)
if text:
self.currentTab.editBox.textCursor().insertText(text)
def switchTab(self, shift=1):
self.tabWidget.setCurrentIndex((self.ind + shift) % self.tabWidget.count())
def updateRecentFiles(self):
self.menuRecentFiles.clear()
self.recentFilesActions = []
filesOld = readListFromSettings("recentFileList")
files = []
for f in filesOld:
if QFile.exists(f):
files.append(f)
self.recentFilesActions.append(self.act(f, trig=self.openFunction(f)))
writeListToSettings("recentFileList", files)
for action in self.recentFilesActions:
self.menuRecentFiles.addAction(action)
def markupFunction(self, markup):
return lambda: self.setDefaultMarkup(markup)
def openFunction(self, fileName):
return lambda: self.openFileWrapper(fileName)
def extensionFunction(self, data):
return lambda: \
self.runExtensionCommand(data['Exec'], data['FileFilter'], data['DefaultExtension'])
def getExportExtensionsList(self):
extensions = []
for extsprefix in datadirs:
extsdir = QDir(extsprefix+'/export-extensions/')
if extsdir.exists():
for fileInfo in extsdir.entryInfoList(['*.desktop', '*.ini'],
QDir.Filter.Files | QDir.Filter.Readable):
extensions.append(self.readExtension(fileInfo.filePath()))
locale = QLocale.system().name()
self.extensionActions = []
for extension in extensions:
try:
if ('Name[%s]' % locale) in extension:
name = extension['Name[%s]' % locale]
elif ('Name[%s]' % locale.split('_')[0]) in extension:
name = extension['Name[%s]' % locale.split('_')[0]]
else:
name = extension['Name']
data = {}
for prop in ('FileFilter', 'DefaultExtension', 'Exec'):
if 'X-ReText-'+prop in extension:
data[prop] = extension['X-ReText-'+prop]
elif prop in extension:
data[prop] = extension[prop]
else:
data[prop] = ''
action = self.act(name, trig=self.extensionFunction(data))
if 'Icon' in extension:
action.setIcon(self.actIcon(extension['Icon']))
mimetype = extension['MimeType'] if 'MimeType' in extension else None
except KeyError:
print('Failed to parse extension: Name is required', file=sys.stderr)
else:
self.extensionActions.append((action, mimetype))
def updateExtensionsVisibility(self):
markupClass = self.currentTab.getActiveMarkupClass()
for action in self.extensionActions:
if markupClass is None:
action[0].setEnabled(False)
continue
mimetype = action[1]
if mimetype is None:
enabled = True
elif markupClass == markups.MarkdownMarkup:
enabled = (mimetype == "text/markdown")
elif markupClass == markups.ReStructuredTextMarkup:
enabled = (mimetype == "text/x-rst")
else:
enabled = False
action[0].setEnabled(enabled)
def readExtension(self, fileName):
extFile = QFile(fileName)
extFile.open(QIODevice.OpenModeFlag.ReadOnly)
extension = {}
stream = QTextStream(extFile)
while not stream.atEnd():
line = stream.readLine()
if '=' in line:
index = line.index('=')
extension[line[:index].rstrip()] = line[index+1:].lstrip()
extFile.close()
return extension
def openFile(self):
supportedExtensions = ['.txt']
for markup in markups.get_all_markups():
supportedExtensions += markup.file_extensions
fileFilter = ' (' + str.join(' ', ['*'+ext for ext in supportedExtensions]) + ');;'
fileNames = QFileDialog.getOpenFileNames(self,
self.tr("Select one or several files to open"), QDir.currentPath(),
self.tr("Supported files") + fileFilter + self.tr("All files (*)"))
for fileName in fileNames[0]:
self.openFileWrapper(fileName)
@pyqtSlot(str)
def openFileWrapper(self, fileName):
if not fileName:
return
fileName = QFileInfo(fileName).canonicalFilePath()
exists = False
for i, tab in enumerate(self.iterateTabs()):
if tab.fileName == fileName:
exists = True
ex = i
if exists:
self.tabWidget.setCurrentIndex(ex)
elif QFile.exists(fileName):
noEmptyTab = (
(self.ind is None) or
self.currentTab.fileName or
self.currentTab.editBox.toPlainText() or
self.currentTab.editBox.document().isModified()
)
if noEmptyTab:
self.createTab(fileName)
self.ind = self.tabWidget.count()-1
self.tabWidget.setCurrentIndex(self.ind)
if fileName:
self.fileSystemWatcher.addPath(fileName)
self.currentTab.readTextFromFile(fileName)
self.moveToTopOfRecentFileList(self.currentTab.fileName)
def showEncodingDialog(self):
if not self.maybeSave(self.ind):
return
codecsSet = set(bytes(QTextCodec.codecForName(alias).name())
for alias in QTextCodec.availableCodecs())
encoding, ok = QInputDialog.getItem(self, '',
self.tr('Select file encoding from the list:'),
[bytes(b).decode() for b in sorted(codecsSet)],
0, False)
if ok:
self.currentTab.readTextFromFile(None, encoding)
def saveFileAs(self):
self.saveFile(dlg=True)
def saveAll(self):
for tab in self.iterateTabs():
if (tab.fileName and tab.editBox.document().isModified()
and QFileInfo(tab.fileName).isWritable()):
tab.saveTextToFile()
def saveFile(self, dlg=False):
fileNameToSave = self.currentTab.fileName
if (not fileNameToSave) or dlg:
proposedFileName = ""
markupClass = self.currentTab.getActiveMarkupClass()
if (markupClass is None) or not hasattr(markupClass, 'default_extension'):
defaultExt = self.tr("Plain text (*.txt)")
ext = ".txt"
else:
defaultExt = self.tr('%s files',
'Example of final string: Markdown files') \
% markupClass.name + ' (' + str.join(' ',
('*'+extension for extension in markupClass.file_extensions)) + ')'
if markupClass == markups.MarkdownMarkup:
ext = globalSettings.markdownDefaultFileExtension
elif markupClass == markups.ReStructuredTextMarkup:
ext = globalSettings.restDefaultFileExtension
else:
ext = markupClass.default_extension
if fileNameToSave is not None:
proposedFileName = fileNameToSave
fileNameToSave = QFileDialog.getSaveFileName(self,
self.tr("Save file"), proposedFileName, defaultExt)[0]
if fileNameToSave:
if not QFileInfo(fileNameToSave).suffix():
fileNameToSave += ext
# Make sure we don't overwrite a file opened in other tab
for tab in self.iterateTabs():
if tab is not self.currentTab and tab.fileName == fileNameToSave:
QMessageBox.warning(self, "",
self.tr("Cannot save to file which is open in another tab!"))
return False
self.actionSetEncoding.setDisabled(self.autoSaveActive())
if fileNameToSave:
if self.currentTab.saveTextToFile(fileNameToSave):
self.moveToTopOfRecentFileList(self.currentTab.fileName)
return True
else:
QMessageBox.warning(self, '',
self.tr("Cannot save to file because it is read-only!"))
return False
def saveHtml(self, fileName):
if not QFileInfo(fileName).suffix():
fileName += ".html"
try:
_, htmltext, _ = self.currentTab.getDocumentForExport(webenv=True)
except Exception:
return self.printError()
htmlFile = QFile(fileName)
result = htmlFile.open(QIODevice.OpenModeFlag.WriteOnly)
if not result:
QMessageBox.warning(self, '',
self.tr("Cannot save to file because it is read-only!"))
return
html = QTextStream(htmlFile)
if globalSettings.defaultCodec:
html.setCodec(globalSettings.defaultCodec)
html << htmltext
htmlFile.close()
def textDocument(self, title, htmltext):
td = QTextDocument()
td.setMetaInformation(QTextDocument.MetaInformation.DocumentTitle, title)
td.setHtml(htmltext)
td.setDefaultFont(globalSettings.font)
return td
def saveOdf(self):
title, htmltext, _ = self.currentTab.getDocumentForExport()
try:
document = self.textDocument(title, htmltext)
except Exception:
return self.printError()
fileName = QFileDialog.getSaveFileName(self,
self.tr("Export document to ODT"), self.currentTab.getBaseName() + ".odt",
self.tr("OpenDocument text files (*.odt)"))[0]
if not QFileInfo(fileName).suffix():
fileName += ".odt"
writer = QTextDocumentWriter(fileName)
writer.setFormat(b"odf")
writer.write(document)
def saveFileHtml(self):
fileName = QFileDialog.getSaveFileName(self,
self.tr("Save file"), self.currentTab.getBaseName() + ".html",
self.tr("HTML files (*.html *.htm)"))[0]
if fileName:
self.saveHtml(fileName)
def getDocumentForPrint(self, title, htmltext, preview):
if globalSettings.useWebKit:
return preview
try:
return self.textDocument(title, htmltext)
except Exception:
self.printError()
def standardPrinter(self, title):
printer = QPrinter(QPrinter.PrinterMode.HighResolution)
printer.setDocName(title)
printer.setCreator('ReText %s' % app_version)
if globalSettings.paperSize:
pageSize = self.getPageSizeByName(globalSettings.paperSize)
if pageSize is not None:
printer.setPaperSize(pageSize)
else:
QMessageBox.warning(self, '',
self.tr('Unrecognized paperSize setting "%s".') %
globalSettings.paperSize)
return printer
def getPageSizeByName(self, pageSizeName):
""" Returns a validated PageSize instance corresponding to the given
name. Returns None if the name is not a valid PageSize.
"""
pageSize = None
lowerCaseNames = {pageSize.lower(): pageSize for pageSize in
self.availablePageSizes()}
if pageSizeName.lower() in lowerCaseNames:
pageSize = getattr(QPagedPaintDevice, lowerCaseNames[pageSizeName.lower()])
return pageSize
def availablePageSizes(self):
""" List available page sizes. """
sizes = [x for x in dir(QPagedPaintDevice)
if type(getattr(QPagedPaintDevice, x)) == QPagedPaintDevice.PageSize]
return sizes
def savePdf(self):
fileName = QFileDialog.getSaveFileName(self,
self.tr("Export document to PDF"),
self.currentTab.getBaseName() + ".pdf",
self.tr("PDF files (*.pdf)"))[0]
if fileName:
if not QFileInfo(fileName).suffix():
fileName += ".pdf"
title, htmltext, preview = self.currentTab.getDocumentForExport()
if globalSettings.useWebEngine:
pageSize = self.getPageSizeByName(globalSettings.paperSize)
if pageSize is None:
pageSize = QPageSize(QPageSize.PageSizeId.A4)
margins = QMarginsF(20, 20, 13, 20) # left, top, right, bottom (in millimeters)
layout = QPageLayout(pageSize, QPageLayout.Orientation.Portrait, margins, QPageLayout.Unit.Millimeter)
preview.page().printToPdf(fileName, layout)
return
printer = self.standardPrinter(title)
printer.setOutputFormat(QPrinter.OutputFormat.PdfFormat)
printer.setOutputFileName(fileName)
document = self.getDocumentForPrint(title, htmltext, preview)
if document != None:
document.print(printer)
def printFile(self):
title, htmltext, preview = self.currentTab.getDocumentForExport()
printer = self.standardPrinter(title)
dlg = QPrintDialog(printer, self)
dlg.setWindowTitle(self.tr("Print document"))
if (dlg.exec() == QDialog.DialogCode.Accepted):
document = self.getDocumentForPrint(title, htmltext, preview)
if document != None:
document.print(printer)
def printPreview(self):
title, htmltext, preview = self.currentTab.getDocumentForExport()
document = self.getDocumentForPrint(title, htmltext, preview)
if document is None:
return
printer = self.standardPrinter(title)
preview = QPrintPreviewDialog(printer, self)
preview.paintRequested.connect(document.print)
preview.exec()
def runExtensionCommand(self, command, filefilter, defaultext):
import shlex
of = ('%of' in command)
html = ('%html' in command)
if of:
if defaultext and not filefilter:
filefilter = '*'+defaultext
fileName = QFileDialog.getSaveFileName(self,
self.tr('Export document'), '', filefilter)[0]
if not fileName:
return
if defaultext and not QFileInfo(fileName).suffix():
fileName += defaultext
else:
fileName = 'out' + defaultext
basename = '.%s.retext-temp' % self.currentTab.getBaseName()
if html:
tmpname = basename+'.html'
self.saveHtml(tmpname)
else:
tmpname = basename + self.currentTab.getActiveMarkupClass().default_extension
self.currentTab.writeTextToFile(tmpname)
command = command.replace('%of', shlex.quote(fileName))
command = command.replace('%html' if html else '%if', shlex.quote(tmpname))
try:
Popen(str(command), shell=True).wait()
except Exception as error:
errorstr = str(error)
QMessageBox.warning(self, '', self.tr('Failed to execute the command:')
+ '\n' + errorstr)
QFile(tmpname).remove()
def autoSaveActive(self, tab=None):
tab = tab if tab else self.currentTab
return bool(self.autoSaveEnabled and tab.fileName and
QFileInfo(tab.fileName).isWritable())
def clipboardDataChanged(self):
mimeData = QApplication.instance().clipboard().mimeData()
if mimeData is not None:
self.actionPaste.setEnabled(mimeData.hasText())
self.actionPasteImage.setEnabled(mimeData.hasImage())
def insertFormatting(self, formatting):
if formatting == 'table':
dialog = InsertTableDialog(self)
dialog.show()
self.formattingBox.setCurrentIndex(0)
return
cursor = self.currentTab.editBox.textCursor()
text = cursor.selectedText()
moveCursorTo = None
def c(cursor):
nonlocal moveCursorTo
moveCursorTo = cursor.position()
def ensurenl(cursor):
if not cursor.atBlockStart():
cursor.insertText('\n\n')
toinsert = {
'header': (ensurenl, '# ', text),
'italic': ('*', text, c, '*'),
'bold': ('**', text, c, '**'),
'underline': ('', text, c, ''),
'numbering': (ensurenl, ' 1. ', text),
'bullets': (ensurenl, ' * ', text),
'image': (', ')'),
'link': ('[', text or self.tr('Link text'), c, '](', self.tr('URL'), ')'),
'inline code': ('`', text, c, '`'),
'code block': (ensurenl, ' ', text),
'blockquote': (ensurenl, '> ', text),
}
if formatting not in toinsert:
return
cursor.beginEditBlock()
for token in toinsert[formatting]:
if callable(token):
token(cursor)
else:
cursor.insertText(token)
cursor.endEditBlock()
self.formattingBox.setCurrentIndex(0)
# Bring back the focus on the editor
self.currentTab.editBox.setFocus(Qt.FocusReason.OtherFocusReason)
if moveCursorTo:
cursor.setPosition(moveCursorTo)
self.currentTab.editBox.setTextCursor(cursor)
def insertSymbol(self, num):
if num:
self.currentTab.editBox.insertPlainText('&'+self.usefulChars[num-1]+';')
self.symbolBox.setCurrentIndex(0)
def fileChanged(self, fileName):
tab = None
for testtab in self.iterateTabs():
if testtab.fileName == fileName:
tab = testtab
if tab is None:
self.fileSystemWatcher.removePath(fileName)
return
if not QFile.exists(fileName):
self.tabWidget.setCurrentWidget(tab)
tab.editBox.document().setModified(True)
QMessageBox.warning(self, '', self.tr(
'This file has been deleted by other application.\n'
'Please make sure you save the file before exit.'))
elif not tab.editBox.document().isModified():
# File was not modified in ReText, reload silently
tab.readTextFromFile()
else:
self.tabWidget.setCurrentWidget(tab)
text = self.tr(
'This document has been modified by other application.\n'
'Do you want to reload the file (this will discard all '
'your changes)?\n')
if self.autoSaveEnabled:
text += self.tr(
'If you choose to not reload the file, auto save mode will '
'be disabled for this session to prevent data loss.')
messageBox = QMessageBox(QMessageBox.Icon.Warning, '', text)
reloadButton = messageBox.addButton(self.tr('Reload'), QMessageBox.ButtonRole.YesRole)
messageBox.addButton(QMessageBox.StandardButton.Cancel)
messageBox.exec()
if messageBox.clickedButton() is reloadButton:
tab.readTextFromFile()
else:
self.autoSaveEnabled = False
tab.editBox.document().setModified(True)
if fileName not in self.fileSystemWatcher.files():
# https://github.com/retext-project/retext/issues/137
self.fileSystemWatcher.addPath(fileName)
def maybeSave(self, ind):
tab = self.tabWidget.widget(ind)
if self.autoSaveActive(tab):
tab.saveTextToFile()
return True
if not tab.editBox.document().isModified():
return True
self.tabWidget.setCurrentIndex(ind)
ret = QMessageBox.warning(self, '',
self.tr("The document has been modified.\nDo you want to save your changes?"),
QMessageBox.StandardButton.Save | QMessageBox.StandardButton.Discard | QMessageBox.StandardButton.Cancel)
if ret == QMessageBox.StandardButton.Save:
return self.saveFile(False)
elif ret == QMessageBox.StandardButton.Cancel:
return False
return True
def closeEvent(self, closeevent):
for ind in range(self.tabWidget.count()):
if not self.maybeSave(ind):
return closeevent.ignore()
if globalSettings.saveWindowGeometry:
globalSettings.windowGeometry = self.saveGeometry()
if globalSettings.openLastFilesOnStartup:
files = [tab.fileName for tab in self.iterateTabs()]
writeListToSettings("lastFileList", files)
globalSettings.lastTabIndex = self.tabWidget.currentIndex()
closeevent.accept()
def viewHtml(self):
htmlDlg = HtmlDialog(self)
try:
_, htmltext, _ = self.currentTab.getDocumentForExport(includeStyleSheet=False)
except Exception:
return self.printError()
winTitle = self.currentTab.getBaseName()
htmlDlg.setWindowTitle(winTitle+" ("+self.tr("HTML code")+")")
htmlDlg.textEdit.setPlainText(htmltext.rstrip())
htmlDlg.hl.rehighlight()
htmlDlg.show()
htmlDlg.raise_()
htmlDlg.activateWindow()
def insertImages(self):
supportedExtensions = ['.png', '.jpg', '.jpeg', '.gif', '.bmp']
fileFilter = ' (%s);;' % ' '.join('*' + ext for ext in supportedExtensions)
fileNames, _selectedFilter = QFileDialog.getOpenFileNames(self,
self.tr("Select one or several images to open"), QDir.currentPath(),
self.tr("Supported files") + fileFilter + self.tr("All files (*)"))
cursor = self.currentTab.editBox.textCursor()
imagesMarkup = '\n'.join(
self.currentTab.editBox.getImageMarkup(fileName)
for fileName in fileNames)
cursor.insertText(imagesMarkup)
self.formattingBox.setCurrentIndex(0)
self.currentTab.editBox.setFocus(Qt.FocusReason.OtherFocusReason)
def openHelp(self):
QDesktopServices.openUrl(QUrl('https://github.com/retext-project/retext/wiki'))
def aboutDialog(self):
QMessageBox.about(self, self.aboutWindowTitle,
'
')
def setDefaultMarkup(self, markupClass):
globalSettings.defaultMarkup = markupClass.name
for tab in self.iterateTabs():
if not tab.fileName:
tab.updateActiveMarkupClass()
././@PaxHeader 0000000 0000000 0000000 00000000026 00000000000 010213 x ustar 00 22 mtime=1633978476.0
ReText-7.2.3/ReText/xsettings.py 0000644 0001750 0001750 00000015504 00000000000 016163 0 ustar 00dmitry dmitry # This file is part of ReText
# Copyright: 2015-2017 Dmitry Shachnev
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see .
# This is implementation of XSettings specification, described at
#
import ctypes
import ctypes.util
import struct
class _xcb_reply_t(ctypes.Structure):
# this can be used instead of xcb_intern_atom_reply_t,
# xcb_get_selection_owner_reply_t, etc
_fields_ = [('response_type', ctypes.c_uint8),
('pad0', ctypes.c_uint8),
('sequence', ctypes.c_uint16),
('length', ctypes.c_uint32),
('payload', ctypes.c_uint32)]
class _xcb_cookie_t(ctypes.Structure):
# this can be used instead of xcb_intern_atom_cookie_t,
# xcb_get_selection_owner_cookie_t, etc
_fields_ = [('sequence', ctypes.c_uint)]
_xcb_error_messages = [
None,
'XCB error: socket, pipe and other stream error',
'XCB connection closed: extension unsupported',
'XCB connection closed: insufficient memory',
'XCB connection closed: request length exceeded',
'XCB connection closed: DISPLAY parse error',
'XCB connection closed: invalid screen'
]
class XSettingsError(RuntimeError):
pass
class XSettingsParseError(XSettingsError):
pass
def get_raw_xsettings(display=0):
# initialize the libraries
xcb_library_name = ctypes.util.find_library('xcb')
if xcb_library_name is None:
raise XSettingsError('Xcb library not found')
xcb = ctypes.CDLL(xcb_library_name)
c_library_name = ctypes.util.find_library('c')
if c_library_name is None:
raise XSettingsError('C library not found')
c = ctypes.CDLL(c_library_name)
# set some args and return types
c.free.argtypes = [ctypes.c_void_p]
c.free.restype = None
xcb.xcb_connect.argtypes = [ctypes.c_char_p, ctypes.POINTER(ctypes.c_int)]
xcb.xcb_connect.restype = ctypes.c_void_p
xcb.xcb_connection_has_error.argtypes = [ctypes.c_void_p]
xcb.xcb_connection_has_error.restype = ctypes.c_int
xcb.xcb_disconnect.argtypes = [ctypes.c_void_p]
xcb.xcb_disconnect.restype = None
xcb.xcb_intern_atom.argtypes = [ctypes.c_void_p, ctypes.c_uint8, ctypes.c_uint16, ctypes.c_char_p]
xcb.xcb_intern_atom.restype = _xcb_cookie_t
xcb.xcb_intern_atom_reply.argtypes = [ctypes.c_void_p, _xcb_cookie_t, ctypes.c_void_p]
xcb.xcb_intern_atom_reply.restype = ctypes.POINTER(_xcb_reply_t)
xcb.xcb_get_selection_owner.argtypes = [ctypes.c_void_p, ctypes.c_uint32]
xcb.xcb_get_selection_owner.restype = _xcb_cookie_t
xcb.xcb_get_selection_owner_reply.argtypes = [ctypes.c_void_p, _xcb_cookie_t, ctypes.c_void_p]
xcb.xcb_get_selection_owner_reply.restype = ctypes.POINTER(_xcb_reply_t)
xcb.xcb_get_property.argtypes = [ctypes.c_void_p, ctypes.c_uint8, ctypes.c_uint32, ctypes.c_uint32,
ctypes.c_uint32, ctypes.c_uint32, ctypes.c_uint32]
xcb.xcb_get_property.restype = _xcb_cookie_t
xcb.xcb_get_property_reply.argtypes = [ctypes.c_void_p, _xcb_cookie_t, ctypes.c_void_p]
xcb.xcb_get_property_reply.restype = ctypes.c_void_p
xcb.xcb_get_property_value_length.argtypes = [ctypes.c_void_p]
xcb.xcb_get_property_value_length.restype = ctypes.c_int
xcb.xcb_get_property_value.argtypes = [ctypes.c_void_p]
xcb.xcb_get_property_value.restype = ctypes.c_void_p
# open the connection
connection = xcb.xcb_connect(None, None)
error = xcb.xcb_connection_has_error(connection)
if error:
raise XSettingsError(_xcb_error_messages[error])
# get selection atom cookie
buffer = ('_XSETTINGS_S%d' % display).encode()
cookie = xcb.xcb_intern_atom(connection, 0, len(buffer), buffer)
# get selection atom reply
reply = xcb.xcb_intern_atom_reply(connection, cookie, None)
selection_atom = reply.contents.payload
c.free(reply)
# get selection owner cookie
cookie = xcb.xcb_get_selection_owner(connection, selection_atom)
# get selection owner reply
reply = xcb.xcb_get_selection_owner_reply(connection, cookie, None)
window = reply.contents.payload
c.free(reply)
# get settings atom cookie
buffer = b'_XSETTINGS_SETTINGS'
cookie = xcb.xcb_intern_atom(connection, 0, len(buffer), buffer)
# get settings atom reply
reply = xcb.xcb_intern_atom_reply(connection, cookie, None)
settings_atom = reply.contents.payload
c.free(reply)
# get property cookie
cookie = xcb.xcb_get_property(connection, 0, window, settings_atom, 0, 0, 0x2000)
# get property reply
reply = xcb.xcb_get_property_reply(connection, cookie, None)
if reply is not None:
length = xcb.xcb_get_property_value_length(reply)
pointer = xcb.xcb_get_property_value(reply) if length else None
result = ctypes.string_at(pointer, length)
c.free(reply)
# close the connection
xcb.xcb_disconnect(connection)
# handle possible errors
if reply is None or not length:
raise XSettingsError('XSettings not available')
return result
def parse_xsettings(raw_xsettings):
if len(raw_xsettings) < 12:
raise XSettingsParseError('length < 12')
if raw_xsettings[0] not in (0, 1):
raise XSettingsParseError('wrong order byte: %d' % raw_xsettings[0])
byte_order = '<>'[raw_xsettings[0]]
settings_count = struct.unpack(byte_order + 'I', raw_xsettings[8:12])[0]
TypeInteger, TypeString, TypeColor = range(3)
result = {}
raw_xsettings = raw_xsettings[12:]
offset = 0
for i in range(settings_count):
setting_type = raw_xsettings[offset]
offset += 2
name_length = struct.unpack(byte_order + 'H', raw_xsettings[offset:offset + 2])[0]
offset += 2
name = raw_xsettings[offset:offset + name_length]
offset += name_length
if offset & 3:
offset += 4 - (offset & 3)
offset += 4 # skip last-change-serial
if setting_type == TypeInteger:
value = struct.unpack(byte_order + 'I', raw_xsettings[offset:offset + 4])[0]
offset += 4
elif setting_type == TypeString:
value_length = struct.unpack(byte_order + 'I', raw_xsettings[offset:offset + 4])[0]
offset += 4
value = raw_xsettings[offset:offset + value_length]
offset += value_length
if offset & 3:
offset += 4 - (offset & 3)
elif setting_type == TypeColor:
value = struct.unpack(byte_order + 'HHHH', raw_xsettings[offset:offset + 8])
offset += 8
else:
raise XSettingsParseError('Wrong setting type: %d' % setting_type)
result[name] = value
return result
def get_xsettings(display=0):
raw_xsettings = get_raw_xsettings(display)
return parse_xsettings(raw_xsettings)
././@PaxHeader 0000000 0000000 0000000 00000000034 00000000000 010212 x ustar 00 28 mtime=1643920524.1765156
ReText-7.2.3/ReText.egg-info/ 0000755 0001750 0001750 00000000000 00000000000 015246 5 ustar 00dmitry dmitry ././@PaxHeader 0000000 0000000 0000000 00000000026 00000000000 010213 x ustar 00 22 mtime=1643920524.0
ReText-7.2.3/ReText.egg-info/PKG-INFO 0000644 0001750 0001750 00000002263 00000000000 016346 0 ustar 00dmitry dmitry Metadata-Version: 2.1
Name: ReText
Version: 7.2.3
Summary: Simple editor for Markdown and reStructuredText
Home-page: https://github.com/retext-project/retext
Author: Dmitry Shachnev
Author-email: mitya57@gmail.com
License: GPL 2+
Platform: UNKNOWN
Classifier: Development Status :: 5 - Production/Stable
Classifier: Environment :: X11 Applications :: Qt
Classifier: License :: OSI Approved :: GNU General Public License v2 or later (GPLv2+)
Classifier: Programming Language :: Python :: 3 :: Only
Classifier: Topic :: Text Editors
Classifier: Topic :: Text Processing :: Markup
Requires: docutils
Requires: Markdown
Requires: Markups(>=2.0)
Requires: pyenchant
Requires: Pygments
Requires: PyQt5(>=5.11)
Requires-Python: >=3.6
Provides-Extra: spellcheck
License-File: LICENSE_GPL
ReText is simple text editor that supports Markdown and reStructuredText
markup languages. It is written in Python using PyQt libraries.
It supports live preview, tabs, math formulas, export to various formats
including PDF and HTML.
For more details, please go to the `home page`_ or to the `wiki`_.
.. _`home page`: https://github.com/retext-project/retext
.. _`wiki`: https://github.com/retext-project/retext/wiki
././@PaxHeader 0000000 0000000 0000000 00000000026 00000000000 010213 x ustar 00 22 mtime=1643920524.0
ReText-7.2.3/ReText.egg-info/SOURCES.txt 0000644 0001750 0001750 00000005405 00000000000 017136 0 ustar 00dmitry dmitry LICENSE_GPL
MANIFEST.in
README.md
changelog.md
configuration.md
setup.py
ReText/__init__.py
ReText/__main__.py
ReText/config.py
ReText/converterprocess.py
ReText/dialogs.py
ReText/editor.py
ReText/fakevimeditor.py
ReText/highlighter.py
ReText/icontheme.py
ReText/mdx_posmap.py
ReText/preview.py
ReText/syncscroll.py
ReText/tab.py
ReText/tabledialog.py
ReText/tablemode.py
ReText/webenginepreview.py
ReText/webkitpreview.py
ReText/window.py
ReText/xsettings.py
ReText.egg-info/PKG-INFO
ReText.egg-info/SOURCES.txt
ReText.egg-info/dependency_links.txt
ReText.egg-info/entry_points.txt
ReText.egg-info/requires.txt
ReText.egg-info/top_level.txt
data/me.mitya57.ReText.appdata.xml
data/me.mitya57.ReText.desktop
data/retext-kde5.png
icons/COPYING
icons/README.md
icons/application-exit.png
icons/application-pdf.png
icons/document-new.png
icons/document-open-recent.png
icons/document-open.png
icons/document-preview.png
icons/document-print-preview.png
icons/document-print.png
icons/document-save-as.png
icons/document-save.png
icons/edit-copy.png
icons/edit-cut.png
icons/edit-find.png
icons/edit-paste.png
icons/edit-redo.png
icons/edit-undo.png
icons/go-next.png
icons/go-previous.png
icons/help-about.png
icons/internet-web-browser.png
icons/retext.ico
icons/retext.png
icons/retext.svg
icons/system-file-manager.png
icons/text-html.png
icons/view-fullscreen.png
icons/x-office-document.png
locale/retext_ar.qm
locale/retext_ar.ts
locale/retext_ca.qm
locale/retext_ca.ts
locale/retext_cs.qm
locale/retext_cs.ts
locale/retext_cy.qm
locale/retext_cy.ts
locale/retext_da.qm
locale/retext_da.ts
locale/retext_de.qm
locale/retext_de.ts
locale/retext_es.qm
locale/retext_es.ts
locale/retext_es_CO.qm
locale/retext_es_CO.ts
locale/retext_et.qm
locale/retext_et.ts
locale/retext_eu.qm
locale/retext_eu.ts
locale/retext_fa.qm
locale/retext_fa.ts
locale/retext_fi.qm
locale/retext_fi.ts
locale/retext_fr.qm
locale/retext_fr.ts
locale/retext_hr.qm
locale/retext_hr.ts
locale/retext_hu.qm
locale/retext_hu.ts
locale/retext_it.qm
locale/retext_it.ts
locale/retext_ja.qm
locale/retext_ja.ts
locale/retext_ko.qm
locale/retext_ko.ts
locale/retext_nl.qm
locale/retext_nl.ts
locale/retext_pl.qm
locale/retext_pl.ts
locale/retext_pt.qm
locale/retext_pt.ts
locale/retext_pt_BR.qm
locale/retext_pt_BR.ts
locale/retext_ru.qm
locale/retext_ru.ts
locale/retext_sk.qm
locale/retext_sk.ts
locale/retext_sr.qm
locale/retext_sr.ts
locale/retext_sr@latin.qm
locale/retext_sr@latin.ts
locale/retext_sv.qm
locale/retext_sv.ts
locale/retext_uk.qm
locale/retext_uk.ts
locale/retext_zh_CN.qm
locale/retext_zh_CN.ts
locale/retext_zh_TW.qm
locale/retext_zh_TW.ts
tests/__init__.py
tests/test_editor.py
tests/test_posmap.py
tests/test_settings.py
tests/test_tablemode.py
tests/test_window.py
tests/testdata/existing_file.md
tests/testdata/existing_file.rst ././@PaxHeader 0000000 0000000 0000000 00000000026 00000000000 010213 x ustar 00 22 mtime=1643920524.0
ReText-7.2.3/ReText.egg-info/dependency_links.txt 0000644 0001750 0001750 00000000001 00000000000 021314 0 ustar 00dmitry dmitry
././@PaxHeader 0000000 0000000 0000000 00000000026 00000000000 010213 x ustar 00 22 mtime=1643920524.0
ReText-7.2.3/ReText.egg-info/entry_points.txt 0000644 0001750 0001750 00000000055 00000000000 020544 0 ustar 00dmitry dmitry [gui_scripts]
retext = ReText.__main__:main
././@PaxHeader 0000000 0000000 0000000 00000000026 00000000000 010213 x ustar 00 22 mtime=1643920524.0
ReText-7.2.3/ReText.egg-info/requires.txt 0000644 0001750 0001750 00000000136 00000000000 017646 0 ustar 00dmitry dmitry docutils
Markdown>=3.0
Markups>=2.0
Pygments
chardet>=2.3
PyQt5>=5.11
[spellcheck]
pyenchant
././@PaxHeader 0000000 0000000 0000000 00000000026 00000000000 010213 x ustar 00 22 mtime=1643920524.0
ReText-7.2.3/ReText.egg-info/top_level.txt 0000644 0001750 0001750 00000000007 00000000000 017775 0 ustar 00dmitry dmitry ReText
././@PaxHeader 0000000 0000000 0000000 00000000026 00000000000 010213 x ustar 00 22 mtime=1643920402.0
ReText-7.2.3/changelog.md 0000644 0001750 0001750 00000034674 00000000000 014630 0 ustar 00dmitry dmitry ## ReText 7.2.3 (2022-02-03)
* Issues #573, #574 — Fixed TypeError crash with Python 3.10 and Qt WebKit.
* Translations updated:
- Chinese (China) (contributed by liulitchi).
- Portuguese (Brazil) (contributed by Igor Garcia and Christiano Morais).
- Slovak (contributed by Jose Riha).
## ReText 7.2.2 (2021-10-11)
* Issue #552 — Fixed bad Spanish translation causing a crash.
* Fixed `TypeError: index 0 has type 'float' but 'int' is expected` with
Python 3.10.
* Fixed `RuntimeError: ffi_prep_cif_var failed` in XSettings code.
## ReText 7.2.1 (2021-03-06)
* Issues #255, #492 — Improved support for dark Qt themes.
* Fixed preview jumping to top during MathJax rendering.
* Issue #544 — Fixed QTextBrowser-based preview jumping.
* Issue #548 — Fixed opening files with spaces from QTextBrowser-based
preview.
* Issue #549 — Use `defaultCodec` setting by default when saving files;
correctly detect encoding for UTF-8 files with BOM.
## ReText 7.2.0 (2021-02-08)
* Dependency changes:
- Python ≥ 3.6 is now required.
- Qt and PyQt ≥ 5.11 are now required.
* General improvements:
- Added ability to show a side panel with directory tree (contributed by
Xavier Gouchet in #531).
- Added support for searching in the preview mode.
- When some text is selected and a quote, bracket or emphasis key is
pressed, the text is surrounded rather than replaced (contributed by
Daniel Venturini in #520).
- Added an option to fully highlight wrapped lines (contributed by
nihillum in #523).
- Improved current line highlighting for right-to-left text layout.
- Ordered list behavior can now be configured to repeat or increment the
list item number (contributed by Binokkio in #527).
- Added mnemonics to open the menus from keyboard (contributed by David
Hebbeker in #528).
- Added Apply button to the Preferences dialog (contributed by Amos Kong
in #543).
- Removed use of deprecated Python, Python-Markdown, Qt and PyQt API.
* Bugs fixed:
- Issue #507 — Improved the error message when trying to build ReText as a
wheel package.
- Issue #529 — Markup that intersects with code blocks is no longer
highlighted.
- PR #530 — Preview is no longer updated when it is not shown (contributed
by rhn in #530).
- Issue #533 — Fixed showing local images with Qt WebEngine 5.15.
* Translations updated:
- Arabic (contributed by ZamanOof).
- Chinese (China) (contributed by liulitchi).
- Dutch (contributed by Heimen Stoffels).
- Japanese (contributed by YAMADA Shinichirou).
- Persian (contributed by Hadi F).
- Polish (contributed by Maciej Haudek).
- Russian.
- Spanish (contributed by Félix Fischer).
- Swedish (contributed by Philip Andersen).
## ReText 7.1.0 (2020-04-04)
* General improvements:
- New files are now opened in new tabs by default, not new windows
(contributed by Daniele Scasciafratte in #476). This can be disabled
using `openFilesInExistingWindow` configuration option.
- Preferences dialog improvements: it now uses tabs; added a link to
configuration file (contributed by Xavier Gouchet in #327); clicking on
checkbox label now changes checkbox state.
- Return key now automatically continues quote blocks and ordered lists
(contributed by Xavier Gouchet in #298 and #326).
- It is now possible to close the current tab with Ctrl+W (contributed by
Xavier Gouchet in #283).
- Ctrl+wheel on editor now increases/decreases font size (contributed by
Xavier Gouchet in #328). Ctrl+wheel in preview zooms in/out (#400).
- Alt+Up/Down arrow now moves the current line up/down (contributed by
Xavier Gouchet in #337).
- Added “Jump to Line” feature, with Ctrl+G shortcut (contributed by
Xavier Gouchet in #382).
- Table mode improvements (contributed by Maurice van der Pot).
- “Paste Image” moved to a separate action, with Ctrl+Shift+V shortcut.
- Added “Insert table” dialog (contributed by Changhee Kim in #431).
- Clicking a link to nonexistent file now prompts the user to create it
(contributed by red-kite in #436 and Xavier Gouchet in #459).
- Added a menu action to insert images from filesystem (contributed by
Daniel Venturini in #500).
* New options added:
- `relativeLineNumbers` — count line numbers as relative to the current
line (contributed by Xavier Gouchet in #270).
- `documentStatsEnabled` — show text statistics in the lower left corner
of the editor (contributed by Xavier Gouchet in #268 and #338).
- `rightMarginWrap` — soft-wrap text at user specified margin line
(contributed by Oğuzhan Öğreden in #313).
- `paperSize` — set the default paper size for print or PDF export
(contributed by mray271 in #335).
- `recentDocumentsCount` — number of recent files to show in the menu
(contributed by red-kite in #407).
- `windowTitleFullPath` — show full path in window title (contributed by
red-kite in #429).
- `defaultPreviewState` — mode for new tabs: `editor`, `normal-preview` or
`live-preview` (contributed by red-kite in #435). It replaces the old
`livePreviewByDefault` option.
- `wideCursor` — make cursor as wide as characters.
* Bugs fixed:
- Issue #252 — Limit max-width of images to 100%.
- Issue #267 — setup.py now installs retext.svg icon.
- Issues #281, #469 — Autofill current filename for PDF export and Save As
dialogs (the Save As part contributed by Xavier Gouchet in #474).
- Issue #291 — Make sure search result does not overlap with stats/info
areas.
- Issue #301 — Made the Markdown include extension working.
- PR #315 — Fixed handling multi-line rows in reStructuredText tables in
table mode (contributed by R1dO).
- Issue #346 — Ctrl+F now focuses the search field, not closes the search
bar. To close the search bar, now the Escape key can be used.
- Issue #378 — Ensure that cursor is visible after resizes.
- Issue #397 — Only check whether .css file exists on initial page load.
- Issue #399 — Try to load libGL.so.1 before creating QApplication.
- Issue #408 — Fix printing with dark themes.
- Issue #409 — Make the WebKit renderer use disk cache.
- PRs #411, #417, #426, #494 — AppData file improvements (contributed by
scx).
- Issue #441 — Files reloading no longer triggers tab change.
- Issue #445 — Implemented PDF export for the WebEngine renderer.
- Issue #451 — Make the synchronized scroll implementation not break the
pymdownx.highlight extension.
- Issues #452, #497, #499 — Prevent pip from building wheels, as that
results in broken desktop files.
- Issues #467, #488 — WebEngine renderer broken with new Qt versions.
- Issue #468 — Include the stylesheet in exported HTML.
- Issue #479 — Display `*` in tab title when document is modified and
unsaved (contributed by Xavier Gouchet in #480).
- Issue #487 — Added a workaround for missing icons in Ubuntu 19.10 Yaru
theme.
- PR #496 — Enable HiDPI icons (contributed by Guo Yunhe).
* Translations updated:
- Chinese (China) (contributed by liulitchi and the Chinese team).
- Czech (contributed by David Kolibáč).
- Danish (contributed by scootergrisen).
- Dutch (contributed by Heimen Stoffels).
- Finnish (contributed by elguitar).
- German (contributed by Oliver A. Gubler in #370, Carsten Beck).
- Italian (contributed by Alessandro Menti).
- Korean (contributed by MukKim in #415).
- Portuguese (Brazil) (contributed by EdemarSantos).
- Portuguese (European) (contributed by Ricardo Simões in #278).
- Russian (contributed by Vladislav Glinsky, Виктор Ерухин).
- Serbian (contributed by Slobodan Simić).
- Spanish (contributed by Félix Fischer, Fito JB).
- Swedish (contributed by Philip Andersen).
- Ukrainian (contributed by Vladislav Glinsky).
## ReText 7.0 (2017-02-11)
* It is now possible to install ReText on Windows and macOS using a simple
`pip install ReText` command. This will pull PyQt5 wheels from PyPI,
and also download and extract the icons pack needed on this platforms.
Setup now also generates a wrapper batch script (this was contributed by
Hong-She Liang).
* Added experimental Qt WebEngine renderer, in addition to the existing
Qt WebKit one.
* The highlighter got support for reStructuredText links, field lists
and for Markdown and reStructuredText code spans.
* The replace option was added to the search toolbar.
* The WebKit and WebEngine previewers can now detect links to local HTML
files and open the corresponding source files in new tab if those are
found.
* The table mode is now able to insert inter-cell line breaks and new rows,
when Return and Shift-Return are pressed (respectively).
* ReText can now automatically detect files encoding when `chardet` module
is present (contributed by Hong-She Liang).
* A configuration option for automatically opening last files was added
(contributed by Hong-She Liang).
* A configuration option for hiding the tabs bar when there is only one tab
was added.
*Bugfix update 7.0.1 was released on 2017-06-25 with improved installation
procedure in setup.py, some crash fixes, and updated translations.*
*Bugfix update 7.0.2 was released on 2018-06-05, fixing many bugs. Most
importantly, issues with installation (#324, #363, #365), with synchronized
scrolling breaking code blocks highlighting (#299), with emoji support
(#357, #368), and with some lines disappearing after opening files (#345).*
*Bugfix update 7.0.3 was released on 2018-06-06 with minor changes and
fixed tarball contents.*
*Bugfix update 7.0.4 was released on 2018-09-23 with improved editor
performance (#360), fixed crash on Windows when pasting images (#385),
support for Python-Markdown 3.0, and updated translations.*
## ReText 6.0 (2016-05-10)
* The live preview now automatically scrolls to match its position with the
editor (only for Markdown).
* Markup conversion is now performed in a background process, improving
responsiveness of the editor.
* Images can now be copied and pasted into ReText (contributed by Bart
Clephas).
* Added a button to quickly close the search bar.
* Added basic CSS styling for tables.
* Replaced the tags box with the new “Formatting” box for Markdown
(contributed by Donato Marrazzo).
* Hitting return twice now ends the Markdown list.
* ReText now depends on version 2.0 or higher of pymarkups.
* The QtWebKit dependency is now optional (though still recommended).
*Bugfix update 6.0.1 was released on 2016-06-25, fixing some crashes and
making auto-save work again.*
*Bugfix update 6.0.2 was released on 2016-10-03, fixing an issue with
startup on Plasma and adding some new translations.*
## ReText 5.3 (2015-12-20)
* Tabs are now reorderable.
* All colors used in editor and highlighter are now configurable via the
configuration file.
* Links referencing other source files are now opened in ReText as new tabs
(feature contributed by Jan Korte).
* Code refactoring: some code moved to the new tab.py module, and some old
hacks dropped.
* The ReText logo is now installed to the data directory.
* Appstream metadata updated to a newer format.
* The desktop file no longer hardcodes the executable path (fix contributed
by Buo-Ren Lin).
## ReText 5.2 (2015-09-23)
* ReText now tries to load the icon theme from system settings if
Qt cannot auto-detect it.
* Added a GUI option to change the editor font.
* Added appdata file for appstream.
## ReText 5.1 (2015-06-30)
* Editor now displays cursor position in bottom-right corner.
* Added FakeVim mode (contributed by Lukas Holecek).
* ReText now shows a notification when the file was modified by another
application, to prevent data loss.
* WebPages generator removed (as better alternatives exist).
* Plain text mode removed.
* Added ability to configure file extensions for Markdown and
reStructuredText.
## ReText 5.0 (2014-07-26)
* Table editing mode.
* New settings: `colorSchemeFile` and `uiLanguage`.
* More settings are now configurable from GUI.
* Code base simplification and modernization.
* Dropped support for Qt 4.
* Added testsuite.
## ReText 4.1 (2013-08-18)
* Added configuration dialog.
* Added current line highlighting and line numbers support.
* Added support for PyQt5 and PySide libraries.
* Use new signals/slots syntax.
* Added option to select file encoding.
* Dropped support for Python 2 and support for running without WebKit
installed.
## ReText 4.0 (2012-12-06)
* Switch to pymarkups backend.
* Switch to Python 3 by default.
* Split `retext.py` to smaller files.
* MathJax support.
* Tab now inserts 4 spaces by default.
* Automatic indentation of new lines.
* External links are now opened in a web browser by default.
* Support for per-document CSS stylesheets.
## ReText 3.1 (2012-06-07)
* Spell checker suggestions.
* Markup-specific highlighting.
* Re-written parser and document-type logic.
* Lots of code clean-up.
## ReText 3.0 (2012-03-08)
* Python 3 support.
* Improved highlighter.
* Export extensions.
* Recent files menu.
* Spell checking improvements.
* Shortcuts for formatting.
* WebKit engine improvements.
## ReText 2.1 (2011-10-02)
* Ability to use QtWebKit.
* Splitter between edit and preview boxes.
* Support for opening several files via command-line.
* Support for GData 3 API and replacing existing document in Google Docs.
* Help page.
## ReText 2.0 (2011-08-04)
* Support for reStructuredText, with a GUI option to switch between
Markdown and reStructuredText.
* Text search.
* Global CSS file support.
* File auto-save support.
* WpGen 0.4, also with reST support.
* Getting title from ReST title or Markdown metadata.
* Changed the default extension for Markdown to `.mkd`.
* New “About” dialog.
## ReText 1.1 (2011-05-28)
* Added spell checker based on enchant.
* Added fullscreen mode.
## ReText 1.0 (2011-04-24)
* First stable release.
* Add “Select default font” option.
* Use HTML input when Markdown is not loaded.
* Add Ctrl+Shift+E sequence for Live preview.
## ReText 0.8 (2011-04-09)
* Add “Show folder”, “Markdown syntax examples” actions.
* Start even if Python-Markdown is not installed.
* Do not highlight quotes outside the tags.
* Save plain text documents with `*.txt` format.
## ReText 0.7 (2011-04-05)
* Tabs support.
* GUI for WpGen.
* Launching preview on Ctrl+E shortcut.
## ReText 0.4 (2011-03-13)
* First public beta release.
././@PaxHeader 0000000 0000000 0000000 00000000026 00000000000 010213 x ustar 00 22 mtime=1642950205.0
ReText-7.2.3/configuration.md 0000644 0001750 0001750 00000016611 00000000000 015537 0 ustar 00dmitry dmitry ReText stores all of its configuration in a text file. A path to that
file is printed to stdout during ReText startup.
Possible configuration options
==============================
Configuration options that you can set to improve your experience:
option name | type | description
----------- | ---- | -----------
`appStyleSheet` | file path | file containing a [Qt stylesheet file]
`autoSave` | boolean | whether to automatically save documents (default: false)
`defaultCodec` | string | name of encoding to use by default (default: use system encoding)
`defaultMarkup` | string | name of markup to use for unknown files
`defaultPreviewState` | string | mode for new tabs: `editor`, `normal-preview` or `live-preview` (default: `editor`)
`detectEncoding` | boolean | whether to automatically detect files encoding; needs chardet package (default: true)
`directoryPath` | string | the path to the root directory to display in the side panel if `showDirectoryTree` is true (default: `~`)
`documentStatsEnabled` | boolean | whether to show document stats (word count, character count) (default: false)
`editorFont` | string | font to use for editor: name (default: `monospace`)
`editorFontSize` | integer | font to use for editor: font size
`font` | string | font to use for previews: name
`fontSize` | integer | font to use for previews: font size
`handleWebLinks` | boolean | whether to use ReText preview area to open external links (default: false)
`hideToolBar` | boolean | whether to hide the toolbars from the UI (default: false)
`highlightCurrentLine` | string | current line highlight mode: `disabled`, `cursor-line` or `wrapped-line` (default: `disabled`)
`iconTheme` | string | name of the system icon theme to use (see below)
`lineNumbersEnabled` | boolean | whether to show column with line numbers in editor (default: false)
`markdownDefaultFileExtension` | string | default file extension for Markdown files (default: `.mkd`)
`openFilesInExistingWindow` | boolean | whether to open new files in the existing window (default: true)
`openLastFilesOnStartup` | boolean | whether to automatically open last documents on startup (default: false)
`orderedListMode` | string | editor behavior for lists continuation: `increment` or `repeat` (default: `increment`)
`paperSize` | string | name of default page size to use for print and export (e.g. A4, Letter)
`pygmentsStyle` | string | name of Pygments syntax highlighting style to use (default: `default`)
`recentDocumentsCount` | integer | number of recent files to show in the menu (default: 10)
`relativeLineNumbers` | boolean | whether to show line numbers as relative from the current line (default: false)
`restDefaultFileExtension` | string | default file extension for reStructuredText files (default: `.rst`)
`rightMargin` | integer | enable drawing of vertical line on defined position (or 0 to disable)
`rightMarginWrap` | boolean | enable soft wrap at specified margin line (default: false)
`saveWindowGeometry` | boolean | whether to restore window geometry from previous session (default: false)
`showDirectoryTree` | boolean | whether to show a directory tree on the left side of the window (default: false)
`spellCheck` | boolean | whether to enable spell checking
`spellCheckLocale` | string | short name of spell check locale to use (examples: `en_US`, `ru`, `pt_BR`)
`styleSheet` | file path | CSS file to use in preview area
`syncScroll` | boolean | whether to enable synchronized scrolling for Markdown (default: true)
`tabBarAutoHide` | boolean | whether to hide the tabs bar when only one tab is open (default: false)
`tabInsertsSpaces` | boolean | whether Tab key should insert spaces instead of tabs (default: true)
`tabWidth` | integer | the width of tab character (default: 4)
`uiLanguage` | string | short name of locale to use for interface (examples: `en_US`, `ru`, `pt_BR`)
`useFakeVim` | boolean | whether to use the FakeVim editor, if available (default: false)
`useWebEngine` | boolean | whether to use the WebEngine (Chromium) as HTML previewer (default: false)
`useWebKit` | boolean | whether to use the WebKit instead of QTextEdit as HTML previewer (default: false)
`wideCursor` | boolean | make cursor as wide as characters (default: false)
`windowTitleFullPath` | boolean | whether the window title should show the full path of file (default: false)
[Qt stylesheet file]: https://doc.qt.io/qt-5/stylesheet-reference.html
If the type is 'file path', then the value should be an absolute path
to a file.
These options can be set internally by ReText and should never be set
manually: `recentFileList`, `lastFileList`, `lastTabIndex` and `windowGeometry`.
Icon themes
===========
If ReText starts and does not show icons, go to Preferences dialog
and fill the "icon theme" field with the icon theme being used.
By default Qt (the toolkit used by ReText) can correctly detect icon
theme only on KDE and on a fixed list of Gtk+-based environments (when
the gtk platformtheme is used).
If you don't know name of your icon theme, look at the names of
subdirectories in `/usr/share/icons/` directory.
Color scheme setting
====================
It is possible to configure ReText highlighter to use custom colors set,
by providing these colors in a separate section in the configuration file.
The example of such section is:
[ColorScheme]
htmlTags=green
htmlSymbols=#ff8800
htmlComments=#abc
Color names for the text editor:
color name | main setting | description
---------- | ------------ | -----------
`marginLine` | `rightMargin` | the vertical right margin line
`currentLineHighlight` | `highlightCurrentLine` | highlighting of the text line being edited
`infoArea` | | the info box in the bottom-right corner
`statsArea` | `documentStatsEnabled` | the stats box in the bottom-right corner
`lineNumberArea` | `lineNumbersEnabled` | the line numbers area background
`lineNumberAreaText` | `lineNumbersEnabled` | the line numbers area foreground
Color names for the highlighter:
color name | description
---------- | -----------
`htmlTags` | HTML tags, e.g. ``
`htmlStrings` | string properties inside HTML tags, e.g. `"baz"` inside ``
`htmlSymbols` | HTML symbols, e.g. `&bar;`
`htmlComments` | HTML comments, e.g. ``
`markdownLinks` | Markdown links and images text, e.g. `foo` inside `[foo](http://example.com)`
`blockquotes` | blockquotes, e.g. `> quote` in Markdown
`codeSpans` | code spans, e.g. `` `code` `` in Markdown
`restDirectives` | reStructuredText directives, e.g. `.. math::`
`restRoles` | reStructuredText roles, e.g. `:math:`
`whitespaceOnEnd` | whitespace at line endings
././@PaxHeader 0000000 0000000 0000000 00000000034 00000000000 010212 x ustar 00 28 mtime=1643920524.1765156
ReText-7.2.3/data/ 0000755 0001750 0001750 00000000000 00000000000 013252 5 ustar 00dmitry dmitry ././@PaxHeader 0000000 0000000 0000000 00000000026 00000000000 010213 x ustar 00 22 mtime=1643919590.0
ReText-7.2.3/data/me.mitya57.ReText.appdata.xml 0000644 0001750 0001750 00000017126 00000000000 020525 0 ustar 00dmitry dmitry
me.mitya57.ReTextReTextSimple text editor for Markdown and reStructuredTextمحرر نصوص بسيط لمارك داون Markdown و ريستكرجر تيكست reStructuredTextEditor de Markdown i reStructuredText senzill alhora que potentJednoduchý editor pro Markdown a reStructuredTextGolygydd testun syml ar gyfer Markdown a reStructuredTextEnkel editor til Markdown og reStructuredTextEinfacher Texteditor für Markdown und reStructuredTextΑπλός επεξεργαστής κειμένου για Markdown και ReStructuredTextEditor básico de texto para Markdown y reStructuredTextLihtne tekstiredaktor Markdown ning reStructuredText süntaksiteleMarkdown et reStructuredText-erako editore sinpleیک ویرایشگر متن ساده برای متن های قالب Markdown و reStructuredTextYksinkertainen tekstieditori Markdownille ja reStructuredTextilleÉditeur de texte simple pour Markdown et reStructuredTextEgyszerű Markdown és reStructuredText szövegszerkesztőSemplice editor di testo per Markdown e reStructuredTextMarkdownとreStructuredTextのためのシンプルで強力なエディタEenvoudige teksteditor voor Markdown en reStructuredTextProsty edytor Markdown i reStructuredTextEditor simples para Markdown e reStructuredTextПростой редактор для Markdown и reStructuredTextJednoduchý textový editor pre Markdown a reStructuredTextЈедноставан уређивач за Markdown и reStructuredTextJednostavan uređivač za Markdown i reStructuredTextEnkel textredigerare för Markdown och reStructuredTextПростий текстовий редактор для Markdown та reStructuredText支持 Markdown 和 reStructuredText 语法的简易文本编辑器簡單高效的 Markdown 與 reStructuredText 編輯器
ReText is a text editor for plain text markup languages, such as Markdown and reStructuredText.
It supports tabs, live text preview, synchronized scrolling (for Markdown) and syntax highlighting.
ReText can export to HTML, ODT and PDF formats. It is also possible to write custom export extensions.
ReText ist ein Texteditor für vereinfachten Auszeichnungssprachen wie Markdown und reStructuredText.
Er unterstützt Reiter, Live-Vorschau, synchrones Scrollen (für Markdown) und Syntaxhervorhebung.
ReText kann Dokumente in HTML, ODT und PDF exportieren. Es ist auch möglich, benutzerdefinierte Export-Erweiterungen zu schreiben.
ReText — это текстовый редактор для языков разметки, таких как Markdown и reStructuredText.
Он поддерживает вкладки, живой просмотр, синхронную прокрутку (для Markdown) и подсветку синтаксиса.
ReText может экспортировать в форматы HTML, ODT и PDF. Также возможно написание собственных расширений экспорта.
https://github.com/retext-project/retextCC0GPL-2.0+retextme.mitya57.ReText.desktophttps://raw.githubusercontent.com/retext-project/retext/master/data/retext-kde5.pngretextDmitry Shachnevmitya57_AT_gmail.com
././@PaxHeader 0000000 0000000 0000000 00000000026 00000000000 010213 x ustar 00 22 mtime=1642949280.0
ReText-7.2.3/data/me.mitya57.ReText.desktop 0000644 0001750 0001750 00000004466 00000000000 017770 0 ustar 00dmitry dmitry [Desktop Entry]
Version=1.0
Name=ReText
Comment=Simple text editor for Markdown and reStructuredText
Comment[ar]=محرر نصوص بسيط لمارك داون Markdown و ريستكرجر تيكست reStructuredText
Comment[ca]=Editor de Markdown i reStructuredText senzill alhora que potent
Comment[cs]=Jednoduchý editor pro Markdown a reStructuredText
Comment[cy]=Golygydd testun syml ar gyfer Markdown a reStructuredText
Comment[da]=Enkel editor til Markdown og reStructuredText
Comment[de]=Einfacher Texteditor für Markdown und reStructuredText
Comment[el]=Απλός επεξεργαστής κειμένου για Markdown και ReStructuredText
Comment[es]=Editor básico de texto para Markdown y reStructuredText
Comment[et]=Lihtne tekstiredaktor Markdown ning reStructuredText süntaksitele
Comment[eu]=Markdown et reStructuredText-erako editore sinple
Comment[fa]=یک ویرایشگر متن ساده برای متن های قالب Markdown و reStructuredText
Comment[fi]=Yksinkertainen tekstieditori Markdownille ja reStructuredTextille
Comment[fr]=Éditeur de texte simple pour Markdown et reStructuredText
Comment[hu]=Egyszerű Markdown és reStructuredText szövegszerkesztő
Comment[it]=Semplice editor di testo per Markdown e reStructuredText
Comment[ja]=MarkdownとreStructuredTextのためのシンプルで強力なエディタ
Comment[nl]=Eenvoudige teksteditor voor Markdown en reStructuredText
Comment[pl]=Prosty edytor Markdown i reStructuredText
Comment[pt_BR]=Editor simples para Markdown e reStructuredText
Comment[ru]=Простой редактор для Markdown и reStructuredText
Comment[sk]=Jednoduchý textový editor pre Markdown a reStructuredText
Comment[sr]=Једноставан уређивач за Markdown и reStructuredText
Comment[sr@latin]=Jednostavan uređivač za Markdown i reStructuredText
Comment[sv]=Enkel textredigerare för Markdown och reStructuredText
Comment[uk]=Простий текстовий редактор для Markdown та reStructuredText
Comment[zh_CN]=支持 Markdown 和 reStructuredText 语法的简易文本编辑器
Comment[zh_TW]=簡單高效的 Markdown 與 reStructuredText 編輯器
Categories=Office;WordProcessor;
Exec=retext %F
Type=Application
Icon=retext
StartupWMClass=ReText
MimeType=text/markdown;text/x-rst;
Keywords=Text;Editor;Markdown;reStructuredText;
././@PaxHeader 0000000 0000000 0000000 00000000026 00000000000 010213 x ustar 00 22 mtime=1630777591.0
ReText-7.2.3/data/retext-kde5.png 0000644 0001750 0001750 00000374004 00000000000 016131 0 ustar 00dmitry dmitry PNG
IHDR B p zTXtRaw profile type exif xU
0D#f*JnTNp skҠ=D^uqwkt 3v<45V=oB,&7
iTXtXML:com.adobe.xmp
:A sBIT|d IDATxwtUwҀ$R=4" MPTP(V*v,(`Q@DAB
RIv# 96;3wf̖y;ooШF-io2*!"""""""b6ӳ2җm]bejԔ>U"""""""_Ψ0"""""""bL&J噱NDmT̆M[hXdeeۨdb=4kҐpvvJ@6mFzuHKK'&6ժAH DvN[lumXfǎг[Wl^T$.ٳ]paک=[&UT&sպ`A(ZE7'*"_,ii'rZbB\]pw'6>̣$&'g~RRص{G df$&yĤd38p0Bqsu3Z2LTDxiAUT
;#6>3frHyovmgOWݍ4|#=5g,||+I~~ddfa <